Agent Upstart

Cool things people are building with agents — and practical help getting the most out of them.

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

  1. 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.
  2. Put the hooks in project settings, not user settings. Hooks live in a hooks key in a settings file. The official reference lists the scopes: user settings apply to all your projects, project settings live in .claude/settings.json and 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.
  3. 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:
    {
      "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" }
            ]
          }
        ]
      }
    }
    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.
  4. 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.sh and make it executable:
    #!/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
    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.
  5. 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 PreToolUse it 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: PostToolUse cannot block, because the tool already ran — its exit code 2 only feeds stderr back to Claude as feedback. That is why the formatter lives in PostToolUse and the guard lives in PreToolUse, 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.
  6. 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.
  7. 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.
  8. Commit the settings file and the scripts, then stop. Commit .claude/settings.json and .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

What can go wrong

Limits

Related playbooks

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