Skip to main content

Hooks, Pre-commit, and Quality Gates

Advanced

Applies to: any repo where an agent edits code and you need certain checks to always run · Time to learn: 45 min reading + 30 min exercise · Lever: guardrails + feedback

AGENTS.md, rules, and skills are advice: the model usually follows them, but nothing forces it to. Hooks, permissions, pre-commit, and CI are enforcement: they run whether or not the model remembers. This page shows how to stack them so a mistake is caught at the cheapest possible point.

TL;DR
  • Advisory (AGENTS.md, rules, skills) can be ignored. Enforced (hooks, permissions, pre-commit, CI) cannot.
  • Use a PostToolUse hook to format after every edit, a PreToolUse hook to block protected paths, and a Stop hook to feed test failures back.
  • Exit code 2 blocks only on events that can block. PostToolUse cannot undo an edit that already happened.
  • Pre-commit (or prek, or lefthook) gates every commit; CI is the final gate.
  • Hooks run arbitrary shell with your credentials: review them like code and keep them fast.

Why it matters in the AI age​

Anthropic's Claude Code guidance says it directly: rules and CLAUDE.md are context, not enforcement; use hooks for actions that must happen every time (memory docs, best practices). An agent that can run a verification step and read its output is far more reliable than one that cannot, and a Stop hook can hold the turn open until that check passes (best practices). For FDEs in unfamiliar client repos, gates also protect the client: the agent cannot touch production config or commit a secret even on a bad day.


Core concepts​

Advisory versus enforced​

LayerExamplesWho enforcesCan the model skip it?
AdvisoryAGENTS.md, .claude/rules/, skillsThe model's attentionYes
Enforced at edit timeHooks, permission rulesThe harnessNo
Enforced at commit timepre-commit / prek / lefthookGitOnly with --no-verify
Enforced at merge timeCI, code reviewThe server and humansNo

The defense-in-depth ladder​

Each rung is slower and more complete than the one before. Push as many checks as possible to the left, where feedback reaches the agent in seconds. CI remains the final gate; see How We Build for our CI pipeline.

Claude Code hook events​

Claude Code documents 33 hook events (as of 2026-10). These eight cover most needs (hooks reference):

EventFiresTypical useExit 2 blocks?
SessionStartSession begins or resumesPrint plan status, load contextNo
UserPromptSubmitYou submit a promptInject context, screen promptsYes
PreToolUseBefore a tool callBlock protected paths or commandsYes
PostToolUseAfter a tool call succeedsFormat, lint, logNo (tool already ran; stderr is shown to Claude)
NotificationClaude needs attentionDesktop alertNo
StopClaude finishes a turnRun tests, force continuationYes
SubagentStopA subagent finishesVerify subagent outputYes
PreCompactBefore context compactionSave stateYes

Settings structure and matchers​

Hooks live in ~/.claude/settings.json, .claude/settings.json (commit it), .claude/settings.local.json (personal), managed policy, plugin hooks/hooks.json, and skill or subagent frontmatter. The structure is event, then matcher group, then handlers (hooks reference):

.claude/settings.json (shape)
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"if": "Bash(rm *)",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.sh",
"args": []
}
]
}
]
}
}
ItemRule
matcher*, empty, or omitted matches all. Plain strings or |-separated lists match exactly. Anything else is treated as an unanchored JavaScript regex. Ignored on events without a matcher.
typecommand, http, mcp_tool, prompt, or agent
timeoutSeconds. Defaults: 600 for command, http, mcp_tool; 30 for prompt; 60 for agent
ifOptional permission-rule filter, such as Bash(rm *)
${CLAUDE_PROJECT_DIR}Project root, for stable script paths

The hook receives JSON on stdin with common fields (session_id, transcript_path, cwd, permission_mode, hook_event_name) plus event fields such as tool_name and tool_input (hooks reference).

Exit code semantics​

Exit codeMeaning
0Success. JSON on stdout is applied. For SessionStart and UserPromptSubmit, plain-text stdout is added as context for Claude
2Blocking error on events that can block; stderr is the reason
Any otherNon-blocking error; the action proceeds

