# Claude Code hooks: guardrails, gates, and live context

URL: https://developertoolkit.ai/en/claude-code/automate/hooks-automation/
Description: Configure Claude Code PreToolUse, PostToolUse, Stop, and SessionStart hooks with fail-closed guards, fixture tests, and safe CI isolation.

Claude Code hooks are deterministic handlers (shell commands, HTTP endpoints, MCP tools, prompts, or agents) attached to lifecycle events including `PreToolUse`, `PostToolUse`, `SessionStart`, and `Stop`. Unlike advisory `CLAUDE.md` instructions, hooks execute on every matching event so repositories block unsafe commands, protect files, lint every edit, and prevent completion while tests fail.

Your `CLAUDE.md` says "never edit merged migrations" and "run the tests before finishing", and last week the agent broke both rules anyway. Context instructions compete with everything else in the prompt window; hooks execute as code every single time. This guide is for developers and tech leads who own `.claude/settings.json` and want enforceable repository invariants.

## Choosing between CLAUDE.md, permissions, and hooks

Always place a rule in the simplest mechanism that reliably enforces it. Heavier layers add latency, maintenance, or extra model calls.

| Mechanism | Deterministic? | Best fit | Example |
| --- | --- | --- | --- |
| `CLAUDE.md` | Advisory only | Conventions, architecture context, commands | "Use `pnpm`, never `npm`" |
| `permissions.deny` | Yes (static pattern) | Fixed tool, command prefix, or file path bans | Deny `Read(./.env)`, deny `Bash(curl *)` |
| Command / HTTP hook | Yes (computed logic) | Checks inspecting payloads, file contents, or repo state | Lint edited file; block destructive SQL; gate `Stop` on tests |
| Prompt / Agent hook | Model-graded | Judgement checks that regex cannot express | Verify final reply cites the exact command and output |

