Guarding Your Claude Code Workflow with Hooks
Claude Code Hooks let you run custom logic before or after any tool call. An earlier post covered using a Stop hook for task-completion notifications; this post covers four higher-leverage guardrails: blocking unnecessary Agent calls, auto-formatting C++ files, capturing verification screenshots after blog edits, and gating git commit on a clean Hexo build.
They share one origin story: every single one exists because I got burned first.
Hooks at a Glance
Configure Hooks under the hooks key in ~/.claude/settings.json. Three lifecycle events are supported:
| Event | Trigger Point | Typical Use Cases |
|---|---|---|
PreToolUse |
Before a tool runs | Blocking, validation, preprocessing |
PostToolUse |
After a tool runs | Formatting, notifications, verification |
Stop |
When a session ends | Notifications, wrap-up |
Each hook is a script that receives the tool-call payload as JSON on stdin. Exit code 0 allows execution to proceed; exit code 2 blocks the call.
Case 1: Blocking Agent Abuse
The pitfall: Claude Code sometimes spawns a subagent via the Agent tool for work a single Read call could finish—“read that file for me.” Spawning a subagent launches a new process and loads context, burning several seconds on work Read finishes in 0.1s. Worse is the Explore subagent, which runs broad codebase searches that are pure overkill for a simple lookup.
Hook script ~/.claude/hooks/pre_tool_use_agent_guard.py:
1 | #!/usr/bin/env python3 |
Design highlights:
- Unconditional
Exploreblock — Blunt but effective; local code lookups do not need a subagent process - Allowlist safeguard — Complex prompts such as “read the file and analyze the architecture” match the
analyzekeyword and pass through unblocked - Bilingual pattern matching — Covers both English and Chinese prompts so daily instructions in either language are caught
Configuration:
1 | { |
Setting matcher: "Agent" scopes the hook strictly to Agent invocations, leaving every other tool untouched.
Case 2: Auto-Formatting C++ Files
The pitfall: When Claude Code writes C++, the generated style often drifts from the repository’s conventions. Running clang-format manually—or reminding Claude to format after every edit—gets old fast. A PostToolUse hook formats C++ files automatically on every write, eliminating the problem permanently.
Hook script ~/.claude/hooks/clang-format.sh:
1 |
|
Design highlights:
- Reads
.tool_input.file_pathfrom stdin JSON — Claude Code passes tool parameters uniformly to hook scripts viastdin - In-place formatting via
clang-format -i— Applies formatting quietly without interrupting the workflow - Silent failure fallback — A missing
.clang-formatconfig or formatter error never blocks normal edits
Case 3: Automated Screenshot Verification for Blog Posts
The pitfall: After having Claude Code edit a blog post and pushing it live, I kept discovering broken layouts in production—overflowing code blocks, missing images, or tables blowing past the viewport. Capturing a full-page screenshot automatically after each edit catches visual regressions before git push.
Hook script <project-dir>/.claude/hooks/screenshot-hook.sh:
1 |
|
screenshot-verify.js drives Puppeteer and manages the local hexo server automatically. The script is longer, so here is its core pipeline:
- Check whether
hexo serveris already running (curl localhost:4000) - If not, start it with
hexo clean && hexo server - Open the edited post in Puppeteer and capture a full-page screenshot
- Save the image to
.claude-output/screenshots/and print the path back to the session
Design highlights:
- Tight path filtering — Fires only for
source/_posts/*and_config*.yml; edits elsewhere pay zero overhead - Automatic
hexo serverlifecycle — Starts the server on demand without spawning duplicates - Git-ignored output — Add
.claude-output/to.gitignoreso temporary screenshots never pollute version control
Case 4: Pre-Commit Hexo Build Gate
The pitfall: A single bad indentation in a post’s YAML Front Matter would slip past review and only surface when GitHub Actions failed after git push. A PreToolUse hook running hexo generate right before git commit blocks broken builds locally before a commit is even created.
Hook script ~/.claude/hooks/pre-tool-use-bash-guard.sh:
1 |
|
Design highlights:
- Targets
git commitonly —git add,git status, and other commands pass through immediately - Hard block on build failure — Writes the reason to
stderrand exits with code2(under theexit 2protocol, Claude readsstderras the rejection reason and ignoresstdout) - Silent on success —
hexo generateoutput is suppressed when the build passes, keeping the session noise-free
Complete Configuration Summary
1 | { |
| Hook | Event | matcher | Purpose |
|---|---|---|---|
| Agent guard | PreToolUse |
Agent |
Block Agent calls for work local tools can handle directly |
| Hexo build gate | PreToolUse |
Bash |
Verify the build before git commit |
| Screenshot verifier | PostToolUse |
Write|Edit |
Capture preview screenshots after post edits |
clang-format |
PostToolUse |
Write|Edit |
Auto-format C++ files on save |
Summary
The real value of Hooks is turning past pitfalls into automated guardrails. Every hook here maps to a concrete failure mode: wasted subagent calls, drifting C++ formatting, broken blog layouts, and post-push CI failures. Automate the check once instead of policing it manually every session.
Keep three principles in mind when writing Hooks:
- Be surgical with matching — The tighter your
matcherand path filters, the fewer false positives you get - Fail silently by default — A hook error should never break normal work unless blocking is explicitly its job
- Give actionable feedback — When blocking a call, explain clearly why it was blocked and what to do instead




