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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/env python3
"""
PreToolUse hook: Block the Agent tool when local tools can handle simple operations directly.
"""

import json
import sys

hook_input = json.load(sys.stdin)
tool = hook_input.get("tool_name", "")

if tool != "Agent":
sys.exit(0)

tool_input = hook_input.get("tool_input", {})
prompt = tool_input.get("prompt", "").lower()
subagent_type = tool_input.get("subagent_type", "")

# Block Explore agent unconditionally: use Glob/Grep/Read directly for local code exploration
if subagent_type == "Explore":
print(
"Explore agent blocked: use Glob/Grep/Read directly for local code exploration "
"instead of delegating through a subagent (CLAUDE.md rule).",
file=sys.stderr,
)
sys.exit(2)

# Simple operation keywords (block on match)
SIMPLE_PATTERNS = [
"read the following", "read file", "return full content",
"get the content", "fetch the file", "list files",
"search for", "find files", "grep for",
"read the following", "read file", "list files",
"search", "find files", "return full content",
]

# Complex operation keywords (skip blocking on match)
COMPLEX_PATTERNS = [
"analyze", "compare", "understand", "design", "implement", "evaluate",
"plan", "organize", "report",
"analyze", "compare", "design", "implement", "evaluate", "report",
]

complex_matched = [p for p in COMPLEX_PATTERNS if p in prompt]
matched = [p for p in SIMPLE_PATTERNS if p in prompt]

if matched and not complex_matched:
print(
f"Agent blocked: matched keyword '{matched[0]}'. "
f"Use Read/Glob/Grep directly instead.",
file=sys.stderr,
)
sys.exit(2)

sys.exit(0)

Design highlights:

  • Unconditional Explore block — 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 analyze keyword and pass through unblocked
  • Bilingual pattern matching — Covers both English and Chinese prompts so daily instructions in either language are caught

Configuration:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"hooks": {
"PreToolUse": [
{
"matcher": "Agent",
"hooks": [
{
"type": "command",
"command": "python3 ~/.claude/hooks/pre_tool_use_agent_guard.py"
}
]
}
]
}
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/bin/bash
# PostToolUse hook: Run clang-format automatically after C++ file edits

INPUT=$(cat)

FILE_PATH=$(echo "$INPUT" | python3 -c "
import json, sys
try:
data = json.load(sys.stdin)
print(data.get('tool_input', {}).get('file_path', ''))
except Exception:
print('')
" 2>/dev/null)

# Exit quietly if no file path was provided
[ -z "$FILE_PATH" ] && exit 0

# Only process C/C++ source and header files
case "$FILE_PATH" in
*.cpp|*.cc|*.cxx|*.c|*.h|*.hpp|*.hh)
[ ! -f "$FILE_PATH" ] && exit 0
clang-format -i "$FILE_PATH" 2>/dev/null
if [ $? -eq 0 ]; then
echo "Auto-formatted: $FILE_PATH"
fi
;;
esac

exit 0

Design highlights:

  • Reads .tool_input.file_path from stdin JSON — Claude Code passes tool parameters uniformly to hook scripts via stdin
  • In-place formatting via clang-format -i — Applies formatting quietly without interrupting the workflow
  • Silent failure fallback — A missing .clang-format config 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/bin/bash
# PostToolUse hook: Capture a verification screenshot after post/config edits

PROJECT_DIR="${CLAUDE_PROJECT_DIR:-$(pwd)}"
INPUT=$(cat)

# Extract file_path (with recursive fallback)
FILE_PATH=""
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty' 2>/dev/null)
[ -z "$FILE_PATH" ] && FILE_PATH=$(echo "$INPUT" | jq -r '.. | objects | select(has("file_path")) | .file_path' 2>/dev/null | head -1)

[ -z "$FILE_PATH" ] && exit 0

# Trigger only for blog posts and site config files
case "$FILE_PATH" in
*source/_posts/*|*_config*.yml)
echo "📸 Generating preview screenshot..."
node "$PROJECT_DIR/.claude/hooks/screenshot-verify.js" "$FILE_PATH" 2>&1
;;
esac

screenshot-verify.js drives Puppeteer and manages the local hexo server automatically. The script is longer, so here is its core pipeline:

  1. Check whether hexo server is already running (curl localhost:4000)
  2. If not, start it with hexo clean && hexo server
  3. Open the edited post in Puppeteer and capture a full-page screenshot
  4. 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 server lifecycle — Starts the server on demand without spawning duplicates
  • Git-ignored output — Add .claude-output/ to .gitignore so 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/bin/bash
# PreToolUse hook: Verify hexo build before git commit

INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // ""' 2>/dev/null)

# Intercept git commit only
echo "$COMMAND" | grep -q 'git commit' || exit 0

PROJECT_DIR="${CLAUDE_PROJECT_DIR:-$(pwd)}"

# Run hexo generate to verify the build
cd "$PROJECT_DIR"
hexo generate > /dev/null 2>&1

if [ $? -ne 0 ]; then
echo "hexo generate failed. Fix the post formatting before committing." >&2
exit 2
fi

exit 0

Design highlights:

  • Targets git commit only — git add, git status, and other commands pass through immediately
  • Hard block on build failure — Writes the reason to stderr and exits with code 2 (under the exit 2 protocol, Claude reads stderr as the rejection reason and ignores stdout)
  • Silent on success — hexo generate output is suppressed when the build passes, keeping the session noise-free

Complete Configuration Summary

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
{
"hooks": {
"PreToolUse": [
{
"matcher": "Agent",
"hooks": [
{
"type": "command",
"command": "python3 ~/.claude/hooks/pre_tool_use_agent_guard.py"
}
]
},
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "bash ~/.claude/hooks/pre-tool-use-bash-guard.sh"
}
]
}
],
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "bash <project-dir>/.claude/hooks/screenshot-hook.sh"
}
]
},
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "bash ~/.claude/hooks/clang-format.sh"
}
]
}
]
}
}
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 matcher and 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

Series Navigation