Use static permission rules whenever a fixed pattern suffices—the [official hooks reference](https://code.claude.com/docs/en/hooks) treats hook `if` filters as best-effort optimisations and relies on the permission engine for hard bans ([permissions and sandboxing](/en/workflows/harness/permissions-and-sandboxing/)). For cross-tool setups spanning Claude Code, Codex, and Cursor, read [agent hooks as deterministic guardrails](/en/workflows/harness/agent-hooks/).

## Lifecycle events and the exit-code contract

Hooks merge across user, project (`.claude/settings.json`), local, managed policy, plugin, and skill/subagent scopes. Core events used in production repositories:

| Event | Fires when | Blocking behaviour |
| --- | --- | --- |
| `SessionStart` | Session starts, resumes, clears, or compacts | Non-blocking; plain stdout injects live context |
| `UserPromptSubmit` | User submits a prompt | Exit `2` blocks and rejects the prompt |
| `PreToolUse` | Before a tool executes | Exit `2` or JSON `permissionDecision: "deny"` blocks; stderr explains next step |
| `PermissionRequest` | Tool awaits permission decision | Decide via structured JSON output (exit `2` is ignored) |
| `PostToolUse` | After a tool succeeds | Cannot undo; exit `2` returns stderr to Claude for immediate self-correction |
| `Stop` / `SubagentStop` | Claude or subagent finishes a turn | Exit `2` or JSON `{"decision": "block"}` forces work to continue |
| `TaskCompleted` | Task is marked complete | Exit `2` blocks completion |

Four protocol invariants prevent broken gates:

- **Exit `0` succeeds; exit `2` blocks.** Any other exit code—including `1` or `127` from a missing binary or mistyped script path—**fails open** by default, letting the action proceed after a brief warning.
- **Set `"onFailure": "block"` on security-critical command or HTTP hooks.** Failing closed ensures that timeouts, missing scripts, malformed JSON, or non-2xx HTTP errors block `PreToolUse`, `UserPromptSubmit`, and `PermissionRequest` actions instead of waving them through.
- **Settings `permissions.deny` always beats a hook's `allow`.** Precedence across multiple hooks is `deny` > `defer` > `ask` > `allow`.
- **Matchers are exact unless they contain regex characters.** `Edit|Write` matches only those two tools; `mcp__github__.*` uses regex to match every tool on that server. Reference scripts via `${CLAUDE_PROJECT_DIR}` in exec form (`"args": []`) so working-directory changes never break paths.

Check the [official Claude Code hooks documentation](https://code.claude.com/docs/en/hooks) for the full event catalogue and JSON schemas.

## Four high-leverage hook patterns

Commit hook scripts under `.claude/hooks/`, mark them executable, and register them in `.claude/settings.json`. Keep `PreToolUse` scripts fast, local, and free of network calls.

### 1. PreToolUse: protect critical paths and destructive commands

Write deny messages as the exact next instruction Claude should follow:

```bash
#!/usr/bin/env bash
# .claude/hooks/protect-paths.sh (PreToolUse, matcher "Edit|Write")
set -euo pipefail
command -v jq >/dev/null || { echo "jq is required to verify path policy." >&2; exit 2; }
file=$(jq -r '.tool_input.file_path // empty')
rel=${file#"$CLAUDE_PROJECT_DIR"/}

case "$rel" in
  db/migrations/*|.env|.env.*|tests/acceptance/*)
    echo "Protected path: $rel. Describe the required change in your reply for human review." >&2
    exit 2 ;;
esac
```

Regex command hooks catch common mistakes (`rm -rf`, `git push --force`, `DROP TABLE`), yet shell indirection (`sh -c`, split flags, `sed -i`) can bypass pattern matching. Treat `PreToolUse` scripts as speed bumps backed by `permissions.deny` and OS sandboxing ([protecting the oracle](/en/workflows/test/protect-the-oracle/)).

### 2. PostToolUse: format and lint every edited file

Run your formatter and linter on the touched file; exit `2` with the first ~40 lines of lint errors on stderr so Claude repairs violations immediately before moving on.

### 3. Stop: refuse completion on failing tests (with loop protection)

Always inspect `stop_hook_active` so a failing suite gets one structured retry before escalating cleanly to a human instead of burning turns in a loop:

```bash
#!/usr/bin/env bash
# .claude/hooks/tests-before-stop.sh (Stop)
set -uo pipefail
retrying=$(jq -r '.stop_hook_active')
[[ -z $(git status --porcelain) ]] && exit 0

if out=$(npm test --silent 2>&1); then exit 0; fi
tail_out=$(tail -n 40 <<<"$out")

if [[ $retrying == "true" ]]; then
  jq -nc '{systemMessage: "Tests still fail after one retry. Stopping for human handoff."}'
  exit 0
fi
jq -nc --arg r "Test suite failed. Fix implementation before finishing:
$tail_out" '{decision: "block", reason: $r}'
```

### 4. SessionStart: inject live repository state

Print changing facts (current branch, dirty file count, latest CI status) on `SessionStart` with matcher `"startup|resume|compact"` so live state survives compaction while static rules remain in [`CLAUDE.md`](/en/claude-code/build/memory-system/). Register all four in `.claude/settings.json`:

```json
{
  "hooks": {
    "SessionStart": [
      { "matcher": "startup|resume|compact", "hooks": [{ "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/session-context.sh", "args": [] }] }
    ],
    "PreToolUse": [
      { "matcher": "Edit|Write", "hooks": [{ "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/protect-paths.sh", "args": [], "onFailure": "block" }] }
    ],
    "PostToolUse": [
      { "matcher": "Edit|Write", "hooks": [{ "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/format-and-lint.sh", "args": [], "timeout": 60 }] }
    ],
    "Stop": [
      { "hooks": [{ "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/tests-before-stop.sh", "args": [], "timeout": 180 }] }
    ]
  }
}
```

When a rule requires judgement rather than deterministic scripting—such as verifying that a final message actually cites the verification command and result—attach a `"type": "prompt"` hook to `Stop` or `SubagentStop` (keep prompt hooks off per-tool events to avoid extra model latency). For slower type checks that should not block edits, use asynchronous background hooks (`async` or `asyncRewake`) locally and keep synchronous gates in CI.

## Proving every hook works without reading regexes

Hooks guard production code and require their own automated tests:

1. **Run JSON fixture tests in CI.** Maintain `.claude/hooks/test-hooks.sh` alongside unit tests: pipe synthetic event payloads into each hook script (using stubbed binaries for fast `PostToolUse` and `Stop` checks) and assert exact exit codes and JSON decisions for both allow and deny cases—including known gaps recorded explicitly.
2. **Smoke-test live with debug logging.** Launch `claude --debug hooks` and trigger a blocked action to verify the hook fires, prints its actionable message, and produces zero "hook error" notices.
3. **Audit repo harness hygiene and gate edits via `CODEOWNERS`.** Run `npx @wondelai/harness-audit` to confirm deterministic hooks and protected paths are wired properly ([Harness Audit](/en/harness-audit/)), and require tech-lead review on `.claude/settings.json`, `.claude/hooks/`, and `.github/`.

**Copy-paste prompt: audit repository hooks and write missing fixtures**

```text
Audit .claude/settings.json, .claude/settings.local.json, and every script under .claude/hooks/.
For each hook report:
1. Event, matcher (exact vs regex), and whether onFailure is set for security gates.
2. Any execution path that exits 1 instead of 0 or 2, or lacks jq / error guards.
3. Whether Stop hooks check stop_hook_active and skip clean working trees.
4. Missing allow/deny cases in .claude/hooks/test-hooks.sh.
Propose minimal diffs and fixture tests; wait for my approval before editing.
```

## Hook security in CI and untrusted repositories

Command hooks execute with full local user privileges. Interactive sessions hold back repository hooks until you accept workspace trust, whereas headless `claude -p` and SDK sessions execute committed repository hooks immediately without a trust prompt.

Never run `claude -p` inside an untrusted checkout (such as a fork pull request or unreviewed repo) while API keys or deployment secrets exist in the environment. Isolate untrusted runs with `--bare --setting-sources "" --strict-mcp-config`, keep trusted scripts on the default branch, and enforce `allowManagedHooksOnly` in organization-wide managed settings when only admin-approved hooks may execute ([managed policy](/en/org/managed-policy/) and [agent threat model](/en/org/agent-threat-model/)).

## When Claude Code hooks fail silently or loop

- **Hook exits `1` and lets the action through.** Only exit `2` or JSON `deny` blocks. Eliminate `exit 1` on block paths, guard missing dependencies like `jq` with `exit 2`, and set `"onFailure": "block"`.
- **Mistyped path or timeout silently disables a gate.** Use `${CLAUDE_PROJECT_DIR}` in exec form (`"args": []`), test the exact configured paths in CI fixtures, keep `PreToolUse` hooks fast and local, and enable `"onFailure": "block"`.
- **JSON decision is ignored.** Extra stdout before `{` forces plain-text fallback. Redirect helper output to stderr or `/dev/null` and inspect `--debug hooks`.
- **Path protection has a Bash-shaped gap.** Blocking `Edit|Write` does not stop `sed -i` in Bash; layer `permissions.deny` and OS sandboxing ([permissions and sandboxing](/en/workflows/harness/permissions-and-sandboxing/)).
- **`Stop` hook loops or drags every turn.** Skip clean working trees, target fast unit or related tests, and escalate to a human when `stop_hook_active` is `true`.
- **Emergency kill switch.** Set `"disableAllHooks": true` in local settings for immediate debugging (managed enterprise hooks remain enforced unless disabled in managed policy).

## Official docs and next steps

Refer to the [official Claude Code hooks reference](https://code.claude.com/docs/en/hooks) for all lifecycle events, HTTP/MCP hook schemas, and timeout defaults.

- [Agent hooks across tools](/en/workflows/harness/agent-hooks/): register equivalent guardrails in Claude Code, Codex, and Cursor.
- [Custom subagents](/en/claude-code/automate/custom-subagents/): attach frontmatter hooks scoped to a single specialist's run.
- [Automated code reviews](/en/claude-code/ship/review-automation/): layer independent diff reviews after local hook gates pass.
- [Managed policy](/en/org/managed-policy/): enforce `allowManagedHooksOnly` and organization-wide security floors.
