# Claude Code Hooks: Format, Block and Enforce Rules

> Set up Claude Code hooks that format files after edits, block protected paths with exit 2, and fail closed with onFailure. Working JSON and a script to copy.

Canonical: https://bridge-terminal.com/atlas/blog/claude-code-hooks-format-block-enforce-rules/
Last updated: 2026-11-21

Published 21 November 2026 · Technical · From Atlas · 7 min read

## The short version

- A Claude Code hook is a command that runs at a fixed point in the session, so a rule happens every time instead of only when the model remembers it.
- Use PostToolUse hooks for chores after an edit, such as formatting, and PreToolUse hooks to stop an action before it runs.
- Only exit code 2 blocks; exit 1 is a non-blocking error, so a policy script that exits 1 enforces nothing.
- Set onFailure to block on a hook that guards something important, otherwise a crash or timeout lets the action go ahead.
- Hooks run with your user permissions, so review them like code and keep the shared ones in the project settings file.

Claude Code hooks are shell commands that Claude Code runs automatically at set points in a session: before a tool call, after a file edit, when Claude stops. They are how you make a rule happen every time, rather than hoping the model follows a line in your instructions file. This guide shows three hooks you can use today (format after edit, block protected files, fail closed) and the exit-code rules that decide whether a hook enforces anything.

The details below come from Anthropic's [hooks guide](https://code.claude.com/docs/en/hooks-guide) and [hooks reference](https://code.claude.com/docs/en/hooks). The scripts are my own illustrations built on the documented behaviour, so test them in your repo before you rely on them.

## What is a Claude Code hook?

The hooks guide describes hooks as user-defined shell commands that run at specific points in Claude Code's lifecycle. The point is deterministic control: "certain actions always happen rather than relying on the LLM to choose to run them."

An instruction in CLAUDE.md is a request. A hook is a mechanism. If "always run the formatter" matters, put it in a hook. If "prefer small functions" matters, an instructions file is the right place, because no script can judge it. For the instruction-file side, see [AGENTS.md and CLAUDE.md: one instruction file for both](https://bridge-terminal.com/atlas/blog/agents-md-claude-md-one-instruction-file/).

The reference lists 33 events. The ones you will use most:

- `PreToolUse`: fires before a tool call and can block it.
- `PostToolUse`: fires after a tool call. The tool has already run, so it cannot undo anything.
- `UserPromptSubmit`: can block a prompt.
- `Stop`: fires when Claude finishes responding.
- `TaskCompleted`: can stop a task being marked complete.
- `Notification`: fires when Claude needs your attention.

Hook types are `command` (runs a shell command, input arrives on stdin as JSON), `http`, `mcp_tool`, `prompt` and `agent`. The reference marks agent hooks as experimental. Start with `command`.

## Where do hooks go?

Hooks live in a `hooks` block in a settings file. Anthropic's [hooks blog post](https://claude.com/blog/how-to-configure-hooks) says settings can sit at the project level (`.claude/settings.json`), the user level (`~/.claude/settings.json`) or in a local project file (`.claude/settings.local.json`) for personal use. Put team rules in the project file so they are committed and shared; put personal conveniences, such as a desktop notification, in your user file. How the scopes combine is covered in [Claude Code settings.json: scopes and precedence](https://bridge-terminal.com/atlas/blog/claude-code-settings-json-scopes-precedence/).

The shape is always the same: an event name, a `matcher` that picks which tools it applies to, and a list of hooks.

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "/path/to/lint-check.sh" }
        ]
      }
    ]
  }
}
```

The matcher `Edit|Write` uses `|` to match either tool. A matcher made only of plain characters (letters, digits, `_`, `-`, spaces, commas and `|`) is compared as an exact string. Anything else is treated as a regular expression, so `mcp__memory__.*` matches every tool from the `memory` MCP server. A bare `mcp__memory` is exact-match only and matches no tool, which is an easy mistake.

## How do I format files after Claude edits them?

Use a `PostToolUse` hook with an `Edit|Write` matcher. The hook receives JSON on stdin describing the tool call; your script reads the edited path from it and runs your formatter.

```bash
#!/bin/bash
# .claude/hooks/format.sh  (illustrative; assumes jq and prettier are installed)
path=$(jq -r '.tool_input.file_path // empty')
[ -n "$path" ] && npx prettier --write "$path" >/dev/null 2>&1
exit 0
```

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/format.sh" }
        ]
      }
    ]
  }
}
```

