Episode 5: Hook - Event-Driven Automation
Hooks allow you to insert custom scripts (Shell or Node.js) into the Claude Code lifecycle. While they don't directly grant Claude new "action" capabilities, they significantly enhance automation and workflow control.
Hook Event Types
| Event | Trigger | Typical Use Case |
|---|---|---|
| SessionStart | Session start, clear, or compact | Start background services, inject init context |
| UserPromptSubmit | User hits Enter to send message | Auto-link external memory, preprocess requirements |
| PreToolUse | Before Claude calls a specific Tool | Permission interception, safety review, auto-backup |
| PostToolUse | After Tool execution completes | Auto-sync state, log operations, trigger notifications |
| Stop | After Claude finishes generating response | Summarize highlights, clean up temporary files |
| SessionEnd | When the session is closed | Stop services, save persistent data |
How Hooks Work
Hooks receive context in JSON format via stdin (e.g., the Tool being called and its arguments) and return a decision via stdout.
sequenceDiagram
participant Claude
participant Engine as Hook Engine
participant Script as Hook Script
participant Tool
Claude->>Engine: try calling Write(file.ts)
Engine->>Script: stdin: { "tool": "Write", "args": {...} }
Script->>Script: Logic check (e.g., coding standards)
Script-->>Engine: stdout: { "decision": "allow" }
Engine->>Tool: Execute Write
Tool-->>Claude: Return SuccessExample: GSD's Permission Guard
GSD implements a security layer via PreToolUse hooks. If you try to bypass the standard GSD workflow and modify core files directly, the Hook intercepts the request and prompts you to use the correct slash command.
The matcher Field
You can use the matcher field to precisely control which Tools trigger a Hook.
"matcher": "Write|Edit": Triggers only for file modifications."matcher": "*": Triggers for all Tool calls.