D3 · Claude Code › Cluster 6 · Hooks

6.5 · Hook Use Cases

Format · guard · notify

CONCEPT The four canonical patterns

Most real hooks fall into four buckets, each pairing an event with a purpose:

PatternEventWhat it does
FormatPostToolUse · Edit|WriteRun a formatter/linter on the file Claude just edited
GuardPreToolUse · Edit|Write or BashBlock edits to protected paths or dangerous commands
NotifyNotification or StopDesktop alert when Claude needs input or finishes
Log / contextPostToolUse / SessionStartAudit-log tool use, or re-inject project context
🔑 The rule of thumb: deterministic actions that must always happen belong in hooks, not in a CLAUDE.md instruction the model might ignore. "Always run prettier after an edit" is a hook; "prefer functional style" is a memory instruction.

CONCEPT Format on PostToolUse, guard on PreToolUse

The timing is not arbitrary. Formatting must happen after the write, so it's a PostToolUse hook — the file already exists and you reshape it. Guarding must happen before the write, so it's a PreToolUse hook that can veto. Putting a guard in PostToolUse is too late; putting a formatter in PreToolUse has nothing to format yet.

DIAGRAM Each pattern on the timeline

flowchart TD U["UserPromptSubmit"] --> PRE["PreToolUse: GUARD
block .env / rm -rf"] PRE --> TOOL["Edit / Write / Bash runs"] TOOL --> POST["PostToolUse: FORMAT + LOG
prettier · append to audit log"] POST --> STOP["Stop: NOTIFY
desktop alert / sound"] SS["SessionStart: CONTEXT
re-inject conventions"] -.-> U classDef ok fill:#d4edda,stroke:#28a745,color:#155724; classDef gate fill:#ffe8cc,stroke:#ff9f40,color:#9a4a0a; class POST ok; class STOP ok; class SS ok; class PRE gate;

CODE Format, guard, and notify in one settings file

Auto-format edits (PostToolUse), protect sensitive files (PreToolUse calling a script that exits 2), and pop a desktop notification when Claude needs you (Notification).

{
  "hooks": {
    "PostToolUse": [
      { "matcher": "Edit|Write",
        "hooks": [
          { "type": "command",
            "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write" } ] }
    ],
    "PreToolUse": [
      { "matcher": "Edit|Write",
        "hooks": [
          { "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh" } ] }
    ],
    "Notification": [
      { "matcher": "",
        "hooks": [
          { "type": "command",
            "command": "osascript -e 'display notification \"Claude needs you\" with title \"Claude Code\"'" } ] }
    ]
  }
}

The guard script itself checks the path and exits 2 to block:

#!/bin/bash   # .claude/hooks/protect-files.sh
INPUT=$(cat)
FILE=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
for p in ".env" "package-lock.json" ".git/"; do
  if [[ "$FILE" == *"$p"* ]]; then
    echo "Blocked: $FILE matches protected pattern '$p'" >&2
    exit 2
  fi
done
exit 0

TRADE-OFFS Hook vs. asking the model to remember

✅ Enforce with a hook

  • Runs deterministically, every time — no reliance on the LLM
  • Survives context compaction and long sessions
  • Auditable and shareable via the repo

⚠️ Rely on CLAUDE.md instruction

  • Flexible, judgment-based, no scripting
  • But the model may forget, or the instruction may drift out of context
  • Not suitable for hard guarantees (formatting, blocking, audit)

EXAM TRAPS

Trap: Auto-formatting in a PreToolUse hook. → Too early — the edit hasn't happened. Format in PostToolUse; guard in PreToolUse.
Trap: "A PostToolUse guard can stop the write." → No, the write already landed. Protective guards must be PreToolUse so they can veto.
Trap: Only matching Edit|Write for a compliance scanner. → Claude can also change files via Bash. For full coverage, add a Stop hook that scans the tree once per turn, or also match Bash.
Trap: Putting "always format" in CLAUDE.md. → Memory is advisory; the model may skip it. Deterministic guarantees belong in a hook.

PRACTICE

Q1 · You want prettier to run on every file Claude edits. Which event + matcher?

PostToolUse with matcher "Edit|Write". Extract the path with jq -r '.tool_input.file_path' and pass it to prettier.

Q2 · Block any edit to .env. Where does the guard go and how does it block?

A PreToolUse hook (matcher Edit|Write) that checks .tool_input.file_path and exit 2s with a stderr reason when the path is protected.

Q3 · Why prefer a hook over a CLAUDE.md rule for "always run tests before stopping"?

A hook is deterministic — a Stop hook runs the check every time and can block stopping. A memory instruction is advisory and the model may forget it.