Two traps. First, exit 1 does not block: the docs say to use exit 2 if the hook enforces policy. Second, exit 2 does nothing to stop a tool on PostToolUse, PermissionRequest, Notification, or SessionStart; the action already happened or cannot be blocked there (hooks reference). For a PreToolUse deny with a reason, you can also print JSON and exit 0:

{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "Database writes are not allowed"
}
}

How to do it​

1. Format after every edit (PostToolUse)​

Matcher Write|Edit fires after Claude writes or edits a file. The hook input includes tool_input.file_path for Write (hooks reference); Edit's input uses the same file_path field.

.claude/settings.json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/format.sh",
"timeout": 30
}
]
}
]
}
}
.claude/hooks/format.sh
#!/usr/bin/env bash
# Route by extension to the right formatter. Never block: formatting is best effort.
f=$(jq -r '.tool_input.file_path // empty')
[ -z "$f" ] && exit 0
case "$f" in
*.py) ruff format "$f" && ruff check --fix "$f" ;;
*.ts|*.tsx|*.js|*.jsx|*.json) biome check --write "$f" ;;
*.go) gofmt -w "$f" ;;
*.tf|*.tfvars) tofu fmt "$f" ;;
esac
exit 0

Make it executable (chmod +x .claude/hooks/format.sh). Lint errors that remain after --fix print to the hook's output; to make Claude see them, print them to stderr and exit 2 (PostToolUse shows stderr to Claude; the edit is not undone).

2. Block edits to protected paths (PreToolUse)​

