Skip to content

armgit / ECC

Public Imported from GitHub
0

The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.

feat(hooks): enforce project Hookify rules

wellkilod8b88172ff59
diff --git a/commands/hookify-help.md b/commands/hookify-help.md
index f30ae0048..486d60a51 100644
--- a/commands/hookify-help.md
+++ b/commands/hookify-help.md
@@ -7,6 +7,8 @@ Display comprehensive hookify documentation.
## Hook System Overview
Hookify creates rule files that integrate with Claude Code's hook system to prevent unwanted behaviors.
+ECC's built-in runtime loads these rules automatically while plugin hooks are
+enabled; installing a separate Hookify plugin is not required.
### Event Types
@@ -44,3 +46,13 @@ Supports multiple lines.
- for `bash`, match against the full command string
- for `file`, match against the file path
- test patterns before deploying
+- avoid nested quantifiers such as `(a+)+`; the runtime rejects unsafe regexes
+- every regex evaluation also has a 25 ms hard timeout
+- malformed or oversized rules fail open with a diagnostic so one bad local rule cannot disable all hooks
+
+### Action Behavior
+
+- `warn` adds the rule message to Claude's context and allows processing to continue
+- `block` denies matching shell/file actions before execution
+- `block` on prompt, post-tool, or stop events uses that event's structured block decision
+- stop rules are skipped when `stop_hook_active` is already true to prevent loops
diff --git a/commands/hookify.md b/commands/hookify.md
index 80969d8cd..c5d676d89 100644
--- a/commands/hookify.md
+++ b/commands/hookify.md
@@ -48,3 +48,5 @@ Message shown when rule triggers.
### Step 4: Confirm
Report created rules and how to manage them with `/hookify-list` and `/hookify-configure`.
+ECC's built-in hook runtime enforces enabled rules automatically; no separate
+Hookify plugin or Python runtime is required.
diff --git a/hooks/README.md b/hooks/README.md
index 144bc89ad..a690e7c74 100644
--- a/hooks/README.md
+++ b/hooks/README.md
@@ -9,7 +9,8 @@ User request → Claude picks a tool → PreToolUse hook runs → Tool executes
```
- **PreToolUse** hooks run before the tool executes. They can **block** (exit code 2) or **warn** (stderr without blocking).
-- **PostToolUse** hooks run after the tool completes. They can analyze output but cannot block.
+- **PostToolUse** hooks run after the tool completes. They can analyze output and return feedback before Claude continues.
+- **UserPromptSubmit** hooks run before Claude processes a user prompt.
- **Stop** hooks run after each Claude response.
- **SessionStart/SessionEnd** hooks run at session lifecycle boundaries.
- **PreCompact** hooks run before context compaction, useful for saving state.
@@ -49,6 +50,7 @@ idempotent updates and safe uninstall. On Windows, the Claude config root is
| **Pre-commit quality check** | `Bash` | Runs quality checks before `git commit`: lints staged files, validates commit message format when provided via `-m/--message`, detects console.log/debugger/secrets | 2 (blocks critical) / 0 (warns) |
| **Doc file warning** | `Write` | Warns about non-standard `.md`/`.txt` files (allows README, CLAUDE, CONTRIBUTING, CHANGELOG, LICENSE, SKILL, docs/, skills/); cross-platform path handling | 0 (warns) |
| **Strategic compact** | `Edit\|Write` | Suggests manual `/compact` at logical intervals (every ~50 tool calls) | 0 (warns) |
+| **Hookify runtime** | `.*` | Evaluates enabled project-local Hookify rules before shell and file tools | 0 (structured warn/block decision) |
### PostToolUse Hooks
@@ -61,14 +63,17 @@ idempotent updates and safe uninstall. On Windows, the Claude config root is
| **Prettier format** | `Edit` | Auto-formats JS/TS files with Prettier after edits |
| **TypeScript check** | `Edit` | Runs `tsc --noEmit` after editing `.ts`/`.tsx` files |
| **console.log warning** | `Edit` | Warns about `console.log` statements in edited files |
+| **Hookify runtime** | `.*` | Evaluates project-local Hookify rules against completed shell and file tools |
### Lifecycle Hooks
| Hook | Event | What It Does |
|------|-------|-------------|
| **Session start** | `SessionStart` | Loads previous context and detects package manager |
+| **Hookify prompt rules** | `UserPromptSubmit` | Evaluates prompt rules before the user prompt reaches Claude |
| **Plan Canvas sessions** | `SessionStart` | Surfaces open Plan Canvas browser reviews so a fresh session can resume the loop |
| **Pre-compact** | `PreCompact` | Saves state before context compaction |
+| **Hookify completion rules** | `Stop` | Warns or requests another turn when an enabled completion rule matches |
| **Console.log audit** | `Stop` | Checks all modified files for `console.log` after each response |
| **Session summary** | `Stop` | Persists session state when transcript path is available |
| **Pattern extraction** | `Stop` | Evaluates session for extractable patterns (continuous learning) |
@@ -141,6 +146,20 @@ The Claude plugin exposes the same choices as the personal `hooks_enabled` and
`hook_profile` settings. Run `ecc setup --mode claude-plugin` to install or
update the plugin and change those preferences.
+### Hookify Rule Runtime
+
+ECC loads enabled `.claude/hookify.*.local.md` files directly; no separate
+Hookify plugin or Python runtime is required. Rules support `bash`, `file`,
+`prompt`, `stop`, and `all` events, plus either a simple regex `pattern` or an
+AND-combined `conditions` list. `warn` adds visible context for Claude while
+allowing the action. `block` denies a matching `PreToolUse` call and uses the
+event's blocking decision contract for prompt, post-tool, and stop events.
+
+Rule loading is project-scoped and bounded. Symlinked, oversized, malformed,
+or unsafe-regex rule files are skipped with a diagnostic instead of breaking
+the entire hook chain. Every regex evaluation also has a 25 ms hard timeout.
+Stop rules ignore `stop_hook_active: true` to avoid continuation loops.
+
### Writing Your Own Hook
Hooks are shell commands that receive tool input as JSON on stdin and must output JSON on stdout.
diff --git a/hooks/hooks.json b/hooks/hooks.json
index 62053904e..fa384412a 100644
--- a/hooks/hooks.json
+++ b/hooks/hooks.json
@@ -106,6 +106,31 @@
],
"description": "Fact-forcing gate: block first Edit/Write/MultiEdit per file and demand investigation (importers, data schemas, user instruction) before allowing",
"id": "pre:edit-write:gateguard-fact-force"
+ },
+ {
+ "matcher": ".*",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node -e \"const p=require('path');const r=(function(){var p=require('path'),f=require('fs'),o=require('os');var e=process.env.CLAUDE_PLUGIN_ROOT;if(e&&e.trim())return e.trim();var d=p.join(o.homedir(),'.claude');function L(x){try{return require(p.join(x,'scripts','lib','resolve-ecc-root')).resolveEccRoot()}catch(_){return null}}var r=L(d);if(r)return r;var s=['ecc','ecc@ecc','marketplaces/ecc','everything-claude-code','everything-claude-code@everything-claude-code','marketplaces/everything-claude-code'];for(var i=0;i<s.length;i++){r=L(p.join(d,'plugins',s[i]));if(r)return r}try{var g=['ecc','everything-claude-code'];for(var j=0;j<g.length;j++){var c=p.join(d,'plugins','cache',g[j]);var O=f.readdirSync(c);for(var k=0;k<O.length;k++){var q=p.join(c,O[k]);var V=f.readdirSync(q);for(var m=0;m<V.length;m++){r=L(p.join(q,V[m]));if(r)return r}}}}catch(_){}return d})();const s=p.join(r,'scripts/hooks/plugin-hook-bootstrap.js');process.env.CLAUDE_PLUGIN_ROOT=r;process.argv.splice(1,0,s);require(s)\" node scripts/hooks/run-with-flags.js pre:hookify-runtime scripts/hooks/hookify-runtime.js minimal,standard,strict",
+ "timeout": 10
+ }
+ ],
+ "description": "Evaluate project-local Hookify rules before Bash, PowerShell, and file tools run",
+ "id": "pre:hookify-runtime"
+ }
+ ],
+ "UserPromptSubmit": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node -e \"const p=require('path');const r=(function(){var p=require('path'),f=require('fs'),o=require('os');var e=process.env.CLAUDE_PLUGIN_ROOT;if(e&&e.trim())return e.trim();var d=p.join(o.homedir(),'.claude');function L(x){try{return require(p.join(x,'scripts','lib','resolve-ecc-root')).resolveEccRoot()}catch(_){return null}}var r=L(d);if(r)return r;var s=['ecc','ecc@ecc','marketplaces/ecc','everything-claude-code','everything-claude-code@everything-claude-code','marketplaces/everything-claude-code'];for(var i=0;i<s.length;i++){r=L(p.join(d,'plugins',s[i]));if(r)return r}try{var g=['ecc','everything-claude-code'];for(var j=0;j<g.length;j++){var c=p.join(d,'plugins','cache',g[j]);var O=f.readdirSync(c);for(var k=0;k<O.length;k++){var q=p.join(c,O[k]);var V=f.readdirSync(q);for(var m=0;m<V.length;m++){r=L(p.join(q,V[m]));if(r)return r}}}}catch(_){}return d})();const s=p.join(r,'scripts/hooks/plugin-hook-bootstrap.js');process.env.CLAUDE_PLUGIN_ROOT=r;process.argv.splice(1,0,s);require(s)\" node scripts/hooks/run-with-flags.js prompt:hookify-runtime scripts/hooks/hookify-runtime.js minimal,standard,strict",
+ "timeout": 10
+ }
+ ],
+ "description": "Evaluate project-local Hookify prompt rules before a user prompt is processed",
+ "id": "prompt:hookify-runtime"
}
],
"PreCompact": [
@@ -197,6 +222,18 @@
}
],
"Stop": [
+ {
+ "matcher": ".*",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node -e \"const fs=require('fs');const path=require('path');const {spawnSync}=require('child_process');const raw=fs.readFileSync(0,'utf8');const finish=(out,err,code)=>{let pending=1;const done=()=>{pending-=1;if(pending===0)process.exit(code);};if(out){pending+=1;process.stdout.write(out,done);}if(err){pending+=1;process.stderr.write(err,done);}process.nextTick(done);};const rel=path.join('scripts','hooks','run-with-flags.js');const root=(function(){var p=require('path'),f=require('fs'),o=require('os');var e=process.env.CLAUDE_PLUGIN_ROOT;if(e&&e.trim())return e.trim();var d=p.join(o.homedir(),'.claude');function L(x){try{return require(p.join(x,'scripts','lib','resolve-ecc-root')).resolveEccRoot()}catch(_){return null}}var r=L(d);if(r)return r;var s=['ecc','ecc@ecc','marketplaces/ecc','everything-claude-code','everything-claude-code@everything-claude-code','marketplaces/everything-claude-code'];for(var i=0;i<s.length;i++){r=L(p.join(d,'plugins',s[i]));if(r)return r}try{var g=['ecc','everything-claude-code'];for(var j=0;j<g.length;j++){var c=p.join(d,'plugins','cache',g[j]);var O=f.readdirSync(c);for(var k=0;k<O.length;k++){var q=p.join(c,O[k]);var V=f.readdirSync(q);for(var m=0;m<V.length;m++){r=L(p.join(q,V[m]));if(r)return r}}}}catch(_){}return d})();const script=path.join(root,rel);if(fs.existsSync(script)){const result=spawnSync(process.execPath,[script,'stop:hookify-runtime','scripts/hooks/hookify-runtime.js','minimal,standard,strict'],{input:raw,encoding:'utf8',env:process.env,cwd:process.cwd(),timeout:30000,maxBuffer:16*1024*1024});const failed=result.error||result.status===null||result.signal;const stdout=!failed&&typeof result.stdout==='string'?result.stdout:'';let stderr=typeof result.stderr==='string'?result.stderr:'';let code=Number.isInteger(result.status)?result.status:0;if(failed){const reason=result.error?result.error.message:(result.signal?'signal '+result.signal:'missing exit status');stderr+='[Stop] ERROR: hook runner failed: '+reason+String.fromCharCode(10);code=1;}finish(stdout,stderr,code);}else{finish(raw,'[Stop] WARNING: could not resolve ECC plugin root; skipping hook'+String.fromCharCode(10),0);}\"",
+ "timeout": 10
+ }
+ ],
+ "description": "Evaluate project-local Hookify completion rules before Claude stops",
+ "id": "stop:hookify-runtime"
+ },
{
"matcher": ".*",
"hooks": [
diff --git a/scripts/hooks/hookify-runtime.js b/scripts/hooks/hookify-runtime.js
new file mode 100644
index 000000000..7a83f7dcc
--- /dev/null
+++ b/scripts/hooks/hookify-runtime.js
@@ -0,0 +1,593 @@
+#!/usr/bin/env node
+/**
+ * ECC-native Hookify runtime.
+ *
+ * Loads project-local Hookify markdown rules and evaluates them against
+ * Claude Code lifecycle payloads. Invalid configuration fails open with a
+ * diagnostic; matched rules use structured hook output.
+ */
+
+'use strict';
+
+const fs = require('fs');
+const path = require('path');
+const { StringDecoder } = require('string_decoder');
+const vm = require('vm');
+
+const MAX_STDIN_BYTES = 1024 * 1024;
+const MAX_RULE_BYTES = 64 * 1024;
+const MAX_RULES = 100;
+const MAX_PATTERN_CHARS = 512;
+const MAX_MESSAGE_CHARS = 8000;
+const MAX_FIELD_CHARS = 64 * 1024;
+const REGEX_TIMEOUT_MS = 25;
+const REGEX_TEST_SCRIPT = new vm.Script('values.some(value => regex.test(value))');
+const VALID_EVENTS = new Set(['bash', 'file', 'stop', 'prompt', 'all']);
+const VALID_ACTIONS = new Set(['warn', 'block']);
+const VALID_OPERATORS = new Set([
+ 'regex_match', 'contains', 'equals', 'not_contains', 'starts_with', 'ends_with',
+]);
+const VALID_FIELDS = new Set([
+ 'command', 'content', 'file_path', 'last_assistant_message',
+ 'new_string', 'new_text', 'old_string', 'old_text', 'prompt',
+ 'reason', 'tool_name', 'tool_response', 'user_prompt',
+]);
+const VALID_RULE_KEYS = new Set([
+ 'name', 'enabled', 'event', 'action', 'pattern', 'conditions', 'tool_matcher',
+]);
+const VALID_CONDITION_KEYS = new Set(['field', 'operator', 'pattern']);
+
+function sanitizeDiagnostic(value) {
+ return String(value || '')
+ // eslint-disable-next-line no-control-regex
+ .replace(/\x1b(?:\[[0-9;?]*[A-Za-z]|\][^\x07\x1b]*(?:\x07|\x1b\\)|\([A-Z]|[A-Z])/g, '')
+ .replace(/[^\x20-\x7E]/g, '?')
+ .slice(0, 500);
+}
+
+function sanitizeMessage(value) {
+ return String(value || '')
+ // eslint-disable-next-line no-control-regex
+ .replace(/\x1b(?:\[[0-9;?]*[A-Za-z]|\][^\x07\x1b]*(?:\x07|\x1b\\)|\([A-Z]|[A-Z])/g, '')
+ // Keep newline and tab for Markdown while dropping other control bytes.
+ // eslint-disable-next-line no-control-regex
+ .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '')
+ .trim();
+}
+
+function diagnostic(fileName, message) {
+ return '[Hookify] ' + sanitizeDiagnostic(fileName) + ': ' + sanitizeDiagnostic(message);
+}
+
+function isPlainObject(value) {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
+ const prototype = Object.getPrototypeOf(value);
+ return prototype === Object.prototype || prototype === null;
+}
+
+function extractFrontmatter(source) {
+ const normalized = String(source || '').replace(/^\uFEFF/, '');
+ const match = normalized.match(/^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/);
+ if (!match) return null;
+ return { yaml: match[1], message: normalized.slice(match[0].length) };
+}
+
+function parseScalar(rawValue) {
+ const value = String(rawValue || '').trim();
+ if (value.toLowerCase() === 'true') return true;
+ if (value.toLowerCase() === 'false') return false;
+ if (value.startsWith('"') && value.endsWith('"')) {
+ try {
+ return JSON.parse(value);
+ } catch {
+ throw new Error('invalid double-quoted scalar');
+ }
+ }
+ if (value.startsWith("'") && value.endsWith("'")) {
+ return value.slice(1, -1).replace(/''/g, "'");
+ }
+ if (value.startsWith('"') || value.endsWith('"') || value.startsWith("'") || value.endsWith("'")) {
+ throw new Error('unterminated quoted scalar');
+ }
+ if (value.startsWith('[') || value.startsWith('{')) {
+ throw new Error('flow collections are not supported in Hookify frontmatter');
+ }
+ return value;
+}
+
+function parseRuleFrontmatter(source) {
+ const result = Object.create(null);
+ const seenTopLevel = new Set();
+ let conditions = null;
+ let currentCondition = null;
+
+ for (const rawLine of String(source || '').split(/\r?\n/)) {
+ const trimmed = rawLine.trim();
+ if (!trimmed || trimmed.startsWith('#')) continue;
+ const indent = rawLine.length - rawLine.trimStart().length;
+
+ if (indent === 0) {
+ currentCondition = null;
+ const separator = rawLine.indexOf(':');
+ if (separator <= 0) throw new Error('invalid top-level frontmatter line');
+ const key = rawLine.slice(0, separator).trim();
+ const rawValue = rawLine.slice(separator + 1);
+ if (seenTopLevel.has(key)) throw new Error('duplicate frontmatter key: ' + key);
+ seenTopLevel.add(key);
+ if (key === 'conditions') {
+ if (rawValue.trim()) throw new Error('conditions must be a YAML list');
+ conditions = [];
+ result.conditions = conditions;
+ } else {
+ result[key] = parseScalar(rawValue);
+ }
+ continue;
+ }
+
+ if (!conditions) throw new Error('nested values are only supported under conditions');
+ if (trimmed.startsWith('- ')) {
+ const item = trimmed.slice(2);
+ const separator = item.indexOf(':');
+ if (separator <= 0) throw new Error('invalid condition list item');
+ currentCondition = Object.create(null);
+ const key = item.slice(0, separator).trim();
+ currentCondition[key] = parseScalar(item.slice(separator + 1));
+ conditions.push(currentCondition);
+ continue;
+ }
+ if (!currentCondition) throw new Error('condition property is missing a list item');
+ const separator = trimmed.indexOf(':');
+ if (separator <= 0) throw new Error('invalid condition property');
+ const key = trimmed.slice(0, separator).trim();
+ if (Object.prototype.hasOwnProperty.call(currentCondition, key)) {
+ throw new Error('duplicate condition key: ' + key);
+ }
+ currentCondition[key] = parseScalar(trimmed.slice(separator + 1));
+ }
+
+ return result;
+}
+
+function isSafeRegexSource(pattern) {
+ if (!pattern || pattern.length > MAX_PATTERN_CHARS) return false;
+ if (/\\[1-9]/.test(pattern) || /\(\?<([=!])/.test(pattern)) return false;
+ // Reject common catastrophic nested-quantifier and ambiguous-alternation
+ // shapes such as (a+)+, ([a-z]+){2,}, and (a|aa)+.
+ if (/(?:\([^()]*(?:\*|\+|\{\d+(?:,\d*)?\})[^()]*\)|\[[^\]]*\](?:\*|\+|\{\d+(?:,\d*)?\}))\s*(?:\*|\+|\{\d+(?:,\d*)?\})/.test(pattern)) {
+ return false;
+ }
+ if (/\([^()]*(?:\|)[^()]*\)\s*(?:\*|\+|\{\d+(?:,\d*)?\})/.test(pattern)) {
+ return false;
+ }
+ if (/(?:\.\*|\.\+)(?:[^|)]{0,32})(?:\.\*|\.\+)/.test(pattern)) return false;
+ // Reject quantified groups containing any quantifier, including nested
+ // parentheses that the simpler one-level detector cannot model.
+ const quantifiedGroup = /\)\s*(?:\*|\+|\{\d+(?:,\d*)?\})/g;
+ let match;
+ while ((match = quantifiedGroup.exec(pattern)) !== null) {
+ let depth = 1;
+ let cursor = match.index - 1;
+ for (; cursor >= 0; cursor -= 1) {
+ if (pattern[cursor] === ')' && pattern[cursor - 1] !== '\\') depth += 1;
+ if (pattern[cursor] === '(' && pattern[cursor - 1] !== '\\') {
+ depth -= 1;
+ if (depth === 0) break;
+ }
+ }
+ if (cursor >= 0) {
+ const groupBody = pattern.slice(cursor + 1, match.index);
+ if (/(?:^|[^\\])(?:\*|\+|\{\d+(?:,\d*)?\})/.test(groupBody)) return false;
+ }
+ }
+ return true;
+}
+
+function compileRegex(pattern) {
+ if (typeof pattern !== 'string' || !isSafeRegexSource(pattern)) {
+ throw new Error('pattern must be a non-empty bounded regex without nested quantifiers');
+ }
+ try {
+ return new RegExp(pattern, 'i');
+ } catch {
+ // Do not echo the user-authored pattern into hook diagnostics. Patterns
+ // may intentionally target secret-shaped strings.
+ throw new Error('invalid regex syntax');
+ }
+}
+
+function testRegex(regex, textOrValues) {
+ const values = Array.isArray(textOrValues) ? textOrValues : [textOrValues];
+ try {
+ return REGEX_TEST_SCRIPT.runInNewContext(
+ { regex, values },
+ { timeout: REGEX_TIMEOUT_MS }
+ );
+ } catch (error) {
+ if (error && error.code === 'ERR_SCRIPT_EXECUTION_TIMEOUT') {
+ const timeoutError = new Error('regex evaluation exceeded ' + REGEX_TIMEOUT_MS + 'ms');
+ timeoutError.code = 'HOOKIFY_REGEX_TIMEOUT';
+ throw timeoutError;
+ }
+ throw error;
+ }
+}
+
+function normalizeCondition(value) {
+ if (!isPlainObject(value)) throw new Error('conditions must contain objects');
+ const unknownKeys = Object.keys(value).filter(key => !VALID_CONDITION_KEYS.has(key));
+ if (unknownKeys.length > 0) throw new Error('unsupported condition key: ' + unknownKeys[0]);
+ const field = String(value.field || '').trim();
+ const operator = String(value.operator || 'regex_match').trim();
+ const pattern = value.pattern;
+ if (!VALID_FIELDS.has(field)) throw new Error('unsupported condition field: ' + (field || '<empty>'));
+ if (!VALID_OPERATORS.has(operator)) throw new Error('unsupported condition operator: ' + (operator || '<empty>'));
+ if (typeof pattern !== 'string' || pattern.length > MAX_PATTERN_CHARS) {
+ throw new Error('condition pattern must be a bounded string');
+ }
+ return Object.freeze({
+ field,
+ operator,
+ pattern,
+ regex: operator === 'regex_match' ? compileRegex(pattern) : null,
+ });
+}
+
+function normalizeRule(frontmatter, message, sourcePath) {
+ if (!isPlainObject(frontmatter)) throw new Error('frontmatter must be a YAML mapping');
+ const unknownKeys = Object.keys(frontmatter).filter(key => !VALID_RULE_KEYS.has(key));
+ if (unknownKeys.length > 0) throw new Error('unsupported frontmatter key: ' + unknownKeys[0]);
+ const name = String(frontmatter.name || '').trim();
+ const event = String(frontmatter.event || 'all').trim().toLowerCase();
+ const action = String(frontmatter.action || 'warn').trim().toLowerCase();
+ const toolMatcher = frontmatter.tool_matcher === undefined
+ ? null
+ : String(frontmatter.tool_matcher || '').trim();
+
+ if (!name || name.length > 100) throw new Error('name must contain 1-100 characters');
+ if (frontmatter.enabled !== undefined && typeof frontmatter.enabled !== 'boolean') {
+ throw new Error('enabled must be true or false');
+ }
+ if (!VALID_EVENTS.has(event)) throw new Error('unsupported event: ' + event);
+ if (!VALID_ACTIONS.has(action)) throw new Error('unsupported action: ' + action);
+ if (toolMatcher !== null && (!toolMatcher || toolMatcher.length > MAX_PATTERN_CHARS)) {
+ throw new Error('tool_matcher must be a bounded non-empty string');
+ }
+
+ const conditions = frontmatter.conditions === undefined ? [] : frontmatter.conditions;
+ if (!Array.isArray(conditions) || conditions.length > 16) {
+ throw new Error('conditions must be an array with at most 16 entries');
+ }
+ const normalizedConditions = conditions.map(normalizeCondition);
+ const simplePattern = frontmatter.pattern;
+ if (normalizedConditions.length === 0 && typeof simplePattern !== 'string') {
+ throw new Error('rule requires pattern or conditions');
+ }
+ const regex = normalizedConditions.length === 0 ? compileRegex(simplePattern) : null;
+ const safeMessage = sanitizeMessage(message);
+ if (!safeMessage) throw new Error('message body must not be empty');
+
+ return Object.freeze({
+ name,
+ enabled: frontmatter.enabled !== false,
+ event,
+ action,
+ pattern: typeof simplePattern === 'string' ? simplePattern : null,
+ regex,
+ conditions: Object.freeze(normalizedConditions),
+ toolMatcher,
+ message: safeMessage,
+ sourcePath,
+ });
+}
+
+function readRuleFile(filePath) {
+ const stat = fs.lstatSync(filePath);
+ if (stat.isSymbolicLink()) throw new Error('symbolic links are not loaded');
+ if (!stat.isFile()) throw new Error('rule path is not a regular file');
+ if (stat.size > MAX_RULE_BYTES) throw new Error('rule exceeds ' + MAX_RULE_BYTES + ' bytes');
+
+ const noFollow = fs.constants.O_NOFOLLOW || 0;
+ const fd = fs.openSync(filePath, fs.constants.O_RDONLY | noFollow);
+ try {
+ const openedStat = fs.fstatSync(fd);
+ if (!openedStat.isFile() || openedStat.size > MAX_RULE_BYTES) {
+ throw new Error('rule exceeds ' + MAX_RULE_BYTES + ' bytes or is not a regular file');
+ }
+ const source = fs.readFileSync(fd, 'utf8');
+ const document = extractFrontmatter(source);
+ if (!document) throw new Error('missing YAML frontmatter');
+ const frontmatter = parseRuleFrontmatter(document.yaml);
+ return normalizeRule(frontmatter, document.message, filePath);
+ } finally {
+ fs.closeSync(fd);
+ }
+}
+
+function loadRules(projectRoot) {
+ const rules = [];
+ const diagnostics = [];
+ const rulesDir = path.join(path.resolve(projectRoot), '.claude');
+ let entries;
+ try {
+ const dirStat = fs.lstatSync(rulesDir);
+ if (dirStat.isSymbolicLink() || !dirStat.isDirectory()) {
+ return { rules, diagnostics: [diagnostic('.claude', 'rule directory must be a real directory')] };
+ }
+ entries = fs.readdirSync(rulesDir, { withFileTypes: true });
+ } catch (error) {
+ if (error && error.code === 'ENOENT') return { rules, diagnostics };
+ return { rules, diagnostics: [diagnostic('.claude', error.message)] };
+ }
+
+ const candidates = entries
+ .filter(entry => /^hookify\.[^/\\]+\.local\.md$/.test(entry.name))
+ .sort((left, right) => left.name.localeCompare(right.name));
+ if (candidates.length > MAX_RULES) {
+ diagnostics.push(diagnostic('.claude', 'only the first ' + MAX_RULES + ' Hookify rules are loaded'));
+ }
+ for (const entry of candidates.slice(0, MAX_RULES)) {
+ try {
+ const rule = readRuleFile(path.join(rulesDir, entry.name));
+ if (rule.enabled) rules.push(rule);
+ } catch (error) {
+ diagnostics.push(diagnostic(entry.name, error.message));
+ }
+ }
+ return { rules, diagnostics };
+}
+
+function resolveProjectRoot(cwd, env) {
+ const configured = String(env.CLAUDE_PROJECT_DIR || '').trim();
+ return path.resolve(configured || cwd || process.cwd());
+}
+
+function toBoundedText(value) {
+ if (typeof value === 'string') return value.slice(0, MAX_FIELD_CHARS);
+ if (value === undefined || value === null) return '';
+ try {
+ return JSON.stringify(value).slice(0, MAX_FIELD_CHARS);
+ } catch {
+ return String(value).slice(0, MAX_FIELD_CHARS);
+ }
+}
+
+function fileValues(toolInput) {
+ const values = [toolInput.file_path, toolInput.path, toolInput.content, toolInput.new_string];
+ if (Array.isArray(toolInput.edits)) {
+ for (const edit of toolInput.edits.slice(0, 100)) {
+ if (!isPlainObject(edit)) continue;
+ values.push(edit.file_path, edit.path, edit.content, edit.new_string);
+ }
+ }
+ return values.map(toBoundedText).filter(Boolean);
+}
+
+function eventAlias(input) {
+ const hookEvent = String(input.hook_event_name || '');
+ if (hookEvent === 'UserPromptSubmit') return 'prompt';
+ if (hookEvent === 'Stop') return 'stop';
+ if (hookEvent !== 'PreToolUse' && hookEvent !== 'PostToolUse') return null;
+ const toolName = String(input.tool_name || '').toLowerCase();
+ if (toolName === 'bash' || toolName === 'powershell') return 'bash';
+ if (toolName === 'write' || toolName === 'edit' || toolName === 'multiedit') return 'file';
+ return 'tool';
+}
+
+function simpleValues(rule, input, alias) {
+ const toolInput = isPlainObject(input.tool_input) ? input.tool_input : {};
+ if (rule.event === 'all') {
+ const values = [
+ input.prompt, input.user_prompt, input.reason, input.last_assistant_message,
+ input.tool_name, toolInput.command, ...fileValues(toolInput), input.tool_response,
+ ].map(toBoundedText).filter(Boolean);
+ return values.length > 0 ? values : [''];
+ }
+ if (alias === 'bash') return [toBoundedText(toolInput.command)].filter(Boolean);
+ if (alias === 'file') return fileValues(toolInput);
+ if (alias === 'prompt') return [toBoundedText(input.prompt || input.user_prompt)].filter(Boolean);
+ if (alias === 'stop') {
+ const stopValues = [toBoundedText(input.last_assistant_message), toBoundedText(input.reason)];
+ return stopValues.some(Boolean) ? stopValues.filter(Boolean) : [''];
+ }
+ return [];
+}
+
+function fieldValue(field, input) {
+ const toolInput = isPlainObject(input.tool_input) ? input.tool_input : {};
+ const edits = Array.isArray(toolInput.edits) ? toolInput.edits.filter(isPlainObject).slice(0, 100) : [];
+ const editField = key => edits.map(edit => edit[key]).map(toBoundedText).filter(Boolean);
+ const present = value => (value === undefined || value === null ? null : toBoundedText(value));
+ const joined = values => {
+ const available = values.filter(value => value !== undefined && value !== null);
+ return available.length > 0 ? available.map(toBoundedText).join('\n') : null;
+ };
+ switch (field) {
+ case 'command': return present(toolInput.command);
+ case 'file_path': return joined([toolInput.file_path, toolInput.path, ...editField('file_path'), ...editField('path')]);
+ case 'content': return joined([toolInput.content, toolInput.new_string, ...editField('content'), ...editField('new_string')]);
+ case 'new_text':
+ case 'new_string': return joined([toolInput.new_string, ...editField('new_string')]);
+ case 'old_text':
+ case 'old_string': return joined([toolInput.old_string, ...editField('old_string')]);
+ case 'prompt':
+ case 'user_prompt': return present(input.prompt ?? input.user_prompt);
+ case 'last_assistant_message': return present(input.last_assistant_message);
+ case 'reason': return present(input.reason);
+ case 'tool_name': return present(input.tool_name);
+ case 'tool_response': return present(input.tool_response);
+ default: return null;
+ }
+}
+
+function matchesTool(matcher, toolName) {
+ if (!matcher || matcher === '*') return true;
+ const actual = String(toolName || '').toLowerCase();
+ return matcher.split('|').map(value => value.trim().toLowerCase()).filter(Boolean).includes(actual);
+}
+
+function matchesCondition(condition, input) {
+ const value = fieldValue(condition.field, input);
+ if (value === null) return false;
+ switch (condition.operator) {
+ case 'regex_match': return testRegex(condition.regex, value);
+ case 'contains': return value.includes(condition.pattern);
+ case 'equals': return value === condition.pattern;
+ case 'not_contains': return !value.includes(condition.pattern);
+ case 'starts_with': return value.startsWith(condition.pattern);
+ case 'ends_with': return value.endsWith(condition.pattern);
+ default: return false;
+ }
+}
+
+function conditionCandidates(input) {
+ const toolInput = isPlainObject(input.tool_input) ? input.tool_input : {};
+ if (String(input.tool_name || '').toLowerCase() !== 'multiedit' || !Array.isArray(toolInput.edits)) {
+ return [input];
+ }
+ const edits = toolInput.edits.filter(isPlainObject).slice(0, 100);
+ if (edits.length === 0) return [input];
+ return edits.map(edit => ({
+ ...input,
+ tool_input: {
+ ...toolInput,
+ ...edit,
+ edits: [],
+ },
+ }));
+}
+
+function ruleMatches(rule, input, alias) {
+ if (rule.event !== 'all' && rule.event !== alias) return false;
+ if (!matchesTool(rule.toolMatcher, input.tool_name)) return false;
+ if (rule.conditions.length > 0) {
+ return conditionCandidates(input).some(candidate => (
+ rule.conditions.every(condition => matchesCondition(condition, candidate))
+ ));
+ }
+ return testRegex(rule.regex, simpleValues(rule, input, alias));
+}
+
+function renderMatches(rules) {
+ const text = rules.map(rule => '**[' + sanitizeMessage(rule.name) + ']**\n' + rule.message).join('\n\n');
+ if (text.length <= MAX_MESSAGE_CHARS) return text;
+ const marker = '\n\n[Hookify output truncated]';
+ return text.slice(0, MAX_MESSAGE_CHARS - marker.length) + marker;
+}
+
+function buildOutput(input, matchedRules) {
+ const blockers = matchedRules.filter(rule => rule.action === 'block');
+ const message = renderMatches(blockers.length > 0 ? blockers : matchedRules);
+ const hookEvent = String(input.hook_event_name || '');
+ if (blockers.length > 0) {
+ if (hookEvent === 'PreToolUse') {
+ return {
+ hookSpecificOutput: {
+ hookEventName: 'PreToolUse',
+ permissionDecision: 'deny',
+ permissionDecisionReason: message,
+ },
+ };
+ }
+ return { decision: 'block', reason: message };
+ }
+ return { hookSpecificOutput: { hookEventName: hookEvent, additionalContext: message } };
+}
+
+function parseInput(inputOrRaw) {
+ if (typeof inputOrRaw !== 'string') return isPlainObject(inputOrRaw) ? inputOrRaw : null;
+ try {
+ const parsed = inputOrRaw.trim() ? JSON.parse(inputOrRaw) : {};
+ return isPlainObject(parsed) ? parsed : null;
+ } catch {
+ return null;
+ }
+}
+
+function run(inputOrRaw, options = {}) {
+ const raw = typeof inputOrRaw === 'string' ? inputOrRaw : JSON.stringify(inputOrRaw || {});
+ const passThrough = { raw, stdout: raw, stderr: '', exitCode: 0 };
+ if (options.truncated) {
+ return { ...passThrough, stderr: diagnostic('input', 'payload exceeded ' + (options.maxStdin || MAX_STDIN_BYTES) + ' bytes; rule evaluation skipped') };
+ }
+ const input = parseInput(inputOrRaw);
+ if (!input) return { ...passThrough, stderr: diagnostic('input', 'invalid hook JSON; rule evaluation skipped') };
+ const alias = eventAlias(input);
+ if (!alias || (alias === 'stop' && input.stop_hook_active === true)) return passThrough;
+
+ const env = options.env || process.env;
+ const loaded = loadRules(resolveProjectRoot(options.cwd || process.cwd(), env));
+ const diagnostics = [...loaded.diagnostics];
+ const matchedRules = [];
+ for (const rule of loaded.rules) {
+ try {
+ if (ruleMatches(rule, input, alias)) matchedRules.push(rule);
+ } catch (error) {
+ diagnostics.push(diagnostic(path.basename(rule.sourcePath), error.message));
+ }
+ }
+ if (matchedRules.length === 0) return { ...passThrough, stderr: diagnostics.join('\n') };
+ return {
+ raw,
+ stdout: JSON.stringify(buildOutput(input, matchedRules)),
+ stderr: diagnostics.join('\n'),
+ exitCode: 0,
+ };
+}
+
+function readStdin() {
+ return new Promise(resolve => {
+ const decoder = new StringDecoder('utf8');
+ let raw = '';
+ let bytes = 0;
+ let truncated = false;
+ process.stdin.on('data', chunk => {
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
+ const remaining = Math.max(0, MAX_STDIN_BYTES - bytes);
+ const accepted = buffer.subarray(0, remaining);
+ if (accepted.length > 0) {
+ raw += decoder.write(accepted);
+ bytes += accepted.length;
+ }
+ if (accepted.length < buffer.length) truncated = true;
+ });
+ process.stdin.once('end', () => {
+ if (!truncated) raw += decoder.end();
+ resolve({ raw, truncated });
+ });
+ process.stdin.once('error', () => resolve({ raw, truncated: true }));
+ });
+}
+
+async function main() {
+ const input = await readStdin();
+ const result = run(input.raw, { truncated: input.truncated, maxStdin: MAX_STDIN_BYTES });
+ if (result.stderr) process.stderr.write(result.stderr + '\n');
+ if (result.stdout && result.stdout !== input.raw) process.stdout.write(result.stdout);
+ process.exitCode = 0;
+}
+
+if (require.main === module) {
+ main().catch(error => {
+ process.stderr.write(diagnostic('runtime', error.message) + '\n');
+ process.exitCode = 0;
+ });
+}
+
+module.exports = {
+ MAX_FIELD_CHARS,
+ MAX_MESSAGE_CHARS,
+ MAX_PATTERN_CHARS,
+ MAX_RULE_BYTES,
+ MAX_RULES,
+ REGEX_TIMEOUT_MS,
+ buildOutput,
+ conditionCandidates,
+ eventAlias,
+ extractFrontmatter,
+ loadRules,
+ normalizeRule,
+ parseRuleFrontmatter,
+ ruleMatches,
+ run,
+ testRegex,
+};
diff --git a/scripts/hooks/posttooluse-dispatcher.js b/scripts/hooks/posttooluse-dispatcher.js
index fcffeb400..78f9d8f82 100644
--- a/scripts/hooks/posttooluse-dispatcher.js
+++ b/scripts/hooks/posttooluse-dispatcher.js
@@ -20,10 +20,21 @@ const { run: runObserve } = require('./observe-runner');
const { run: runMetricsBridge } = require('./ecc-metrics-bridge');
const { run: runContextMonitor } = require('./ecc-context-monitor');
const { run: runSkillRunTracker } = require('./skill-run-tracker');
+const { run: runHookify } = require('./hookify-runtime');
const MAX_STDIN = 1024 * 1024;
const SYNC_HOOKS = [
+ {
+ id: 'post:hookify-runtime',
+ matcher: '*',
+ profiles: 'minimal,standard,strict',
+ script: 'scripts/hooks/hookify-runtime.js',
+ run(raw, options) {
+ const result = runHookify(raw, options);
+ return result.stdout === raw ? { ...result, stdout: '' } : result;
+ }
+ },
{ id: 'post:edit:design-quality-check', matcher: 'Edit|Write|MultiEdit', profiles: 'standard,strict', script: 'scripts/hooks/design-quality-check.js', run: runDesignQualityCheck },
{ id: 'post:edit:accumulator', matcher: 'Edit|Write|MultiEdit', profiles: 'standard,strict', script: 'scripts/hooks/post-edit-accumulator.js', run: runPostEditAccumulator },
{ id: 'post:edit:console-warn', matcher: 'Edit', profiles: 'standard,strict', script: 'scripts/hooks/post-edit-console-warn.js', run: runConsoleWarn },
@@ -128,12 +139,22 @@ function appendLine(current, next) {
return current + (String(next).endsWith('\n') ? String(next) : `${next}\n`);
}
-function parseAdditionalContext(stdout) {
+function parseStructuredOutput(stdout) {
try {
const parsed = JSON.parse(stdout);
const output = parsed?.hookSpecificOutput;
+ if (parsed?.decision === 'block' && typeof parsed.reason === 'string') {
+ return {
+ blockReason: parsed.reason,
+ additionalContext: output?.hookEventName === 'PostToolUse'
+ && typeof output.additionalContext === 'string'
+ ? output.additionalContext
+ : '',
+ };
+ }
if (output?.hookEventName !== 'PostToolUse') return null;
- return typeof output.additionalContext === 'string' ? output.additionalContext : null;
+ if (typeof output.additionalContext !== 'string') return null;
+ return { blockReason: '', additionalContext: output.additionalContext };
} catch {
return null;
}
@@ -143,15 +164,44 @@ function mergeHookStdout(outputs) {
if (outputs.length === 0) return { stdout: '', warning: '' };
if (outputs.length === 1) return { stdout: outputs[0].stdout, warning: '' };
- const contexts = outputs.map(output => parseAdditionalContext(output.stdout));
- if (contexts.every(context => context !== null)) {
+ const structured = outputs.map(output => parseStructuredOutput(output.stdout));
+ const blockOutputs = structured.filter(output => output?.blockReason);
+ if (blockOutputs.length > 0) {
+ const contexts = structured
+ .filter(output => output !== null)
+ .map(output => output.additionalContext)
+ .filter(Boolean);
+ const blocked = {
+ decision: 'block',
+ reason: blockOutputs.map(output => output.blockReason).join('\n\n'),
+ };
+ if (contexts.length > 0) {
+ blocked.hookSpecificOutput = {
+ hookEventName: 'PostToolUse',
+ additionalContext: contexts.join('\n'),
+ };
+ }
+ const rawOutputIds = outputs
+ .filter((_output, index) => structured[index] === null)
+ .map(output => output.id);
+ return {
+ stdout: JSON.stringify(blocked),
+ warning: rawOutputIds.length > 0
+ ? '[Hook] raw stdout from ' + rawOutputIds.join(', ') + ' dropped in favor of a blocking decision'
+ : '',
+ };
+ }
+ if (structured.every(output => output !== null)) {
+ const contexts = structured.map(output => output.additionalContext).filter(Boolean);
+ const mergedOutput = {};
+ if (contexts.length > 0) {
+ mergedOutput.hookSpecificOutput = {
+ hookEventName: 'PostToolUse',
+ additionalContext: contexts.join('\n'),
+ };
+ }
return {
- stdout: JSON.stringify({
- hookSpecificOutput: {
- hookEventName: 'PostToolUse',
- additionalContext: contexts.join('\n')
- }
- }),
+ stdout: JSON.stringify(mergedOutput),
warning: ''
};
}
@@ -189,6 +239,8 @@ function runHooks(raw, hooks, options = {}) {
hookId: hook.id,
pluginRoot,
scriptPath: path.join(pluginRoot, hook.script || ''),
+ cwd: options.cwd || process.cwd(),
+ env,
truncated: options.truncated === true,
maxStdin: MAX_STDIN
})
@@ -206,7 +258,12 @@ function runHooks(raw, hooks, options = {}) {
const merged = mergeHookStdout(outputs);
if (merged.warning) stderr = appendLine(stderr, merged.warning);
- return { stdout: merged.stdout, stderr, exitCode };
+ const mergedDecision = parseStructuredOutput(merged.stdout);
+ // Structured blocking decisions must reach Claude on a successful command
+ // hook exit. An unrelated sibling hook failure must not downgrade the block
+ // into a generic non-blocking hook error.
+ const finalExitCode = mergedDecision?.blockReason ? 0 : exitCode;
+ return { stdout: merged.stdout, stderr, exitCode: finalExitCode };
}
function readStdinRaw() {
diff --git a/skills/hookify-rules/SKILL.md b/skills/hookify-rules/SKILL.md
index e256d2e92..47f18c6bd 100644
--- a/skills/hookify-rules/SKILL.md
+++ b/skills/hookify-rules/SKILL.md
@@ -7,6 +7,10 @@ description: This skill should be used when the user asks to create a hookify ru
## Overview
+ECC evaluates project-local Hookify rules with its built-in Node runtime. No
+separate Hookify plugin or Python installation is required when ECC hooks are
+enabled.
+
Hookify rules are markdown files with YAML frontmatter that define patterns to watch for and messages to show when those patterns match. Rules are stored in `.claude/hookify.{rule-name}.local.md` files.
## Rule File Format
@@ -101,6 +105,19 @@ Match user prompt content for workflow enforcement.
python3 -c "import re; print(re.search(r'your_pattern', 'test text'))"
```
+Avoid nested quantifiers such as `(a+)+`. The runtime rejects patterns with
+common catastrophic-backtracking shapes because rules run synchronously in the
+hook path, and every regex evaluation has a 25 ms hard timeout. Invalid,
+symlinked, or oversized local rules fail open and emit a
+diagnostic without disabling other Hookify rules.
+
+## Runtime Behavior
+
+- `warn` injects the message as event-specific additional context and does not block.
+- `block` denies matching Bash, PowerShell, Write, Edit, or MultiEdit calls before execution.
+- On prompt, post-tool, and stop events, `block` uses Claude Code's structured block decision.
+- Stop rules skip recursive `stop_hook_active` events to prevent infinite continuation loops.
+
## File Organization
- **Location**: `.claude/` directory in project root
diff --git a/tests/hooks/hookify-runtime.test.js b/tests/hooks/hookify-runtime.test.js
new file mode 100644
index 000000000..d26d69a87
--- /dev/null
+++ b/tests/hooks/hookify-runtime.test.js
@@ -0,0 +1,812 @@
+/**
+ * Contract tests for the ECC-native Hookify rule runtime (#2561).
+ */
+
+'use strict';
+
+const assert = require('assert');
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+const { spawnSync } = require('child_process');
+
+const repoRoot = path.join(__dirname, '..', '..');
+const runtimePath = path.join(repoRoot, 'scripts', 'hooks', 'hookify-runtime.js');
+const hooksPath = path.join(repoRoot, 'hooks', 'hooks.json');
+const dispatcherPath = path.join(repoRoot, 'scripts', 'hooks', 'posttooluse-dispatcher.js');
+const runtime = require(runtimePath);
+
+function test(name, fn) {
+ try {
+ fn();
+ console.log(' \u2713 ' + name);
+ return true;
+ } catch (error) {
+ console.log(' \u2717 ' + name);
+ console.log(' Error: ' + error.message);
+ return false;
+ }
+}
+
+function createProject() {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-hookify-'));
+ fs.mkdirSync(path.join(root, '.claude'), { recursive: true });
+ return root;
+}
+
+function writeRule(root, slug, frontmatter, message = 'Hookify policy matched.') {
+ const file = path.join(root, '.claude', 'hookify.' + slug + '.local.md');
+ fs.writeFileSync(file, '---\n' + frontmatter.trim() + '\n---\n' + message + '\n');
+ return file;
+}
+
+function runHook(root, input, env = {}) {
+ const raw = typeof input === 'string' ? input : JSON.stringify(input);
+ return runtime.run(raw, {
+ cwd: root,
+ env: {
+ ...process.env,
+ CLAUDE_PROJECT_DIR: root,
+ ...env,
+ },
+ });
+}
+
+function parseDecision(result) {
+ assert.strictEqual(result.exitCode, 0, result.stderr);
+ assert.ok(result.stdout, 'expected hook output');
+ return JSON.parse(result.stdout);
+}
+
+function removeProject(root) {
+ fs.rmSync(root, { recursive: true, force: true });
+}
+
+function runRegisteredEntry(root, entry, input, env = {}) {
+ const raw = JSON.stringify(input);
+ return spawnSync(entry.hooks[0].command, {
+ cwd: root,
+ input: raw,
+ encoding: 'utf8',
+ shell: true,
+ env: {
+ ...process.env,
+ CLAUDE_PLUGIN_ROOT: repoRoot,
+ CLAUDE_PROJECT_DIR: root,
+ ECC_HOOK_PROFILE: 'minimal',
+ ...env,
+ },
+ timeout: 15000,
+ maxBuffer: 16 * 1024 * 1024,
+ });
+}
+
+console.log('\nHookify runtime tests (#2561)');
+console.log('\u2500'.repeat(50));
+
+let passed = 0;
+let failed = 0;
+
+if (test('loads enabled project-local rules and ignores disabled rules', () => {
+ const root = createProject();
+ try {
+ writeRule(root, 'enabled', 'name: enabled-rule\nenabled: true\nevent: bash\npattern: npm\\s+publish');
+ writeRule(root, 'disabled', 'name: disabled-rule\nenabled: false\nevent: bash\npattern: npm\\s+publish');
+ const loaded = runtime.loadRules(root);
+ assert.deepStrictEqual(loaded.rules.map(rule => rule.name), ['enabled-rule']);
+ assert.deepStrictEqual(loaded.diagnostics, []);
+ } finally {
+ removeProject(root);
+ }
+})) passed++; else failed++;
+
+if (test('parses supported quoted scalars and rejects unsupported frontmatter shapes', () => {
+ const parsed = runtime.parseRuleFrontmatter([
+ 'name: "quoted-rule"',
+ "event: 'bash'",
+ 'enabled: TRUE',
+ 'pattern: "npm\\\\s+test"',
+ ].join('\n'));
+ assert.deepStrictEqual({ ...parsed }, {
+ name: 'quoted-rule',
+ event: 'bash',
+ enabled: true,
+ pattern: 'npm\\s+test',
+ });
+ assert.throws(
+ () => runtime.parseRuleFrontmatter('name: [one, two]'),
+ /flow collections/
+ );
+ assert.throws(
+ () => runtime.parseRuleFrontmatter('name: "unterminated'),
+ /unterminated quoted scalar/
+ );
+ assert.throws(
+ () => runtime.parseRuleFrontmatter('name: rule\n nested: value'),
+ /nested values/
+ );
+})) passed++; else failed++;
+
+if (test('runtime has no install-time package dependency', () => {
+ const source = fs.readFileSync(runtimePath, 'utf8');
+ assert.doesNotMatch(source, /require\(['"](?:js-yaml|yaml)['"]\)/);
+ const result = spawnSync(process.execPath, [runtimePath], {
+ cwd: os.tmpdir(),
+ input: JSON.stringify({ hook_event_name: 'PreToolUse', tool_name: 'Read', tool_input: {} }),
+ encoding: 'utf8',
+ env: { ...process.env, CLAUDE_PROJECT_DIR: os.tmpdir(), NODE_PATH: '' },
+ timeout: 10000,
+ });
+ assert.strictEqual(result.status, 0, result.stderr);
+ assert.strictEqual(result.stdout, '');
+})) passed++; else failed++;
+
+if (test('blocks a matching Bash command before tool execution', () => {
+ const root = createProject();
+ try {
+ writeRule(
+ root,
+ 'publish',
+ 'name: block-publish\nenabled: true\nevent: bash\naction: block\npattern: npm\\s+publish',
+ 'Publishing requires an explicit release approval.'
+ );
+ const output = parseDecision(runHook(root, {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'Bash',
+ tool_input: { command: 'npm publish --access public' },
+ cwd: root,
+ }));
+ assert.strictEqual(output.hookSpecificOutput.hookEventName, 'PreToolUse');
+ assert.strictEqual(output.hookSpecificOutput.permissionDecision, 'deny');
+
+ assert.match(output.hookSpecificOutput.permissionDecisionReason, /block-publish/);
+ assert.match(output.hookSpecificOutput.permissionDecisionReason, /release approval/);
+ } finally {
+ removeProject(root);
+ }
+})) passed++; else failed++;
+
+if (test('emits visible additionalContext for warning rules', () => {
+ const root = createProject();
+ try {
+ writeRule(
+ root,
+ 'warn-force',
+ 'name: warn-force\nenabled: true\nevent: bash\naction: warn\npattern: git\\s+push\\s+--force',
+ 'Prefer --force-with-lease.'
+ );
+ const output = parseDecision(runHook(root, {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'Bash',
+ tool_input: { command: 'git push --force origin topic' },
+ }));
+ assert.strictEqual(output.hookSpecificOutput.hookEventName, 'PreToolUse');
+ assert.match(output.hookSpecificOutput.additionalContext, /warn-force/);
+ assert.match(output.hookSpecificOutput.additionalContext, /force-with-lease/);
+ assert.ok(!output.hookSpecificOutput.permissionDecision);
+ } finally {
+ removeProject(root);
+ }
+})) passed++; else failed++;
+
+if (test('matches simple file rules against paths and edited content', () => {
+ const root = createProject();
+ try {
+ writeRule(root, 'env-file', 'name: warn-env-file\nevent: file\npattern: \\.env$', 'Do not edit secrets directly.');
+ writeRule(root, 'debugger', 'name: warn-debugger\nevent: file\npattern: debugger', 'Remove debugger statements.');
+
+ const pathOutput = parseDecision(runHook(root, {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'Write',
+ tool_input: { file_path: path.join(root, '.env'), content: 'SAFE=value' },
+ }));
+ assert.match(pathOutput.hookSpecificOutput.additionalContext, /warn-env-file/);
+
+ const contentOutput = parseDecision(runHook(root, {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'Edit',
+ tool_input: { file_path: 'src/app.js', old_string: 'run();', new_string: 'debugger; run();' },
+ }));
+ assert.match(contentOutput.hookSpecificOutput.additionalContext, /warn-debugger/);
+ } finally {
+ removeProject(root);
+ }
+})) passed++; else failed++;
+
+if (test('simple file rules do not match text that an Edit removes', () => {
+ const root = createProject();
+ try {
+ writeRule(root, 'removed-debugger', 'name: warn-debugger\nevent: file\npattern: debugger', 'Remove debugger statements.');
+ const result = runHook(root, {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'Edit',
+ tool_input: { file_path: 'src/app.js', old_string: 'debugger; run();', new_string: 'run();' },
+ });
+ assert.strictEqual(result.stdout, result.raw);
+ } finally {
+ removeProject(root);
+ }
+})) passed++; else failed++;
+
+if (test('supports advanced conditions and requires every condition to match', () => {
+ const root = createProject();
+ try {
+ writeRule(
+ root,
+ 'api-key',
+ [
+ 'name: block-api-key',
+ 'event: file',
+ 'action: block',
+ 'conditions:',
+ ' - field: file_path',
+ ' operator: ends_with',
+ ' pattern: .env',
+ ' - field: content',
+ ' operator: contains',
+ ' pattern: API_KEY=',
+ ].join('\n'),
+ 'Keep credentials out of tracked files.'
+ );
+
+ const matching = parseDecision(runHook(root, {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'Write',
+ tool_input: { file_path: 'config/.env', content: 'API_KEY=secret' },
+ }));
+ assert.strictEqual(matching.hookSpecificOutput.permissionDecision, 'deny');
+
+ const postOutput = parseDecision(runHook(root, {
+ hook_event_name: 'PostToolUse',
+ tool_name: 'Write',
+ tool_input: { file_path: 'config/.env', content: 'API_KEY=secret' },
+ tool_response: {},
+ }));
+ assert.strictEqual(postOutput.decision, 'block');
+
+ const nonMatching = runHook(root, {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'Write',
+ tool_input: { file_path: 'config/.env.example', content: 'API_KEY=placeholder' },
+ });
+ assert.strictEqual(nonMatching.stdout, nonMatching.raw);
+ } finally {
+ removeProject(root);
+ }
+})) passed++; else failed++;
+
+if (test('does not satisfy negative conditions when the requested field is absent', () => {
+ const root = createProject();
+ try {
+ writeRule(
+ root,
+ 'missing-field',
+ 'name: missing-field\nevent: bash\nconditions:\n - field: file_path\n operator: not_contains\n pattern: vendor',
+ 'A missing file path must not match.'
+ );
+ const result = runHook(root, {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'Bash',
+ tool_input: { command: 'pwd' },
+ });
+ assert.strictEqual(result.stdout, result.raw);
+ } finally {
+ removeProject(root);
+ }
+})) passed++; else failed++;
+
+if (test('requires MultiEdit conditions to match the same edit item', () => {
+ const root = createProject();
+ try {
+ writeRule(
+ root,
+ 'correlated-edits',
+ 'name: correlated-edits\nevent: file\naction: block\nconditions:\n - field: file_path\n operator: ends_with\n pattern: .env\n - field: content\n operator: contains\n pattern: API_KEY=',
+ 'A single edit must satisfy both conditions.'
+ );
+ const split = runHook(root, {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'MultiEdit',
+ tool_input: { edits: [
+ { file_path: 'config/.env', new_string: 'SAFE=value' },
+ { file_path: 'src/constants.js', new_string: 'API_KEY=placeholder' },
+ ] },
+ });
+ assert.strictEqual(split.stdout, split.raw);
+
+ const correlated = parseDecision(runHook(root, {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'MultiEdit',
+ tool_input: { edits: [
+ { file_path: 'config/.env', new_string: 'API_KEY=secret' },
+ { file_path: 'src/constants.js', new_string: 'SAFE=value' },
+ ] },
+ }));
+ assert.strictEqual(correlated.hookSpecificOutput.permissionDecision, 'deny');
+ } finally {
+ removeProject(root);
+ }
+})) passed++; else failed++;
+
+if (test('supports PowerShell and MultiEdit on the cross-platform aliases', () => {
+ const root = createProject();
+ try {
+ writeRule(root, 'remove-item', 'name: warn-remove-item\nevent: bash\npattern: Remove-Item', 'Review recursive deletion.');
+ writeRule(root, 'multi-edit', 'name: warn-eval\nevent: file\npattern: eval\\(', 'Avoid dynamic evaluation.');
+
+ const shellOutput = parseDecision(runHook(root, {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'PowerShell',
+ tool_input: { command: 'Remove-Item -Recurse build' },
+ }));
+ assert.match(shellOutput.hookSpecificOutput.additionalContext, /warn-remove-item/);
+
+ const editOutput = parseDecision(runHook(root, {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'MultiEdit',
+ tool_input: { edits: [{ file_path: 'a.js', new_string: 'eval(source)' }] },
+ }));
+ assert.match(editOutput.hookSpecificOutput.additionalContext, /warn-eval/);
+ } finally {
+ removeProject(root);
+ }
+})) passed++; else failed++;
+
+if (test('bounds one simple rule to one isolated regex evaluation for large MultiEdit input', () => {
+ const root = createProject();
+ try {
+ writeRule(root, 'large-multi', 'name: large-multi\nevent: file\npattern: sentinel$', 'Match the final edit.');
+ const edits = Array.from({ length: 100 }, (_, index) => ({
+ file_path: 'src/file-' + index + '.js',
+ new_string: index === 99 ? 'sentinel' : 'ordinary content',
+ }));
+ const started = Date.now();
+ const output = parseDecision(runHook(root, {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'MultiEdit',
+ tool_input: { edits },
+ }));
+ assert.ok(Date.now() - started < 1000, 'large MultiEdit matching should stay bounded');
+ assert.match(output.hookSpecificOutput.additionalContext, /large-multi/);
+ } finally {
+ removeProject(root);
+ }
+})) passed++; else failed++;
+
+if (test('uses prompt input and the top-level block contract for UserPromptSubmit', () => {
+ const root = createProject();
+ try {
+ writeRule(
+ root,
+ 'production',
+ 'name: block-production-deploy\nevent: prompt\naction: block\npattern: deploy.*production',
+ 'Production deploys require a change ticket.'
+ );
+ const output = parseDecision(runHook(root, {
+ hook_event_name: 'UserPromptSubmit',
+ prompt: 'Please deploy this service to production',
+ }));
+ assert.strictEqual(output.decision, 'block');
+ assert.match(output.reason, /change ticket/);
+ assert.ok(!output.hookSpecificOutput);
+ } finally {
+ removeProject(root);
+ }
+})) passed++; else failed++;
+
+if (test('blocks Stop once and skips recursive stop_hook_active events', () => {
+ const root = createProject();
+ try {
+ writeRule(root, 'tests', 'name: require-tests\nevent: stop\naction: block\npattern: .*', 'Run the test suite before stopping.');
+
+ const first = parseDecision(runHook(root, {
+ hook_event_name: 'Stop',
+ stop_hook_active: false,
+ last_assistant_message: 'Implementation is complete.',
+ }));
+ assert.strictEqual(first.decision, 'block');
+ assert.match(first.reason, /Run the test suite/);
+
+ const retry = runHook(root, {
+ hook_event_name: 'Stop',
+ stop_hook_active: true,
+ last_assistant_message: 'Tests now pass.',
+ });
+ assert.strictEqual(retry.stdout, retry.raw);
+ } finally {
+ removeProject(root);
+ }
+})) passed++; else failed++;
+
+if (test('matches all-event rules while respecting tool_matcher', () => {
+ const root = createProject();
+ try {
+ writeRule(
+ root,
+ 'all-write',
+ 'name: warn-generated\nevent: all\ntool_matcher: Write|Edit\npattern: generated',
+ 'Confirm generated output is intentional.'
+ );
+ const edit = parseDecision(runHook(root, {
+ hook_event_name: 'PostToolUse',
+ tool_name: 'Edit',
+ tool_input: { file_path: 'src/generated.js', new_string: 'export {}' },
+ tool_response: {},
+ }));
+ assert.strictEqual(edit.hookSpecificOutput.hookEventName, 'PostToolUse');
+ assert.match(edit.hookSpecificOutput.additionalContext, /warn-generated/);
+
+ const bash = runHook(root, {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'Bash',
+ tool_input: { command: 'echo generated' },
+ });
+ assert.strictEqual(bash.stdout, bash.raw);
+ } finally {
+ removeProject(root);
+ }
+})) passed++; else failed++;
+
+if (test('all-event rules can match tool events outside bash and file aliases', () => {
+ const root = createProject();
+ try {
+ writeRule(root, 'all-read', 'name: warn-sensitive-read\nevent: all\npattern: sensitive\\.json', 'Review access to sensitive data.');
+ const output = parseDecision(runHook(root, {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'Read',
+ tool_input: { file_path: 'config/sensitive.json' },
+ }));
+ assert.strictEqual(output.hookSpecificOutput.hookEventName, 'PreToolUse');
+ assert.match(output.hookSpecificOutput.additionalContext, /warn-sensitive-read/);
+ } finally {
+ removeProject(root);
+ }
+})) passed++; else failed++;
+
+if (test('an all-event wildcard can match a Stop payload with no optional text', () => {
+ const root = createProject();
+ try {
+ writeRule(root, 'all-stop', 'name: warn-all-stop\nevent: all\npattern: .*', 'Review the completed turn.');
+ const output = parseDecision(runHook(root, {
+ hook_event_name: 'Stop',
+ stop_hook_active: false,
+ }));
+ assert.strictEqual(output.hookSpecificOutput.hookEventName, 'Stop');
+ assert.match(output.hookSpecificOutput.additionalContext, /warn-all-stop/);
+ } finally {
+ removeProject(root);
+ }
+})) passed++; else failed++;
+
+if (test('fails open on malformed YAML, invalid regex, and unsupported operators', () => {
+ const root = createProject();
+ try {
+ fs.writeFileSync(path.join(root, '.claude', 'hookify.bad-yaml.local.md'), '---\nname: [\n---\nBad YAML');
+ writeRule(root, 'bad-regex', 'name: bad-regex\nevent: bash\npattern: "("', 'Invalid regex');
+ writeRule(
+ root,
+ 'bad-condition',
+ 'name: bad-condition\nevent: bash\nconditions:\n - field: command\n operator: executes\n pattern: npm',
+ 'Unsupported operator'
+ );
+ const result = runHook(root, {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'Bash',
+ tool_input: { command: 'npm publish' },
+ });
+ assert.strictEqual(result.stdout, result.raw);
+ assert.match(result.stderr, /bad-yaml/);
+ assert.match(result.stderr, /bad-regex/);
+ assert.match(result.stderr, /bad-condition/);
+ assert.doesNotMatch(result.stderr, /npm publish/);
+ } finally {
+ removeProject(root);
+ }
+})) passed++; else failed++;
+
+if (test('rejects duplicate keys instead of silently changing rule semantics', () => {
+ const root = createProject();
+ try {
+ writeRule(root, 'duplicate-action', 'name: duplicate-action\nevent: bash\naction: block\naction: warn\npattern: .*', 'Duplicate action.');
+ writeRule(root, 'duplicate-condition', 'name: duplicate-condition\nevent: bash\nconditions:\n - field: command\n field: file_path\n operator: contains\n pattern: pwd', 'Duplicate field.');
+ const result = runHook(root, {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'Bash',
+ tool_input: { command: 'pwd' },
+ });
+ assert.strictEqual(result.stdout, result.raw);
+ assert.match(result.stderr, /duplicate-action/);
+ assert.match(result.stderr, /duplicate-condition/);
+ } finally {
+ removeProject(root);
+ }
+})) passed++; else failed++;
+
+if (test('rejects unknown keys instead of silently weakening a rule', () => {
+ const root = createProject();
+ try {
+ writeRule(root, 'typo-action', 'name: typo-action\nevent: bash\nactions: block\npattern: .*', 'Typo must fail closed at rule level.');
+ writeRule(root, 'typo-condition', 'name: typo-condition\nevent: bash\nconditions:\n - field: command\n operators: contains\n pattern: pwd', 'Typo must not change matching.');
+ const result = runHook(root, {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'Bash',
+ tool_input: { command: 'pwd' },
+ });
+ assert.strictEqual(result.stdout, result.raw);
+ assert.match(result.stderr, /typo-action/);
+ assert.match(result.stderr, /typo-condition/);
+ } finally {
+ removeProject(root);
+ }
+})) passed++; else failed++;
+
+if (test('rejects common catastrophic-backtracking regex shapes', () => {
+ const root = createProject();
+ try {
+ writeRule(root, 'nested-quantifier', 'name: nested-quantifier\nevent: bash\npattern: (a+)+$', 'Unsafe regex.');
+ writeRule(root, 'nested-parens', 'name: nested-parens\nevent: bash\npattern: ((a)+)+$', 'Unsafe regex.');
+ writeRule(root, 'ambiguous-alternative', 'name: ambiguous-alternative\nevent: bash\npattern: (a|aa)+$', 'Unsafe regex.');
+ writeRule(root, 'repeated-wildcard', 'name: repeated-wildcard\nevent: bash\npattern: .*prefix.*suffix', 'Unsafe regex.');
+ const result = runHook(root, {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'Bash',
+ tool_input: { command: 'a'.repeat(20000) + '!' },
+ });
+ assert.strictEqual(result.stdout, result.raw);
+ assert.match(result.stderr, /nested-quantifier/);
+ assert.match(result.stderr, /nested-parens/);
+ assert.match(result.stderr, /ambiguous-alternative/);
+ assert.match(result.stderr, /repeated-wildcard/);
+ } finally {
+ removeProject(root);
+ }
+})) passed++; else failed++;
+
+if (test('hard-times out ReDoS shapes that pass static screening', () => {
+ const root = createProject();
+ try {
+ writeRule(root, 'runtime-redos', 'name: runtime-redos\nevent: bash\npattern: a+a+$', 'Must time out safely.');
+ const started = Date.now();
+ const result = runHook(root, {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'Bash',
+ tool_input: { command: 'a'.repeat(60000) + '!' },
+ });
+ assert.ok(Date.now() - started < 1000, 'regex timeout must bound hook latency');
+ assert.strictEqual(result.stdout, result.raw);
+ assert.match(result.stderr, /regex evaluation exceeded/);
+ assert.doesNotMatch(result.stderr, /a\+a\+/);
+ } finally {
+ removeProject(root);
+ }
+})) passed++; else failed++;
+
+if (test('a timed-out rule cannot suppress a later valid blocking rule', () => {
+ const root = createProject();
+ try {
+ writeRule(root, 'aaa-timeout', 'name: aaa-timeout\nevent: bash\npattern: a+a+$', 'Must time out safely.');
+ writeRule(root, 'zzz-block', 'name: zzz-block\nevent: bash\naction: block\npattern: !$', 'The later rule must still block.');
+ const result = runHook(root, {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'Bash',
+ tool_input: { command: 'a'.repeat(60000) + '!' },
+ });
+ const output = parseDecision(result);
+ assert.strictEqual(output.hookSpecificOutput.permissionDecision, 'deny');
+ assert.match(output.hookSpecificOutput.permissionDecisionReason, /zzz-block/);
+ assert.match(result.stderr, /regex evaluation exceeded/);
+ } finally {
+ removeProject(root);
+ }
+})) passed++; else failed++;
+
+if (test('does not follow rule symlinks outside the project .claude directory', () => {
+ if (process.platform === 'win32') return;
+ const root = createProject();
+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-hookify-outside-'));
+ try {
+ const externalRule = path.join(outside, 'external.md');
+ fs.writeFileSync(externalRule, '---\nname: outside\nevent: bash\naction: block\npattern: .*\n---\nMust not load.\n');
+ fs.symlinkSync(externalRule, path.join(root, '.claude', 'hookify.link.local.md'));
+ const result = runHook(root, {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'Bash',
+ tool_input: { command: 'pwd' },
+ });
+ assert.strictEqual(result.stdout, result.raw);
+ assert.match(result.stderr, /symbolic link/);
+ } finally {
+ removeProject(root);
+ removeProject(outside);
+ }
+})) passed++; else failed++;
+
+if (test('trusted CLAUDE_PROJECT_DIR takes precedence over payload cwd', () => {
+ const trusted = createProject();
+ const untrusted = createProject();
+ try {
+ writeRule(untrusted, 'outside', 'name: outside-rule\nevent: bash\naction: block\npattern: .*', 'Must not load.');
+ const result = runtime.run(JSON.stringify({
+ hook_event_name: 'PreToolUse',
+ tool_name: 'Bash',
+ tool_input: { command: 'pwd' },
+ cwd: untrusted,
+ }), {
+ cwd: trusted,
+ env: { ...process.env, CLAUDE_PROJECT_DIR: trusted },
+ });
+ assert.strictEqual(result.stdout, result.raw);
+ } finally {
+ removeProject(trusted);
+ removeProject(untrusted);
+ }
+})) passed++; else failed++;
+
+if (test('caps rule files and emitted messages without producing invalid JSON', () => {
+ const root = createProject();
+ try {
+ fs.writeFileSync(
+ path.join(root, '.claude', 'hookify.oversized.local.md'),
+ '---\nname: oversized\nevent: bash\npattern: .*\n---\n' + 'x'.repeat(runtime.MAX_RULE_BYTES + 1)
+ );
+ writeRule(root, 'long-message', 'name: long-message\nevent: bash\npattern: .*', 'm'.repeat(runtime.MAX_MESSAGE_CHARS * 2));
+ const result = runHook(root, {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'Bash',
+ tool_input: { command: 'pwd' },
+ });
+ const output = parseDecision(result);
+ assert.ok(output.hookSpecificOutput.additionalContext.length <= runtime.MAX_MESSAGE_CHARS);
+ assert.match(result.stderr, /oversized/);
+ } finally {
+ removeProject(root);
+ }
+})) passed++; else failed++;
+
+if (test('registers all four events and keeps PostToolUse consolidated', () => {
+ const hooks = JSON.parse(fs.readFileSync(hooksPath, 'utf8')).hooks;
+ assert.ok(hooks.PreToolUse.some(entry => entry.id === 'pre:hookify-runtime'));
+ assert.ok(hooks.UserPromptSubmit.some(entry => entry.id === 'prompt:hookify-runtime'));
+ assert.ok(hooks.Stop.some(entry => entry.id === 'stop:hookify-runtime'));
+ assert.strictEqual(hooks.PostToolUse.length, 2, 'PostToolUse must remain consolidated');
+
+ delete require.cache[require.resolve(dispatcherPath)];
+ const dispatcher = require(dispatcherPath);
+ assert.ok(dispatcher.SYNC_HOOKS.some(entry => entry.id === 'post:hookify-runtime'));
+})) passed++; else failed++;
+
+if (test('registered hook commands enforce rules across all four events', () => {
+ const root = createProject();
+ try {
+ writeRule(root, 'all-events', 'name: all-events\nevent: all\naction: block\npattern: HOOKIFY_SENTINEL', 'Registered runtime matched.');
+ const hooks = JSON.parse(fs.readFileSync(hooksPath, 'utf8')).hooks;
+ const entries = [
+ [
+ hooks.PreToolUse.find(entry => entry.id === 'pre:hookify-runtime'),
+ { hook_event_name: 'PreToolUse', tool_name: 'Bash', tool_input: { command: 'echo HOOKIFY_SENTINEL' } },
+ output => output.hookSpecificOutput?.permissionDecision === 'deny',
+ ],
+ [
+ hooks.UserPromptSubmit.find(entry => entry.id === 'prompt:hookify-runtime'),
+ { hook_event_name: 'UserPromptSubmit', prompt: 'HOOKIFY_SENTINEL' },
+ output => output.decision === 'block',
+ ],
+ [
+ hooks.PostToolUse.find(entry => entry.id === 'post:dispatcher:sync'),
+ { hook_event_name: 'PostToolUse', tool_name: 'Read', tool_input: { file_path: 'HOOKIFY_SENTINEL' }, tool_response: {} },
+ output => output.decision === 'block',
+ ],
+ [
+ hooks.Stop.find(entry => entry.id === 'stop:hookify-runtime'),
+ { hook_event_name: 'Stop', stop_hook_active: false, last_assistant_message: 'HOOKIFY_SENTINEL' },
+ output => output.decision === 'block',
+ ],
+ ];
+
+ for (const [entry, input, assertion] of entries) {
+ assert.ok(entry, 'registered Hookify entry should exist');
+ const result = runRegisteredEntry(root, entry, input, {
+ ECC_DISABLED_HOOKS: 'post:ecc-metrics-bridge',
+ });
+ assert.strictEqual(result.status, 0, result.stderr);
+ const output = JSON.parse(result.stdout);
+ assert.ok(assertion(output), entry.id + ' did not preserve the blocking decision');
+ assert.match(JSON.stringify(output), /Registered runtime matched/);
+ }
+ } finally {
+ removeProject(root);
+ }
+})) passed++; else failed++;
+
+if (test('registered Hookify IDs can be disabled independently', () => {
+ const root = createProject();
+ try {
+ writeRule(root, 'disable', 'name: block-disabled\nevent: bash\naction: block\npattern: .*', 'Must not run.');
+ const hooks = JSON.parse(fs.readFileSync(hooksPath, 'utf8')).hooks;
+ const entry = hooks.PreToolUse.find(item => item.id === 'pre:hookify-runtime');
+ const input = {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'Bash',
+ tool_input: { command: 'pwd' },
+ };
+ const result = runRegisteredEntry(root, entry, input, { ECC_DISABLED_HOOKS: 'pre:hookify-runtime' });
+ assert.strictEqual(result.status, 0, result.stderr);
+ assert.strictEqual(result.stdout, '');
+ } finally {
+ removeProject(root);
+ }
+})) passed++; else failed++;
+
+if (test('PostToolUse dispatcher preserves Hookify block decisions over warnings', () => {
+ const dispatcher = require(dispatcherPath);
+ const raw = JSON.stringify({ hook_event_name: 'PostToolUse', tool_name: 'Write' });
+ const result = dispatcher.runHooks(raw, [
+ {
+ id: 'post:test:hookify-block',
+ matcher: '*',
+ profiles: 'standard,strict',
+ run: () => ({ stdout: JSON.stringify({ decision: 'block', reason: 'Hookify blocked this result.' }) }),
+ },
+ {
+ id: 'post:test:warning',
+ matcher: '*',
+ profiles: 'standard,strict',
+ run: () => ({ additionalContext: 'Secondary warning.' }),
+ },
+ ], { toolName: 'Write', env: { ECC_HOOK_PROFILE: 'standard' } });
+ const output = JSON.parse(result.stdout);
+ assert.strictEqual(output.decision, 'block');
+ assert.match(output.reason, /Hookify blocked this result/);
+ assert.strictEqual(output.hookSpecificOutput.hookEventName, 'PostToolUse');
+ assert.match(output.hookSpecificOutput.additionalContext, /Secondary warning/);
+
+ const withRawOutput = dispatcher.mergeHookStdout([
+ { id: 'post:test:block', stdout: JSON.stringify({ decision: 'block', reason: 'Keep the block.' }) },
+ { id: 'post:test:raw', stdout: 'unstructured output' },
+ ]);
+ assert.strictEqual(JSON.parse(withRawOutput.stdout).decision, 'block');
+ assert.match(JSON.parse(withRawOutput.stdout).reason, /Keep the block/);
+ assert.match(withRawOutput.warning, /post:test:raw/);
+
+ const withSiblingFailure = dispatcher.runHooks(raw, [
+ {
+ id: 'post:test:block',
+ matcher: '*',
+ profiles: 'standard,strict',
+ run: () => ({ stdout: JSON.stringify({ decision: 'block', reason: 'Block still wins.' }) }),
+ },
+ {
+ id: 'post:test:failure',
+ matcher: '*',
+ profiles: 'standard,strict',
+ run: () => ({ exitCode: 7 }),
+ },
+ ], { toolName: 'Write', env: { ECC_HOOK_PROFILE: 'standard' } });
+ assert.strictEqual(withSiblingFailure.exitCode, 0);
+ assert.strictEqual(JSON.parse(withSiblingFailure.stdout).decision, 'block');
+ assert.match(withSiblingFailure.stderr, /post:test:failure exited with code 7/);
+})) passed++; else failed++;
+
+if (test('direct entrypoint emits valid JSON for a matched prompt rule', () => {
+ const root = createProject();
+ try {
+ writeRule(root, 'prompt', 'name: warn-password\nevent: prompt\npattern: password', 'Do not paste credentials.');
+ const result = spawnSync(process.execPath, [runtimePath], {
+ cwd: root,
+ input: JSON.stringify({ hook_event_name: 'UserPromptSubmit', prompt: 'Here is my password' }),
+ encoding: 'utf8',
+ env: { ...process.env, CLAUDE_PROJECT_DIR: root },
+ timeout: 10000,
+ });
+ assert.strictEqual(result.status, 0, result.stderr);
+ const output = JSON.parse(result.stdout);
+ assert.strictEqual(output.hookSpecificOutput.hookEventName, 'UserPromptSubmit');
+ assert.match(output.hookSpecificOutput.additionalContext, /Do not paste credentials/);
+ } finally {
+ removeProject(root);
+ }
+})) passed++; else failed++;
+
+console.log('\nPassed: ' + passed);
+console.log('Failed: ' + failed);
+process.exit(failed > 0 ? 1 : 0);
diff --git a/tests/hooks/posttooluse-dispatcher.test.js b/tests/hooks/posttooluse-dispatcher.test.js
index c21f003f3..2fad3b3ad 100644
--- a/tests/hooks/posttooluse-dispatcher.test.js
+++ b/tests/hooks/posttooluse-dispatcher.test.js
@@ -108,6 +108,7 @@ function runTests() {
{
tool: 'Edit',
sync: [
+ 'post:hookify-runtime',
'post:edit:design-quality-check',
'post:edit:accumulator',
'post:edit:console-warn',
@@ -120,27 +121,27 @@ function runTests() {
},
{
tool: 'Write',
- sync: ['post:edit:design-quality-check', 'post:edit:accumulator', 'post:governance-capture', 'post:session-activity-tracker', 'post:ecc-metrics-bridge', 'post:ecc-context-monitor'],
+ sync: ['post:hookify-runtime', 'post:edit:design-quality-check', 'post:edit:accumulator', 'post:governance-capture', 'post:session-activity-tracker', 'post:ecc-metrics-bridge', 'post:ecc-context-monitor'],
async: ['post:quality-gate', 'post:observe:continuous-learning']
},
{
tool: 'Bash',
- sync: ['post:governance-capture', 'post:session-activity-tracker', 'post:ecc-metrics-bridge', 'post:ecc-context-monitor'],
+ sync: ['post:hookify-runtime', 'post:governance-capture', 'post:session-activity-tracker', 'post:ecc-metrics-bridge', 'post:ecc-context-monitor'],
async: ['post:bash:dispatcher', 'post:observe:continuous-learning']
},
{
tool: 'PowerShell',
- sync: ['post:governance-capture', 'post:session-activity-tracker', 'post:ecc-metrics-bridge', 'post:ecc-context-monitor'],
+ sync: ['post:hookify-runtime', 'post:governance-capture', 'post:session-activity-tracker', 'post:ecc-metrics-bridge', 'post:ecc-context-monitor'],
async: ['post:observe:continuous-learning']
},
{
tool: 'powershell',
- sync: ['post:governance-capture', 'post:session-activity-tracker', 'post:ecc-metrics-bridge', 'post:ecc-context-monitor'],
+ sync: ['post:hookify-runtime', 'post:governance-capture', 'post:session-activity-tracker', 'post:ecc-metrics-bridge', 'post:ecc-context-monitor'],
async: ['post:observe:continuous-learning']
},
{
tool: 'Read',
- sync: ['post:session-activity-tracker', 'post:ecc-metrics-bridge', 'post:ecc-context-monitor'],
+ sync: ['post:hookify-runtime', 'post:session-activity-tracker', 'post:ecc-metrics-bridge', 'post:ecc-context-monitor'],
async: ['post:observe:continuous-learning']
}
];
@@ -177,6 +178,7 @@ function runTests() {
}
const ids = results.flatMap(result => previewedIds(result.stderr));
assert.deepStrictEqual(ids, [
+ 'post:hookify-runtime',
'post:edit:design-quality-check',
'post:edit:accumulator',
'post:edit:console-warn',
@@ -225,7 +227,7 @@ function runTests() {
ECC_HOOK_PROFILE: 'minimal'
});
assert.strictEqual(minimalSync.status, 0, minimalSync.stderr);
- assert.deepStrictEqual(previewedIds(minimalSync.stderr), ['post:ecc-metrics-bridge']);
+ assert.deepStrictEqual(previewedIds(minimalSync.stderr), ['post:hookify-runtime', 'post:ecc-metrics-bridge']);
const minimalAsync = runDispatcher('async', 'Bash', {
ECC_DRY_RUN: '1',
diff --git a/tests/scripts/install-apply.test.js b/tests/scripts/install-apply.test.js
index 270339cb9..a7fcde289 100644
--- a/tests/scripts/install-apply.test.js
+++ b/tests/scripts/install-apply.test.js
@@ -168,6 +168,7 @@ function runTests() {
assert.ok(fs.existsSync(path.join(claudeRoot, 'rules', 'ecc', 'typescript', 'testing.md')));
assert.ok(fs.existsSync(path.join(claudeRoot, 'commands', 'plan.md')));
assert.ok(fs.existsSync(path.join(claudeRoot, 'scripts', 'hooks', 'session-end.js')));
+ assert.ok(fs.existsSync(path.join(claudeRoot, 'scripts', 'hooks', 'hookify-runtime.js')));
assert.ok(fs.existsSync(path.join(claudeRoot, 'scripts', 'lib', 'utils.js')));
assert.ok(fs.existsSync(path.join(claudeRoot, 'skills', 'tdd-workflow', 'SKILL.md')));
assert.ok(fs.existsSync(path.join(claudeRoot, 'skills', 'coding-standards', 'SKILL.md')));
@@ -803,6 +804,9 @@ function runTests() {
const settings = readJson(path.join(claudeRoot, 'settings.json'));
assert.strictEqual(settings.includeCoAuthoredBy, false);
assert.ok(settings.hooks.SessionStart.some(entry => entry.id === 'session:start'));
+ assert.ok(settings.hooks.PreToolUse.some(entry => entry.id === 'pre:hookify-runtime'));
+ assert.ok(settings.hooks.UserPromptSubmit.some(entry => entry.id === 'prompt:hookify-runtime'));
+ assert.ok(settings.hooks.Stop.some(entry => entry.id === 'stop:hookify-runtime'));
const state = readJson(path.join(claudeRoot, 'ecc', 'install-state.json'));
const settingsOperation = state.operations.find(operation => (