Claude Code Hooks and Subagents Step by Step
👋 In plain words: Hooks are small scripts Claude Code runs automatically at fixed moments, such as just before a command runs. They can block it, log it or add information, every time, whatever the model decides. Subagents are specialised helpers with their own instructions and tools. This lesson sets up both in a real project, step by step.
Instructions in CLAUDE.md are followed most of the time; hooks are followed every time. That difference is why the exam treats hooks as the tool for deterministic enforcement. In this lesson you will write a PreToolUse hook that protects a folder and watch Claude Code block a real command with it, add a PostToolUse hook that logs every edit, learn the main hook events and how hooks talk back to Claude, and define a read-only reviewer subagent in .claude/agents.
🔑 Key terms
- Hook event: the moment a hook runs, such as
PreToolUse(before a tool) orPostToolUse(after it). - Matcher: which tools a tool hook applies to, for example
BashorEdit|Write. - Exit code 2: the hook’s signal to block the action; its stderr is shown to Claude.
- Subagent file: a Markdown file in
.claude/agents/with frontmatter (name, description, tools, model) and a system prompt.
🪜 Step 1: Know the main hook events
| Event | Runs | Typical QA use |
|---|---|---|
PreToolUse |
Before a tool call | Block destructive commands, protect folders, require approval |
PostToolUse |
After a tool call succeeds | Run formatters or linters, log edits |
UserPromptSubmit |
When you send a prompt | Add context (current branch, ticket), block secrets in prompts |
SessionStart / SessionEnd |
At start and end | Load environment info, clean up |
Stop / SubagentStop |
When Claude (or a subagent) finishes | Run the test suite before “done” counts |
Notification, PreCompact |
On notifications, before compaction | Alerts, saving context |
Recent versions add more events; /hooks shows what your version supports.
🪜 Step 2: Write a PreToolUse hook that protects a folder
A command hook receives a JSON description of the event on stdin. Exit code 2 blocks the call, and whatever you print to stderr is sent to Claude as the reason:
📄 .claude/hooks/protect_migrations.py
import json
import sys
event = json.load(sys.stdin)
command = event.get("tool_input", {}).get("command", "")
if "migrations" in command and any(w in command for w in ("rm ", "del ", "mv ", "> ")):
print("Blocked: migrations/ is protected. Create a new migration instead of changing old ones.", file=sys.stderr)
sys.exit(2)
sys.exit(0)
📄 .claude/hooks/log_edits.py
import datetime
import json
import sys
event = json.load(sys.stdin)
with open(".claude/edit-log.jsonl", "a") as f:
f.write(json.dumps({"tool": event.get("tool_name"), "input": event.get("tool_input"),
"time": datetime.date.today().isoformat()}) + "\n")
Register both in the project’s .claude/settings.json:
📄 .claude/settings.json
{
"hooks": {
"PreToolUse": [
{"matcher": "Bash", "hooks": [{"type": "command", "command": "python .claude/hooks/protect_migrations.py"}]}
],
"PostToolUse": [
{"matcher": "Edit|Write", "hooks": [{"type": "command", "command": "python .claude/hooks/log_edits.py"}]}
]
}
}
📄 migrations/0001_init.sql
CREATE TABLE orders (id INT PRIMARY KEY);
🪜 Step 3: Watch the hook block a real command
Ask Claude Code to “clean up” the migrations. The model requests rm -rf migrations; the hook stops it:
⌨️ Terminal
claude -p "Clean up the old migrations folder." --allowedTools Bash --model claude-opus-5-5🖥️ Output (sample run)
I did not delete migrations/: the project hook blocked it because migrations are protected. If you need a schema change, I can create a new migration file instead.
📄 check.py
from pathlib import Path
print("migration still exists:", Path("migrations/0001_init.sql").exists())⌨️ Terminal
python check.py🖥️ Output
migration still exists: True
The command never ran: the real Claude Code harness called the hook, the hook exited with 2, and Claude received the hook’s message as the tool result. Even with --allowedTools Bash, the hook had the final say.
🪜 Step 4: Return structured decisions
Instead of exit codes, a hook can print JSON for finer control. For PreToolUse, a decision can allow, deny or ask the user, with a reason:
📄 .claude/hooks/ask_before_push.py
import json
import sys
event = json.load(sys.stdin)
if event.get("tool_input", {}).get("command", "").startswith("git push"):
print(json.dumps({"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "ask",
"permissionDecisionReason": "Pushing changes needs a human check.",
}}))
sys.exit(0)
Keep hooks fast (they run on every matching call), deterministic, and safe: a hook runs with your user’s permissions, so review hooks in pull requests like any other code.
.claude/settings.json hooks like a change to a build script: review it, and never pull hooks from an untrusted repository without reading them.🪜 Step 5: Define a subagent
Subagents live in .claude/agents/ (project) or ~/.claude/agents/ (personal). This one reviews test code but cannot edit anything:
📄 .claude/agents/test-reviewer.md
---
name: test-reviewer
description: Reviews test code for flakiness risks, weak assertions and missing negative cases. Use after tests are written or changed. Read-only.
tools: Read, Grep, Glob
model: sonnet
---
You review automated tests. For each file you are given:
1. Flag fixed sleeps, shared mutable test data and order dependence.
2. Flag assertions that would still pass if the feature were broken.
3. List missing negative and boundary cases.
Return a short list per file: issue, line, suggested fix. Do not rewrite the files.
- The description tells the main session when to delegate (“use after tests are written or changed”).
toolskeeps it read-only;modellets it run on a cheaper model.- Manage subagents with
/agents, or ask explicitly: “use the test-reviewer subagent on tests/ui/”.
🪜 Step 6: Combine hooks and subagents
A common QA setup:
- The main session writes or fixes tests.
- A
SubagentStoporStophook runspytest -qand blocks “done” if tests fail (exit code 2 with the failing summary on stderr). - The
test-reviewersubagent reviews the changed tests read-only. - A
PostToolUsehook logs every edit for the pull-request description.
Each piece has one job: hooks enforce, the subagent isolates review, and the main session does the work.
🌍 Real-world example: Ravi’s protected folders
Ravi’s team lost an afternoon when Claude Code “tidied” a folder of recorded API fixtures. A CLAUDE.md rule had said not to touch them. Ravi replaced the rule with a PreToolUse hook on Edit|Write|Bash that blocks any path under tests/fixtures/recorded/, plus a read-only test-reviewer subagent. The rule has held ever since, including in headless CI runs.
🧪 Practice Questions
Question 1. A CLAUDE.md rule says “never modify files in migrations/”, but Claude Code occasionally edits them during long sessions. What enforces the rule every time?
- A. Repeating the rule in capitals
- B. A PreToolUse hook (and/or deny permission rules) that blocks edits and commands touching migrations/
- C. A Skill about migrations
- D. Switching to plan mode permanently
Show answer
Answer: B. Hooks and permission rules are deterministic; CLAUDE.md guidance can be lost or ignored.
Question 2. How does a command hook block a PreToolUse action and tell Claude why?
- A. Exit code 0 with a message on stdout
- B. Exit code 2 with the reason printed to stderr
- C. Exit code 1 with no output
- D. Writing the reason into CLAUDE.md
Show answer
Answer: B. Exit code 2 is the blocking signal, and stderr is passed to Claude as the reason.
Question 3. Which two are good uses of a subagent in Claude Code? (Choose 2.)
- A. A read-only reviewer that checks changed tests
- B. Blocking git push –force in every session
- C. Reading large logs on a cheaper model and returning a summary
- D. Storing the team’s API keys
Show answer
Answer: A and C. Subagents isolate work with their own tools and model. Enforcement belongs to hooks; secrets belong in secret stores.
Question 4. A team wants every change Claude Code makes to be logged for audit. Which hook event fits?
- A. SessionStart
- B. PostToolUse with a matcher for Edit|Write (and Bash if needed)
- C. UserPromptSubmit
- D. PreCompact
Show answer
Answer: B. PostToolUse runs after each successful tool call, so it sees what was changed.
📝 Assignment
- Task 1: Add the
protect_migrations.pyhook (adapted to a folder you care about) to a test project and try to make Claude Code change that folder.
✅ Done when: the attempt is blocked with your message. - Task 2: Add a
Stophook that runs your fastest test command and exits 2 with the failure summary if it fails.
✅ Done when: Claude Code cannot finish while a test is red. - Stretch: Create the
test-reviewersubagent and run it on a test file with a deliberatetime.sleep(5)and a weak assertion.
✅ Done when: both issues are reported and no file was modified.
❓ Frequently Asked Questions
🤔 What are Claude Code hooks?
Commands that Claude Code runs automatically at events such as before or after a tool call. They can block, allow, ask, log or add context, deterministically.
🤔 How do I block a command in Claude Code?
Add a PreToolUse hook with a matcher (for example Bash) whose script exits with code 2 and prints the reason to stderr, or add a deny permission rule.
🤔 Where are Claude Code subagents defined?
As Markdown files with frontmatter in .claude/agents/ (project) or ~/.claude/agents/ (personal), or inside plugins.
🤔 Are hooks safe?
They run with your permissions, so review them like code, keep them fast and deterministic, and only use hooks from trusted sources.
🏁 Summary
- Hooks run at fixed events;
PreToolUsecan block,PostToolUsecan log and post-process. - Exit code 2 blocks and sends stderr to Claude; JSON output gives allow, deny or ask decisions.
- Configure hooks in
.claude/settings.jsonand review them like build scripts. - Subagents in
.claude/agents/have their own description, tools and model. - Combine them: hooks enforce, subagents isolate, the main session works.
Next, continue with Claude Code Headless Mode and GitHub Actions CI.
Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.