Playbooks · Coding agents
Two hooks that enforce your coding conventions
Written October 26, 2026 · Edited November 20, 2026
For a solo developer × making two rules the agent cannot talk its way around × Claude Code hooks, ending with a formatter that runs on every edit and a guard that blocks force-pushes to main — both tested, both committed, and no more hooks than that.
Before you start
You need a project with a formatter already configured (the example uses Prettier; swap in your project's formatter) and a git repo with a main branch. You also need jq installed and on your path, because the official hooks documentation's own examples parse the hook input with it. The fail-closed setting in step 5 needs Claude Code 2.1.295 or later — that is the floor the hooks reference states for onFailure, and on an older version the setting does not take effect. The hook mechanics below are the official hooks reference, and the guard script's expected behavior against sample inputs is spelled out in the steps below. A hook you have not tested is a rule you have not enforced, whatever the settings file says.
The one distinction the whole page rests on: a rule in a prompt is advice the model can weigh and set aside, while a hook is a check that runs whether the model wants it or not. Hooks are for the two rules that must not be judged case by case. Everything else stays a prompt, or your hooks file becomes a second, worse linter that everyone learns to resent.
What "done" looks like
At the end of one sitting you have exactly two hooks, committed in the repo: a formatter hook that runs on every edited file, and a guard hook that blocks force-pushes to main. Each hook has a test you ran and can re-run, and you know the three ways a hook silently stops enforcing: the wrong exit code, a hook that fails to run, and a blocking attempt made in an event that cannot block.
Steps
- Pick two rules, and only two. Format on edit, and block force-push to main. Resist the third, fourth, and fifth hooks until these two have survived a week of real sessions. A hooks file that grows faster than your trust in it gets deleted whole the first time it annoys someone, and then you have zero hooks instead of two good ones.
- Put the hooks in project settings, not user settings. Hooks live in a
hookskey in a settings file. The official reference lists the scopes: user settings apply to all your projects, project settings live in.claude/settings.jsonand can be committed to the repo, and local settings are ignored by git. Project settings are the right scope here, because the formatter and the protected branch belong to the repo, and a teammate who clones it should get the same two guards you have. - Write the settings file. The configuration has three levels: the event, a matcher group that filters which tool calls it fires on, and the handler command. For this page the file is:
Check that the file is valid JSON before going further — a settings file that does not parse enforces nothing, and the failure will not announce itself.{ "hooks": { "PreToolUse": [ { "matcher": "Bash", "hooks": [ { "type": "command", "command": ".claude/hooks/block-force-push-main.sh", "onFailure": "block" } ] } ], "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write" } ] } ] } } - Write the guard script. A hook receives its event as JSON on stdin. The guard reads that JSON, pulls out the Bash command, and blocks only the exact danger: a git push that carries a force flag and names main. Save it as
.claude/hooks/block-force-push-main.shand make it executable:
The structure matters: the push check, then the force-flag check, then the branch check, each narrowing the last. A guard that blocks every force-push, including to a feature branch, will be bypassed the first time someone legitimately rewrites their own branch — and a bypassed guard is a deleted guard.#!/bin/bash INPUT=$(cat) COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // ""') if echo "$COMMAND" | grep -qE '(^|[[:space:]])git push([[:space:]]|$)'; then if echo "$COMMAND" | grep -qE '\-\-force(\-with\-lease)?([[:space:]]|$)|[[:space:]]-f([[:space:]]|$)'; then if echo "$COMMAND" | grep -qw 'main'; then echo "Blocked: force-push to main is not allowed" >&2 exit 2 fi fi fi exit 0 - Learn the exit-code rules before trusting any hook. The official reference's exit-code table is the whole enforcement model, and three rows decide whether your hooks work at all. First: exit code 2 is the blocking signal on events that can block — on
PreToolUseit blocks the tool call, and the message you write to stderr goes back to Claude. Second: any other non-zero exit is a non-blocking error — the action proceeds and you get a notice, so a guard script that crashes has stopped enforcing anything. Third:PostToolUsecannot block, because the tool already ran — its exit code 2 only feeds stderr back to Claude as feedback. That is why the formatter lives inPostToolUseand the guard lives inPreToolUse, and why swapping them would silently break both. One more row: a hook that fails to run does not block by default, so the guard entry above carries"onFailure": "block", which makes a failure act like exit code 2 — a broken guard must fail closed, not open. The field requires Claude Code v2.1.295 or later, so check your version before relying on it. - Test the guard against sample inputs before any session uses it. Feed the script the JSON it would receive and check the exit code for each case. Expect exit 2 for a force-push to main, for a force-with-lease push to main, and for a short-flag force-push to main; exit 0 for a normal push to main, for a force-push to a feature branch, and for a command that merely mentions force and main without being a push. Keep this test: re-run it whenever the script changes, and do not trust a guard whose test you cannot re-run.
- Test the formatter hook on a scratch file. Make a badly formatted file, have the agent edit it through the normal Edit or Write path, and confirm the file comes out formatted. If it does not, check the two usual suspects first: the formatter is not installed where the hook runs, or the matcher does not match the tool the agent actually used. A hook that never fires and a hook that fires and fails look identical from the outside — silent — so confirm the effect, not just the configuration.
- Commit the settings file and the scripts, then stop. Commit
.claude/settings.jsonand.claude/hooks/so the two guards travel with the repo. Then stop adding hooks. Live with two for a week. The next hook earns its place by a real incident — a rule broken twice that a hook would have caught — not by enthusiasm on setup day.
Check the agent's work
- Check that the settings file parses as JSON. A settings file that does not parse enforces nothing and complains about nothing.
- Check that the guard script is executable. A script Claude Code cannot run is a guard that never fires, and a hook that never fires fails open.
- Check that the guard blocks with exit 2, not exit 1. Any other non-zero exit is a non-blocking error and the push proceeds.
- Check that the formatter hook is in PostToolUse, not PreToolUse. A formatter cannot format a file that has not been written yet, and a PreToolUse formatter would run on the old content.
- Check that the guard entry carries onFailure block. Without it, a broken guard script fails open and the branch it protects is unprotected.
What can go wrong
- A guard that exits 1. Only exit 2 blocks. A script that ends with exit 1 on the danger case has written a stern message and then watched the push go through.
- A blocking attempt in an event that cannot block. PostToolUse, Notification, and several other events ignore the blocking signal because the action already happened or cannot be prevented. A "block" placed in one of those events is decoration, not enforcement — the reference's per-event table says which events can block, and it is worth reading before designing any hook.
- A guard that blocks too much. Block every force-push and the team routes around the guard within days. Block only force-pushes to main, and the guard survives contact with real work.
- Hook sprawl. Ten hooks, each firing on every tool call, slow every session and train everyone to ignore hook output. Two hooks, each with a test, beat ten hooks nobody can explain.
Limits
- Hooks run with your user's permissions, so a hook script is code that runs on your machine on the agent's behalf. Read every script before enabling it, and keep hooks in version control where changes are visible.
- Hooks do not replace review. A formatted file can still be wrong, and a branch protected from force-pushes can still receive a bad merge. The hooks enforce two rules; everything else still needs a human reading the diff.
Related playbooks
- Kiro 3.1: hooks that can veto compaction
- Check whether your Claude Code hooks are adding tokens to every prompt or cutting them
- Claude Code 2.1.329 warns where a folder's hooks live
- Claude agents now dream: memory that consolidates
Sources
Sources: Claude Code hooks reference.
Back to: Coding playbooks hub · Also: Run three independent lines of research at the same time in Claude Code, then combine the short summaries