.claude/settings.json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/protect-paths.sh",
"timeout": 5
}
]
}
]
}
}
.claude/hooks/protect-paths.sh
#!/usr/bin/env bash
f=$(jq -r '.tool_input.file_path // empty')
case "$f" in
*.env|*/.env.*|*/package-lock.json|*/uv.lock|*/go.sum|*/.terraform.lock.hcl|*/infra/prod/*)
echo "Blocked: $f is protected. Ask the user to change it or edit it themselves." >&2
exit 2 ;;
esac
exit 0

Exit 2 stops the tool call and returns the stderr text to Claude, which then picks another approach. Lockfiles should change through the package manager (uv lock, npm install), never by hand.

3. Run tests and lint when Claude stops (Stop)​

A Stop hook can refuse to let Claude finish while checks fail. Always check stop_hook_active: it is true when Claude is already continuing because of a stop hook, and ignoring it can loop forever (hooks reference).

.claude/settings.json
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/stop-check.sh",
"timeout": 120
}
]
}
]
}
}
.claude/hooks/stop-check.sh
#!/usr/bin/env bash
input=$(cat)
# Already continuing because of this hook: let Claude stop to avoid a loop.
[ "$(jq -r '.stop_hook_active' <<<"$input")" = "true" ] && exit 0

out=$(cd "$CLAUDE_PROJECT_DIR" && mise run check 2>&1) && exit 0

# Feed a trimmed failure report back; decision "block" keeps Claude working.
jq -n --arg r "Checks failed. Fix these, then finish:
$(tail -n 40 <<<"$out")" '{decision: "block", reason: $r}'
exit 0

mise run check stands for whatever single fast command your repo uses for tests plus lint (see The Agent-Ready Toolchain). The Stop output format, decision: "block" with a reason, is documented in the hooks reference. Trim the output: dumping a full test log wastes context (Context Engineering).

4. Print the plan status at session start (SessionStart)​

For SessionStart, plain-text stdout is added to Claude's context before the first prompt; matcher values are startup, resume, clear, compact, and fork (hooks reference).

.claude/settings.json
{
"hooks": {
"SessionStart": [
{
"matcher": "startup|resume|clear|compact",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/plan-status.sh",
"timeout": 10
}
]
}
]
}
}
.claude/hooks/plan-status.sh
#!/usr/bin/env bash
# Print the Progress section of every plan under plans/ (adapt the path to your repo).
for p in "$CLAUDE_PROJECT_DIR"/plans/*.md; do
[ -e "$p" ] || exit 0
echo "== $(basename "$p")"
awk '/^## Progress/{f=1;next} /^## /{f=0} f' "$p" | tail -n 15
done

Including compact and clear re-injects the plan after those events, so the agent re-orients itself. See Execution Plans for the plan format.

5. Permissions: allow and deny lists​

Permission rules are evaluated deny first, then ask, then allow; the first match wins, and an allow rule cannot carve an exception out of a deny rule (permissions docs).

.claude/settings.json
{
"permissions": {
"allow": [
"Bash(npm run *)",
"Bash(mise run *)",
"Bash(git diff *)"
],
"deny": [
"Bash(git push *)",
"Read(./.env)",
"Read(./secrets/**)",
"Edit(infra/prod/**)"
]
}
}

Syntax notes from the docs: Bash(npm run *) allows any npm run command; the space before a trailing * matters (Bash(ls *) does not match lsof). Use Read(path) and Edit(path) for files: Write(path) rules are accepted but never match, so write Edit(docs/**) instead. Bash argument patterns are fragile (for example, URL restrictions), so use deny rules for dangerous commands and hooks for anything you need to be exact. The bare permissions.allow list merges across settings scopes (settings docs).

Permissions and hooks complement each other: permissions decide what the agent may do, hooks run code at the moment it does it.

6. OpenCode and Codex equivalents​

HarnessMechanismWhereNotes
Claude CodeHooks in settings JSON.claude/settings.jsonDescribed above
OpenCodePlugins: JS/TS modules returning a hooks object.opencode/plugins/ or ~/.config/opencode/plugins/Events include tool.execute.before, tool.execute.after, file.edited, session.idle, permission.asked
CodexHooks in hooks.json or [hooks] tables in config.toml<repo>/.codex/ or ~/.codex/Events include PreToolUse, PostToolUse, Stop, SessionStart; project hooks load only when the .codex/ layer is trusted; exit 2 blocks on PreToolUse, UserPromptSubmit, Stop, SubagentStop, PostToolUse

OpenCode hooks are code, not config:

.opencode/plugins/protect-env.ts
export const EnvProtection = async ({ project, client, $, directory, worktree }) => {
return {
"tool.execute.before": async (input, output) => {
// inspect input/output and throw to block, e.g. when the path is .env
},
}
}

Sources for the plugin signature and event names: OpenCode plugins. Codex: Codex hooks. Whichever harness you use, the pre-commit layer below works unchanged, which is why it is the most portable gate (see Agent Harnesses).

7. Pre-commit frameworks​

ToolWhat it isConfigNotes
pre-commitThe original multi-language hook framework.pre-commit-config.yamlInstall: pip install pre-commit
prekRust drop-in alternative to pre-commit, MITReads .pre-commit-config.yaml and its own prek.tomlInstall: uv tool install prek; project claims it is multiple times faster and uses less disk
lefthookFast Git hook managerlefthook.ymlInstall the hooks with lefthook install; supports parallel, glob, stage_fixed

Choose prek or pre-commit if you want the large ecosystem of shared hook repos with one YAML file (prek runs the same file); choose lefthook if you prefer running your own commands (from mise tasks, for example) with globs. Sources: pre-commit, prek, lefthook.

.pre-commit-config.yaml
# Run `pre-commit autoupdate` (or `prek autoupdate`) after copying this, review the
# diff, and keep the revs pinned. Revs below were current on 2026-10-22.
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.17.2
hooks:
- id: ruff-check
args: [ --fix ]
- id: ruff-format

- repo: https://github.com/biomejs/pre-commit
rev: v2.6.2
hooks:
- id: biome-check

- repo: https://github.com/golangci/golangci-lint
rev: v2.15.0
hooks:
- id: golangci-lint-fmt
- id: golangci-lint

- repo: https://github.com/tofuutils/pre-commit-opentofu
rev: v2.4.2
hooks:
- id: tofu_fmt
- id: tofu_validate

- repo: https://github.com/gitleaks/gitleaks
rev: v8.30.1
hooks:
- id: gitleaks

Install and run: pre-commit install (or prek install), then pre-commit run --all-files. The golangci-lint hook ids golangci-lint (runs golangci-lint run --new-from-rev HEAD --fix) and golangci-lint-fmt come from that repo's .pre-commit-hooks.yaml. The gitleaks hook runs gitleaks git --pre-commit --redact --staged --verbose on staged changes. If your Biome version in the project differs from v2.6.2, match the hook rev to the version in biome.json's $schema.

The same gates in lefthook (the tofu and gitleaks commands assume the binaries are on PATH, for example through mise):

lefthook.yml
pre-commit:
parallel: true
jobs:
- run: ruff check --fix {staged_files}
glob: "*.py"
stage_fixed: true
- run: ruff format {staged_files}
glob: "*.py"
stage_fixed: true
- run: biome check --write {staged_files}
glob: "*.{ts,tsx,js,jsx,json}"
stage_fixed: true
- run: golangci-lint run
glob: "*.go"
- run: tofu fmt -recursive
glob: "*.tf"
stage_fixed: true
- run: gitleaks git --pre-commit --redact --staged --verbose

Activate it with lefthook install.

8. "Post-update" automation​

Two complementary mechanisms keep the repo coherent after every change:

MechanismRunsDoes
PostToolUse hook (step 1)After every Write or EditFormat only the file touched; seconds
post-change-update skillWhen you invoke /post-change-update after a taskFull check run, doc updates, plan progress log, scratchpad (Skills and Skill Creation)
SessionStart hook (step 4)Each session start, resume, clear, compactShows the plan status so the next session starts oriented

The hook handles the mechanical, per-edit work with guaranteed execution; the skill handles judgment work (which docs changed meaning?) that a script cannot do. Keep the split: never put doc rewriting in a hook.

CI is the final gate. Everything above can be bypassed locally (--no-verify, a disabled hook), so run the same linters again in the pipeline described in How We Build.

9. Safety​

Hooks run arbitrary shell commands with your user's permissions and credentials. Treat them like code:

  • Review every hook in a pull request, and review hooks that arrive via plugins or a cloned repo before trusting them.
  • Keep hooks fast. Set an explicit timeout (the command default is 600 seconds, far too long for an edit hook). Rough budgets: PostToolUse under a few seconds, PreToolUse well under one second, Stop under 2 minutes.
  • Quote variables ("$f") and never build commands from untrusted tool input with eval.
  • Never let a hook read secrets it does not need; hooks should not print them either.

Best practices​

  • Put cheap checks on the left of the ladder and expensive checks on the right.
  • Make every gate one command that humans can also run (mise run check).
  • Pin pre-commit revs and update them on purpose, with a diff review.
  • Share .claude/settings.json and .claude/hooks/ through the repo; keep personal tweaks in .claude/settings.local.json.
  • Use /status to confirm which settings sources loaded when a hook does not fire.
  • Keep failure messages short and actionable: the agent reads them.

Pitfalls to design around​

  • Use exit 2, not exit 1, when a hook must block.
  • Do not rely on PostToolUse to prevent an edit; use PreToolUse for prevention.
  • Guard Stop hooks with stop_hook_active so they cannot loop.
  • Scope matchers to what you need (Write|Edit); a catch-all matcher runs on every tool call.
  • Do not skip hooks with --no-verify; fix the cause or ask for a reviewed exception.
  • Keep permission rules simple; fragile Bash patterns invite bypasses.
  • Do not duplicate the same check in five places with different versions; one config, called from each rung.

Try it​

Lab (20 min)

  1. In a repo with Python or TypeScript, add the PostToolUse formatter hook and format.sh. Ask Claude to write a badly formatted function and confirm the file ends up formatted.
  2. Add the PreToolUse hook. Ask Claude to edit .env; confirm it is blocked and that Claude explains why.
  3. Add .pre-commit-config.yaml, run pre-commit autoupdate (or prek autoupdate), commit a file containing a fake secret such as AKIA plus 16 characters, and watch gitleaks stop it.
  4. Add a Stop hook that runs your test command. Break a test on purpose and watch Claude keep working until it passes.
  5. Time each hook with time. Anything over its budget goes back to CI.

Checklist​

  • Advisory guidance (AGENTS.md, rules) is separate from enforced gates.
  • An edit-time formatter hook exists, with a timeout.
  • A PreToolUse hook blocks .env, lockfiles, and production infra paths, using exit 2.
  • The Stop hook checks stop_hook_active.
  • permissions.deny covers secrets and git push.
  • Pre-commit or lefthook is installed and revs are pinned.
  • CI runs the same checks as the final gate.
  • Every hook was reviewed like code and finishes within its time budget.

Sources​