Step 3. Add a hook for rules a deny list can't express
Builds on step 2. Deny rules match text. Some rules need logic: "block merges, but only on protected branches", or "block SQL that changes the schema, but allow SELECT".
What to do
Why: a hook is a script. It gets the tool call as JSON on stdin and can refuse it with a message the agent reads and acts on.
Do this:
- Pick the one or two mistakes that have cost you the most. Start with those.
- Write a small script for each. Exit code 2 blocks the call, and whatever you print to stderr goes back to the agent.
- Register it in
.claude/settings.json. Hooks work only when registered there, insettings.local.json, in a plugin, or in skill or subagent frontmatter. - Keep the timeout short. A slow hook gets disabled.
Example
Example. Block direct schema changes through psql and point to migrations instead.
.claude/hooks/block-ddl.js:
let raw = "";
process.stdin.on("data", (chunk) => (raw += chunk));
process.stdin.on("end", () => {
const command = JSON.parse(raw).tool_input?.command ?? "";
const touchesDb = /\bpsql\b/i.test(command);
const changesSchema = /\b(ALTER|CREATE|DROP)\s+(TABLE|INDEX|TYPE)\b/i.test(command);
if (touchesDb && changesSchema) {
console.error(
"Blocked: schema changes must go through migrations. " +
"Edit the schema file, then run `npm run db:generate`."
);
process.exit(2);
}
});Register it in .claude/settings.json:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": "node .claude/hooks/block-ddl.js", "timeout": 5 }
]
}
]
}
}Check it works
Check in two stages. First, test the script alone:
echo '{"tool_input":{"command":"psql $DB -c \"DROP TABLE users\""}}' | node .claude/hooks/block-ddl.js
echo $? # expect 2, with the message on screenThen test it through the real agent. Ask Claude to run that command and confirm it gets refused. Run /hooks to see what is registered. A hook that exists as a file but isn't registered does nothing, and nobody notices.
Other events worth knowing:
PostToolUseruns after a call. Good for recording evidence or running a formatter.UserPromptSubmitruns when you send a prompt.Stopruns when the agent tries to finish. Step 8 uses it.
Watch out:
- Regex rules produce false positives. The example above would also block an
echothat mentionsDROP TABLE. Decide how much that matters. - Decide what happens when the hook crashes. Failing open is fine for style checks and wrong for security checks.
- Don't spawn a package manager on every call.
node script.jsis faster thannpm run script.