An editor has approved proof/final.md. Claude can keep drafting in proof/draft.md. A line in the team handbook tells an assistant how to behave. A hook lets Claude Code check the destination each time the assistant proposes a matching edit, before it changes the file.
A settings hook connects an event to an action through JSON configuration. The example below runs a local Python script. It covers Claude Code’s Edit and Write tools in one lab project. It is an editorial guardrail. File permissions and repository protections are the places to enforce who can alter a real approved proof through any program. Hooks guide
1. Pick the moment when a decision can still help
Choose PreToolUse to stop a proposed edit. Use PostToolUse to format a file after a successful edit, when the write has already happened. Other useful events include UserPromptSubmit to inspect a prompt, PostToolUseFailure to record a tool error, and SessionStart with a compact matcher to add a reminder after a conversation is summarized. A Stop hook can check completion, but needs an exit condition to avoid repeatedly asking for more work. Each event accepts its own fields and decisions. Event reference
2. Make a personal test project
Use a macOS, Linux or WSL terminal. Check python3 --version, git --version and claude --version. This exercise uses Claude Code 2.1.295 or later for its failure setting. Sign in to Claude, then return to the shell with /exit. Python downloads · Claude Code setup
Start a new lab. Run lab=$(mktemp -d "${TMPDIR:-/tmp}/claude-hook-lab.XXXXXX") && cd "$lab" && git init -q && pwd. Save the printed path. Paste each file-creation block in full, including its closing marker. Resume the lab. Type cd followed by a space and your saved path in quotes. Skip blocks for files you already have. To repeat the edits in step 5 with their original wording, start a new lab.
mkdir -p .claude/hooks proof
printf '%s\n' 'Approved wording.' > proof/final.md
printf '%s\n' 'Draft wording.' > proof/draft.md
Use .claude/settings.local.json for this trial. It applies to you in this project. The shared equivalent is .claude/settings.json, while ~/.claude/settings.json applies to your projects on this machine. A plugin can distribute the same kind of hook in hooks/hooks.json. In an existing repository, merge the new event into its settings instead of replacing the file. Settings scopes · Hook locations
3. Create the file check in .claude/hooks/protect_proof.py
cat > .claude/hooks/protect_proof.py <<'PY'
import json
import os
import sys
from pathlib import Path
event = json.load(sys.stdin)
root = Path(os.environ["CLAUDE_PROJECT_DIR"])
proposed = Path(event["tool_input"]["file_path"])
if not proposed.is_absolute():
proposed = Path(event["cwd"]) / proposed
approved = root / "proof/final.md"
try:
is_approved = proposed.samefile(approved)
except FileNotFoundError:
is_approved = proposed.resolve() == approved.resolve()
if is_approved:
print("The proof is approved. Put the change in proof/draft.md.", file=sys.stderr)
sys.exit(2)
PY
Claude Code writes the event as JSON to the process’s standard input. The tool’s arguments include the target file_path. For an existing target, samefile asks the filesystem whether both names identify the same file. It also catches a differently capitalized spelling on a case-insensitive disk. If a file does not exist yet, the fallback compares its proposed location with the reserved final path. CLAUDE_PROJECT_DIR anchors the protected proof at the lab root. For other targets the script reaches its end and exits successfully without printing anything. Hook input and project paths
For this PreToolUse command hook, exit 2 with a reason on standard error blocks the tool call. Exit 0 with no output lets Claude Code continue to its usual permission decision. Hooks can also return a structured decision as JSON. Command hook outcomes
4. Register the hook in .claude/settings.local.json
cat > .claude/settings.local.json <<'JSON'
{
"hooks": {
"PreToolUse": [{
"matcher": "^(Edit|Write)$",
"hooks": [{
"type": "command",
"command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/protect_proof.py\"",
"timeout": 5,
"onFailure": "block"
}]
}]
}
}
JSON
The event selects when, the matcher selects which tools, and the inner list says what to run. The quotes protect paths containing spaces. If this command takes over five seconds or crashes with exit 1, Claude Code normally continues to the usual permission decision. Here "onFailure": "block" stops that edit, even for the draft, until the checker works again. The denial will identify a failed or timed-out hook. Hook failure and timeout behavior
5. Test two sample events from the lab shell
printf '%s\n' '{"cwd":".","tool_input":{"file_path":"proof/draft.md"}}' |
CLAUDE_PROJECT_DIR="$PWD" python3 .claude/hooks/protect_proof.py
echo "draft exit = $?"
printf '%s\n' '{"cwd":".","tool_input":{"file_path":"proof/./final.md"}}' |
CLAUDE_PROJECT_DIR="$PWD" python3 .claude/hooks/protect_proof.py
echo "final exit = $?"
Expect draft exit = 0, then the editorial message and final exit = 2. These checks leave both files untouched. Run claude in the lab. If asked to trust the folder, compare the path with the one you saved. Type /hooks, find the local PreToolUse entry and close the panel with Escape. Send these prompts separately. Allow reads of the practice files and the draft edit if prompted.
Use the Edit tool to change “Draft wording.” to “Revised draft.” in proof/draft.md.Use the Edit tool to change “Approved wording.” to “Revised final.” in proof/final.md. If the tool is blocked, report the reason and stop.
Type /exit and run cat proof/draft.md proof/final.md. Expect Revised draft. then Approved wording. Check the session for an actual edit and a denial. To try a checker failure, add raise RuntimeError("practice failure") below import sys in the lab script. Start Claude again and ask it to use Edit to change “Revised draft.” to “Second draft.” in the draft and stop if blocked. Even this edit should be blocked with a hook error. Exit Claude, confirm the draft still reads Revised draft., then remove the practice line.
6. Choose handlers that fit the work
A command suits a local formatter, filename check or small calculation. An HTTP hook sends an event to a configured endpoint. Check what the payload contains before sending it off the machine. An MCP tool hook calls a configured server tool. Prompt and agent hooks use a model to evaluate a condition, which adds latency and token use. Event support varies by handler. Multiple matching handlers can run concurrently, so one script should not depend on another finishing first. Use async handlers for work that can finish later. A decision that must block this edit has to arrive before it runs. Handler types and execution
When the result surprises you
- Nothing fires. Check
/hooks, the project root, the event’s spelling and the actual tool name. If a change to the settings has not appeared, restart the session. An edit made outside Claude Code’s matched tools is outside this hook’s scope. - The script works in a shell but errors in Claude Code. Check that
python3is on the hook process’sPATH. Replay an event containing the same path. Keep diagnostic chatter off standard output when using JSON decisions. - Every edit feels slower. A synchronous hook sits in the edit path. Narrow the matcher, run the cheapest check first, and return little or no output on success.
- You want to undo the exercise. In this disposable lab, rename the configuration with
mv .claude/settings.local.json .claude/settings.local.off. Startclaudeagain and check/hooksfor the absence of that local entry. Running the Python script by hand still runs its rule. A distributed version should reference scripts relative toCLAUDE_PLUGIN_ROOTinside the plugin. Packaging hooks · Hook troubleshooting