Make the script executable with `chmod +x`. I have not checked the exact field names in the edit payload against the reference, so log stdin to a file once and confirm that `tool_input.file_path` is what your Claude Code version sends before you trust it.

This is the best first hook. It fixes a real annoyance (style diffs in review), it cannot do harm because the edit already happened, and it removes a recurring request from your prompts. The hooks blog post gives the same advice: start with one simple hook that fixes a real friction point.

## How do I block edits to protected files?

Formatting is a chore; blocking is a control. For that you need `PreToolUse`, because only events that run before the action can stop it. In the reference's exit-code table, `PostToolUse` shows stderr to Claude but the tool already ran.

Here is a protected-paths script:

```bash
#!/bin/bash
# .claude/hooks/protect-files.sh  (illustrative)
path=$(jq -r '.tool_input.file_path // empty')
case "$path" in
  *.env|*/migrations/*|*/.github/workflows/*)
    echo "Blocked: $path is protected. Ask the user before changing it." >&2
    exit 2
    ;;
esac
exit 0
```

```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/protect-files.sh" }
        ]
      }
    ]
  }
}
```

Exit code 2 blocks the call and, per the hooks blog post, stderr becomes the error message, so Claude sees why it was refused and can change course. Write that message as an instruction to the model.

A hook can also decide with JSON instead of an exit code. For `PreToolUse` the reference shows:

```json
{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "deny",
    "permissionDecisionReason": "Destructive command blocked by hook"
  }
}
```

