Vibe coding with Claude Code course Β· Module 15: Advanced Claude Code
Rules without exceptions: hooks
In this lesson9
A line in the CLAUDE.md of Treasure Map says: we do not edit migrations in prisma/migrations/, a schema change is a new migration. You ask Claude to rename a column, and it conscientiously fixes it in schema.prisma and in the saved migration, because the old name stands there too. Your database has already run that migration, so the migration history stops matching the database. The rule was written down, but a written rule is a request, and a request is not a lock.
What you already know
In lesson 7_1 you nailed down a PostToolUse hook with the Edit|Write matcher that formats the edited file, and you looked at it in /hooks. In lesson 7_3 a Notification hook in the user settings rang when Claude was waiting for consent. From lesson 8_4 you know the deny rule for .env, and from lesson 14_3 the order deny, ask, allow and the /permissions command. Now the hook does not tidy up after an edit, it stands in front of it and says "no".
A request, a rule, a hook
You can write a rule down in three ways, and they differ in who guards it:
- A line in
CLAUDE.mdis context for the model. Claude reads it and usually applies it, but the documentation says outright that there is no guarantee of strict obedience. - A
denyoraskrule is a pattern for a tool and a path, guarded by Claude Code in every mode. The refusal is general, with no hint of what to do instead. - A hook is your program run at a set moment of the work. It can check anything and answer with its own message.
The memory documentation advises: if something is to happen at a specific moment, for example before every edit, write a hook, not a line in CLAUDE.md. Events have their rhythm: SessionStart once at the start of a session, PreToolUse before every tool call, PostToolUse after it, and Stop when Claude finishes an answer. A ban must work before the write, so you choose PreToolUse.
Request for Claude Code
In a session in the treasure-map folder write:
Add to .claude/settings.json a PreToolUse hook for the Edit and Write tools. It is to run
the script .claude/hooks/protect-files.sh, which ends with code 2 and a message on stderr
for .env* files (except .env.example) and for everything in prisma/migrations/.
The message is to say what to do instead. Do not touch the existing hooks.
Done when the script gets JSON with the .env path and ends with code 2.The request gives the event, the tools, the exit code and a check, so it leaves no room for guessing.
What Claude wrote: the script
In Cursor open .claude/hooks/protect-files.sh. A hook gets the description of the call as JSON on standard input: the tool name in tool_name and the arguments in tool_input, and for Edit and Write the full path in file_path. The first line of the script pulls out the path:
#!/bin/bash
# protect-files.sh: a PreToolUse hook that keeps edits away from secrets and finished migrations
FILE=$(jq -r '.tool_input.file_path // empty')jq reads the JSON from the input, and // empty gives an empty text when the field is missing, for example for a Bash command. Further on stands the decision:
case "$FILE" in
*/.env.example)
exit 0
;;
*/.env*)
echo "Blocked: $FILE is a file with secrets. A human sets the variables in .env; add the missing name to .env.example." >&2
exit 2
;;
*/prisma/migrations/*)
echo "Blocked: $FILE is a saved migration. Change prisma/schema.prisma and ask for a new migration." >&2
exit 2
;;
esac
exit 0case compares the path with the patterns one by one and takes the first that matches, which is why the exception for .env.example stands before */.env*. The exit code is the answer. 2 blocks the call, and the text printed with >&2 to stderr Claude gets as the reason. 0 means no objection, not consent: the ordinary permissions decide further. Code 1, although in Unix it means an error, blocks nothing: the documentation calls it a non-blocking error and warns that a hook guarding a rule must end with code 2. Instead of code 2 the script may also end with code 0 and print JSON with permissionDecision set to deny. Pick one way per hook; code 2 is simpler and I stick to it.
What Claude wrote: the settings entry
In .claude/settings.json, next to permissions from lesson 14_3, a hooks section appeared:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "bash",
"args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/protect-files.sh"],
"onFailure": "block"
}
]
}
]
}
}You know the shape from lesson 7_1. matcher with Edit|Write is an exact list of tool names: Edit changes a fragment of an existing file, and Write saves the whole file, a new one too. ${CLAUDE_PROJECT_DIR} is the project folder, so the script will be found even when Claude changes the working directory. The args field runs bash without the shell as a go-between, so a path with a space will not fall into pieces and the script needs no chmod +x. onFailure: "block" reverses the default: without it a hook that fails to start, because the path is wrong, lets every edit through.
A live trial
You check the script first without Claude, giving it JSON by hand:
echo '{"tool_input":{"file_path":"/x/treasure-map/.env"}}' | bash .claude/hooks/protect-files.sh; echo $?The terminal will print the message "Blocked: ..." and the number 2. Swap the path for /x/treasure-map/lib/pins.ts and you will see just 0. Then a trial with Claude: in claude -p, with writing allowed by --allowedTools "Write", we asked it to create .env.test and a new file in prisma/migrations/. The migration stopped at the hook, despite the consent for Write:
PreToolUse:Write hook error: [bash ${CLAUDE_PROJECT_DIR}/.claude/hooks/protect-files.sh]: Blocked: .../prisma/migrations/20261115120000_tags/migration.sql is a saved migration. Change prisma/schema.prisma and ask for a new migration.Claude passed the message on and did not look for another way. .env.test had been stopped earlier by the Read(./.env.*) rule from lesson 8_4, with the general "File is covered by a Read deny rule". So for .env the hook is the second layer, and for migrations the only lock. In the session type /hooks as well: your hook stands under PreToolUse with the source in the project settings, and the Notification hook from lesson 7_3, if you have it, with the source in the user settings.
What a hook does not see
A hook with the Edit|Write matcher looks only at those two tools. When Claude adds a line with the command echo DEBUG=1 >> .env or changes a file through sed -i, the hook does not stir. The documentation advises adding a deny rule for Edit, for example Edit(./prisma/migrations/**), because the Read and Edit rules also cover recognised file commands in Bash (cat, sed, tee) and > redirects. A script that opens the file itself will get around even that; a wall at the system level comes only with the sandbox, which you will meet in lesson 14_7.
Remember also that a hook is a command that works with your permissions, in someone else's repository too. As lesson 14_1 said, claude -p in a cloned project will run the hooks from its .claude/settings.json without asking. Before you run a script on foreign code, read .claude/settings.json and .claude/hooks/, or switch hooks off for one run with the flag --settings '{"disableAllHooks": true}'. Hooks can also come in a skill's frontmatter and in a plugin, and in lesson 14_8 a Stop hook will send Claude back to work until the types agree.
Captain's review
Writein the matcher. A typical agent mistake is"matcher": "Edit", because the task said "before an edit". A new.env.localfile or a new migration goes throughWriteand gets around the hook. You will recognise it in the diff byEditalone.- Code 2 and stderr. Every block ends with
exit 2, and the message goes through>&2. Without the redirect Claude gets a block with no reason and will guess what to do next. jqon board.jq --versionmust work. WithoutjqtheFILEvariable is empty, the script ends with code 0 and lets everything through, andonFailurewill not catch that.- A trial. JSON given by hand gives 2 for
.envand migrations and 0 for.env.exampleandlib/pins.ts, and/hooksshows the entry.
Next step
Close the gap in Bash for the most dangerous Prisma command:
Extend protect-files.sh: when tool_input.command contains prisma migrate reset, end
with code 2 and a message. In settings.json add a second group with the Bash matcher.
Check the script with JSON given by hand before you ask for a commit.Then ask for a commit, for example "A hook protecting secrets and migrations". In the editor next to the lesson you will pick an event, a matcher, a call and an exit code, and the simulator will show whether the hook fires, what it gets as input and what happens to the tool.
Remember: what must happen always you do not write in the logbook, you nail to the deck.
Code for this lesson: App.tsx
// Hook simulator: event, matcher, tool call, exit code and what follows from it
import { useState } from 'react';
export type Tool = 'Edit' | 'Write' | 'Bash';
export type HookEvent = 'PreToolUse' | 'PostToolUse';
export type ExitChoice = 'script' | '0' | '1' | '2';
export interface Call {
tool: Tool;
target: string;
}
export const ROOT = '/x/treasure-map/';
export const CALLS: Call[] = [
{ tool: 'Edit', target: '.env' },
{ tool: 'Write', target: '.env.local' },
{ tool: 'Edit', target: '.env.example' },
{ tool: 'Write', target: 'prisma/migrations/20261115120000_tags/migration.sql' },
{ tool: 'Edit', target: 'prisma/schema.prisma' },
{ tool: 'Edit', target: 'lib/pins.ts' },
{ tool: 'Bash', target: 'echo DEBUG=1 >> .env' },
];
export function matcherHits(matcher: string, tool: string): boolean {
const m = matcher.trim();
if (m === '' || m === '*') return true;
if (/^[A-Za-z0-9_|, -]+$/.test(m)) {
return m.split(/[|,]/).map((s) => s.trim()).includes(tool);
}
try {
return new RegExp(m).test(tool);
} catch {
return false;
}
}
function casePattern(pattern: string, value: string): boolean {
const re = pattern.replace(/[.+?^$()[\]{}|\\]/g, (c) => '\\' + c).replace(/\*/g, '.*');
return new RegExp('^' + re + '$').test(value);
}
export interface ScriptResult {
code: number;
stderr: string;
}
export function runScript(call: Call): ScriptResult {
const file = call.tool === 'Bash' ? '' : ROOT + call.target;
if (casePattern('*/.env.example', file)) return { code: 0, stderr: '' };
if (casePattern('*/.env*', file)) {
return { code: 2, stderr: 'Blocked: ' + file + ' is a file with secrets. A human sets the variables in .env; add the missing name to .env.example.' };
}
if (casePattern('*/prisma/migrations/*', file)) {
return { code: 2, stderr: 'Blocked: ' + file + ' is a saved migration. Change prisma/schema.prisma and ask for a new migration.' };
}
return { code: 0, stderr: '' };
}
export function stdinFor(event: HookEvent, call: Call): string {
const input = call.tool === 'Bash' ? { command: call.target } : { file_path: ROOT + call.target };
return JSON.stringify({ hook_event_name: event, tool_name: call.tool, tool_input: input });
}
export interface Outcome {
fired: boolean;
code: number | null;
blocked: boolean;
text: string;
}
export function simulate(event: HookEvent, matcher: string, call: Call, exit: ExitChoice, onFailureBlock: boolean): Outcome {
if (!matcherHits(matcher, call.tool)) {
const gap = call.tool === 'Bash' && call.target.includes('.env')
? ' A deny rule for Edit patches this hole, as it also covers redirects in Bash.'
: '';
return { fired: false, code: null, blocked: false, text: 'The hook did not fire: the matcher "' + matcher + '" does not cover the tool ' + call.tool + '.' + gap };
}
const script = runScript(call);
const code = exit === 'script' ? script.code : Number(exit);
const note = call.tool === 'Bash' && exit === 'script'
? ' The script reads only file_path, so it lets a Bash command through; a separate condition on tool_input.command is needed.'
: '';
if (event === 'PostToolUse') {
if (code === 2) return { fired: true, code, blocked: false, text: 'The tool has already run. stderr goes to Claude, but it will not undo the change.' };
return { fired: true, code, blocked: false, text: 'A hook after the fact blocks nothing; this is how the formatting from lesson 7_1 works.' + note };
}
if (code === 2) {
const reason = exit === 'script' ? script.stderr : '(Your message from stderr)';
return { fired: true, code, blocked: true, text: 'Blocked before it runs, even when an allow rule would let it through. Claude gets: ' + reason };
}
if (code === 0) {
return { fired: true, code, blocked: false, text: 'No objection, but not consent: the permission rules and mode decide further.' + note };
}
return onFailureBlock
? { fired: true, code, blocked: true, text: 'A code other than 0 and 2 is a hook error, and onFailure: "block" turns it into a block.' }
: { fired: true, code, blocked: false, text: 'Code ' + code + ' is a non-blocking error: the tool runs on. Only code 2 guards the rule.' };
}
export default function App() {
const [event, setEvent] = useState<HookEvent>('PreToolUse');
const [matcher, setMatcher] = useState('Edit|Write');
const [index, setIndex] = useState(1);
const [exit, setExit] = useState<ExitChoice>('script');
const [onFailureBlock, setOnFailureBlock] = useState(true);
const call = CALLS[index];
const result = simulate(event, matcher, call, exit, onFailureBlock);
return (
<div className="min-h-screen space-y-4 bg-slate-950 p-4 text-slate-100">
<h1 className="text-xl font-bold">A hook on board Treasure Map</h1>
<div className="grid gap-3 text-sm md:grid-cols-2">
<label className="block">
Event{' '}
<select className="rounded bg-slate-800 p-1" value={event} onChange={(e) => setEvent(e.target.value as HookEvent)}>
<option value="PreToolUse">PreToolUse</option>
<option value="PostToolUse">PostToolUse</option>
</select>
</label>
<label className="block">
matcher{' '}
<input className="rounded bg-slate-800 p-1 font-mono" value={matcher} onChange={(e) => setMatcher(e.target.value)} />
</label>
<label className="block">
Call{' '}
<select className="rounded bg-slate-800 p-1 font-mono" value={index} onChange={(e) => setIndex(Number(e.target.value))}>
{CALLS.map((c, i) => (
<option key={i} value={i}>{c.tool}: {c.target}</option>
))}
</select>
</label>
<label className="block">
Exit code{' '}
<select className="rounded bg-slate-800 p-1" value={exit} onChange={(e) => setExit(e.target.value as ExitChoice)}>
<option value="script">as in protect-files.sh</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</label>
</div>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" checked={onFailureBlock} onChange={(e) => setOnFailureBlock(e.target.checked)} />
onFailure: "block"
</label>
<section>
<h2 className="font-semibold">What the hook gets as input</h2>
<pre className="overflow-x-auto whitespace-pre-wrap rounded bg-slate-900 p-2 font-mono text-xs">{stdinFor(event, call)}</pre>
</section>
<p role="status" className="rounded border border-slate-700 p-2 text-sm">
<strong className={result.blocked ? 'text-rose-400' : result.fired ? 'text-emerald-400' : 'text-amber-400'}>
{result.fired ? 'hook fired, code ' + result.code : 'hook did not fire'}
</strong>{' '}
{result.text}
</p>
</div>
);
}Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. CLAUDE.md says we do not edit migrations, and Claude fixed a file in prisma/migrations/ anyway. What will stop it every time and say what to do instead?
2. A PreToolUse hook with no onFailure field printed the reason on stderr and ended with code 1. What happens to the edit?
Hands-on tasks in the game
- Horizontal ordering
Arrange the line that gives the hook script JSON with the .env path and prints its exit code:
- Vertical ordering
Put the hook events in the order they occur while using a tool in a session: