Summary audio
No audio recap for this lesson.
Study notes
What Hooks Are
- Deterministic code at fixed points in the loop that guarantee enforcement beyond formatting
- Turn rules from "Claude usually listens" into "Claude can't skip it"
- Claude code fires around 30 hook events
Common Hook Events
pre-tool use
- Fires before a tool call
- Return JSON with decision field: allow, deny, ask, or defer
- Exit 0 = success; exit 2 = blocking error
- Can return updated input to modify the tool call without blocking (useful for redacting secrets)
post-tool use
- Fires after a successful tool call
- Too late to stop the call, but can feed text back to Claude
- Use for auto-formatting or auto-linting
stop
- Fires when Claude wants to end their turn
- Exit 2 blocks the stop (says "you're not done")
session start
- Primes the environment
- Use source startup to run only on fresh starts
- Plain text output gets added to context
instructions loaded
- Fires when Claude. md or rule file loads
- Audit what made it into context
pre-compact and post-compact
- Fire before and after conversation compaction
- Use session start with compact matcher to re-inject context after compaction (not post-compact)
Exit Codes
- 0 = success (JSON parsed if provided; plain text ignored on most events)
- 2 = blocking error (standard error fed back to Claude as context)
- 1 = NOT blocking (Claude runs the command anyway)
- Other codes = non-blocking and locked
Key Patterns
- Redact secrets: return updated input instead of deny to rewrite tool calls
- Preserve state across compaction: session start hook with compact matcher re-injects file summaries
- Guard tools with pre-tool use; gate turns with stop
Takeaways
- Hooks are deterministic code at fixed loop points that enforce rules beyond formatting—turning "Claude usually listens" into "Claude can't skip it"
- pre-tool use lets you allow/deny/ask/defer tool calls or redact secrets by returning updated input; post-tool use can auto-format but can't block
- Exit code 0 = success, exit code 2 = blocking error that feeds to Claude, exit code 1 = non-blocking (Claude proceeds anyway)
- Use session start with compact matcher to re-inject context after conversation compaction, not post-compact
- stop hook with exit 2 blocks Claude from ending their turn; instructions loaded audits what made it into context
Flashcards 8 cards
Question
click to reveal · ←/→
Answer
click to flip back
Knowledge check 5 questions