`permissionDecision` accepts allow, deny, ask or defer. One subtlety from the reference: exiting 0 with no output sends the call through the normal permission flow. "The hook can deny the call, but staying silent doesn't approve it." A hook narrows what is allowed; it does not grant permission. For the allow and deny rules that sit beside hooks, read [Claude Code permissions: allow, deny rules and modes](https://bridge-terminal.com/atlas/blog/claude-code-permissions-allow-deny-rules/).

## Which exit code blocks, and which does not?

This is where most broken hooks come from. The reference says:

- Exit 0: success. The call goes on.
- Exit 2: blocking error on events that can block. On `PreToolUse` it blocks the call; on `Stop` it prevents Claude stopping and the conversation continues; on `UserPromptSubmit` it blocks the prompt. `TaskCompleted` is also listed among the events that can block completion.
- Exit 1 or any other code: a non-blocking error. The reference is direct: "If your hook is meant to enforce a policy, use `exit 2`."

Some events cannot be blocked at all. `PostToolUse` and `PostToolUseFailure` only show stderr to Claude, and `InstructionsLoaded` ignores the exit code.

A plausible failure is a script that runs `set -e`, hits a missing `jq`, exits 127 and lets everything through, since 127 is not 2. Which brings us to the next section.

## What happens when a hook crashes or times out?

By default, the action goes ahead. The reference says a timed-out command, HTTP or MCP hook does not block the tool call unless `onFailure` is set to `"block"`. The other value is `"continue"`. The setting needs Claude Code v2.1.295 or later (v2.1.328 for `mcp_tool` hooks).

```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "node",
            "args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/check-command.js"],
            "onFailure": "block"
          }
        ]
      }
    ]
  }
}
```

When `args` is present, the command is started directly as an executable with no shell, which avoids quoting problems with path placeholders.

With `"block"`, a failure does what exit 2 does on that event, except on `PermissionRequest`, where it denies the request. It has no effect on `Stop`, `SubagentStop`, `TaskCompleted` and `TeammateIdle` hooks, or on background hooks marked `async` or `asyncRewake`.

Use it on hooks that guard something you cannot afford to skip, such as a command checker. Leave it off for convenience hooks like formatters, where a crash should not stop your work. We cover the reasoning in [Claude Code hooks fail closed](https://bridge-terminal.com/atlas/blog/claude-code-hooks-fail-closed-onfailure-block/).

Timeouts: the reference gives 600 seconds as the default for `command`, `http` and `mcp_tool` hooks, 30 for `prompt` and 60 for `agent`, with lower limits on some events (for example 30 seconds for command hooks on `UserPromptSubmit`). Set a short `timeout` on anything that runs on every edit. Also note that matching hooks run in parallel, per the hooks blog post, so two hooks must not depend on each other's order.

## Can a hook make Claude keep working until tests pass?

Yes, with `Stop`. Exit 2 on `Stop` prevents Claude stopping, so a script that runs your test command and exits 2 with the failures on stderr sends Claude back to fix them. The reference also notes that on `Stop` and `SubagentStop`, `continue: false` takes precedence over exit 2 and ends the turn, and that `Stop` hooks receive `last_assistant_message`, so you do not need to parse the transcript. Make sure the script exits 0 once the checks pass, or the session never ends.

This is the mechanical version of "do not take the agent's word that it is done", a theme in [AI agent says it's done: how to check it really is](https://bridge-terminal.com/atlas/blog/ai-agent-says-done-how-to-check/).

## Safety and debugging

Hooks run arbitrary shell commands with your user permissions. Anthropic's hooks post says direct edits to hook configuration files need review in the `/hooks` menu before they take effect, and suggests:

- Validate and sanitise the stdin input.
- Quote shell variables and use absolute script paths.
- Avoid processing sensitive files such as `.env` or credentials.

My own addition: when a hook misbehaves, wrap it so it logs its input and its exit code to a file. Review a hook in a pull request as you would any script that executes on every developer machine, because that is what it is.

## Where Atlas fits

Atlas, the AI engineering team built on Claude Code, applies a similar idea (rules enforced by machinery, not by asking) at team level. Completion is refused until the work is on main or queued for the landing train and the product's rules pass, and checks that AI wrote once run as programs on each builder's change, with no model call. That is enforcement around the engineers' sessions, not hooks you edit. Atlas does not manage or show the hooks you write for each engineer today. Guardrail hooks that stop work when they break are coming to Atlas, built in, so they will need no setup. Until then, put your own hooks in the project's `.claude/settings.json`. See the [Atlas home page](https://bridge-terminal.com/atlas/) for how the team works.

## Conclusion

Start with one `PostToolUse` formatter, add one `PreToolUse` guard for the files that must never change without you, and put `onFailure: "block"` on the guard. Remember that exit 2 is the only code that blocks, and test each hook by deliberately breaking it. A hook that fails open looks the same as a hook that works until the day it matters.

## Questions people ask

### What is a hook in Claude Code?

A hook is a shell command that Claude Code runs automatically at a set point in its lifecycle, such as before a tool call or after a file edit. It makes an action happen every time instead of relying on the model to remember.

### Which exit code blocks an action in a Claude Code hook?

Exit code 2. On PreToolUse it blocks the tool call, and stderr becomes the error message Claude sees. Exit 1 and other codes are non-blocking errors, so they do not enforce a policy.

### What happens if a Claude Code hook crashes or times out?

By default the action carries on. Setting onFailure to block on a command, http or mcp_tool hook makes a failure act like exit 2 instead. It needs Claude Code v2.1.295 or later (v2.1.328 for mcp_tool hooks).

### Where do I put Claude Code hooks for my team?

In a hooks block in .claude/settings.json at project level, so they are committed and shared. Personal hooks can go in ~/.claude/settings.json or a local project file.

### Can a PostToolUse hook stop a bad edit?

No. The tool has already run by then, and exit 2 only shows stderr to Claude. To stop an action before it happens, use a PreToolUse hook.

## About Atlas: Rules enforced outside the session, as hooks aim to do

Atlas refuses to mark work done until it is on main or queued for the landing train and the product's rules pass, and AI-written checks run as programs on each builder's change. Managing your own hooks per engineer is not something Atlas does today; guardrail hooks that stop work when they break are coming to Atlas, built in, so they need no setup. Until then, put your own hooks in the project's .claude/settings.json. — https://bridge-terminal.com/atlas/

## Sources

- [Automate actions with hooks (Claude Code docs)](https://code.claude.com/docs/en/hooks-guide)
- [Hooks reference (Claude Code docs)](https://code.claude.com/docs/en/hooks)
- [Claude Code power user customization: How to configure hooks](https://claude.com/blog/how-to-configure-hooks)

_Researched and drafted with Claude, then checked against the sources above. Atlas is an independent product, not affiliated with Anthropic or OpenAI._

## Related

- [Claude Code Hooks as Guardrails: Block, Format, Test](https://bridge-terminal.com/atlas/blog/claude-code-hooks-guardrails/)
- [Claude Code -p: JSON Output, Schemas and Cost in Scripts](https://bridge-terminal.com/atlas/blog/claude-code-print-mode-json-output-scripts/)
- [Claude Code Now Fails Loudly When Automated Runs Break](https://bridge-terminal.com/atlas/blog/claude-code-automated-runs-exit-code-failures/)
