Hooks, Pre-commit, and Quality Gates
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.
- 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
| Layer | Examples | Who enforces | Can the model skip it? |
|---|---|---|---|
| Advisory | AGENTS.md, .claude/rules/, skills | The model's attention | Yes |
| Enforced at edit time | Hooks, permission rules | The harness | No |
| Enforced at commit time | pre-commit / prek / lefthook | Git | Only with --no-verify |
| Enforced at merge time | CI, code review | The server and humans | No |
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):
| Event | Fires | Typical use | Exit 2 blocks? |
|---|---|---|---|
SessionStart | Session begins or resumes | Print plan status, load context | No |
UserPromptSubmit | You submit a prompt | Inject context, screen prompts | Yes |
PreToolUse | Before a tool call | Block protected paths or commands | Yes |
PostToolUse | After a tool call succeeds | Format, lint, log | No (tool already ran; stderr is shown to Claude) |
Notification | Claude needs attention | Desktop alert | No |
Stop | Claude finishes a turn | Run tests, force continuation | Yes |
SubagentStop | A subagent finishes | Verify subagent output | Yes |
PreCompact | Before context compaction | Save state | Yes |
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):
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"if": "Bash(rm *)",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.sh",
"args": []
}
]
}
]
}
}
| Item | Rule |
|---|---|
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. |
type | command, http, mcp_tool, prompt, or agent |
timeout | Seconds. Defaults: 600 for command, http, mcp_tool; 30 for prompt; 60 for agent |
if | Optional 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 code | Meaning |
|---|---|
| 0 | Success. JSON on stdout is applied. For SessionStart and UserPromptSubmit, plain-text stdout is added as context for Claude |
| 2 | Blocking error on events that can block; stderr is the reason |
| Any other | Non-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.
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/format.sh",
"timeout": 30
}
]
}
]
}
}
#!/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)
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/protect-paths.sh",
"timeout": 5
}
]
}
]
}
}
#!/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).
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/stop-check.sh",
"timeout": 120
}
]
}
]
}
}
#!/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).
{
"hooks": {
"SessionStart": [
{
"matcher": "startup|resume|clear|compact",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/plan-status.sh",
"timeout": 10
}
]
}
]
}
}
#!/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).
{
"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
| Harness | Mechanism | Where | Notes |
|---|---|---|---|
| Claude Code | Hooks in settings JSON | .claude/settings.json | Described above |
| OpenCode | Plugins: 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 |
| Codex | Hooks 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:
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
| Tool | What it is | Config | Notes |
|---|---|---|---|
| pre-commit | The original multi-language hook framework | .pre-commit-config.yaml | Install: pip install pre-commit |
| prek | Rust drop-in alternative to pre-commit, MIT | Reads .pre-commit-config.yaml and its own prek.toml | Install: uv tool install prek; project claims it is multiple times faster and uses less disk |
| lefthook | Fast Git hook manager | lefthook.yml | Install 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.
# 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):
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:
| Mechanism | Runs | Does |
|---|---|---|
| PostToolUse hook (step 1) | After every Write or Edit | Format only the file touched; seconds |
post-change-update skill | When you invoke /post-change-update after a task | Full check run, doc updates, plan progress log, scratchpad (Skills and Skill Creation) |
| SessionStart hook (step 4) | Each session start, resume, clear, compact | Shows 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 witheval. - 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.jsonand.claude/hooks/through the repo; keep personal tweaks in.claude/settings.local.json. - Use
/statusto 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, notexit 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_activeso 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)
- 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. - Add the PreToolUse hook. Ask Claude to edit
.env; confirm it is blocked and that Claude explains why. - Add
.pre-commit-config.yaml, runpre-commit autoupdate(orprek autoupdate), commit a file containing a fake secret such asAKIAplus 16 characters, and watch gitleaks stop it. - Add a Stop hook that runs your test command. Break a test on purpose and watch Claude keep working until it passes.
- 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, usingexit 2. - The Stop hook checks
stop_hook_active. -
permissions.denycovers secrets andgit 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
- Claude Code hooks reference: https://code.claude.com/docs/en/hooks (events, schema, exit codes, input fields, Stop and SessionStart behavior; 33 events as of 2026-10)
- Claude Code permissions: https://code.claude.com/docs/en/permissions (rule order,
Bash(...),Read(...),Edit(...)syntax) - Claude Code settings: https://code.claude.com/docs/en/settings (scopes, merging of list keys)
- Claude Code memory: https://code.claude.com/docs/en/memory (rules and CLAUDE.md are context, not enforcement)
- Claude Code best practices: https://code.claude.com/docs/en/best-practices (verification, Stop hook)
- OpenCode plugins: https://opencode.ai/docs/plugins/
- Codex hooks: https://developers.openai.com/codex/hooks
- pre-commit: https://pre-commit.com/
- prek: https://github.com/j178/prek
- lefthook: https://lefthook.dev/
- ruff-pre-commit (v0.17.2): https://github.com/astral-sh/ruff-pre-commit
- Biome pre-commit (v2.6.2): https://github.com/biomejs/pre-commit
- golangci-lint v2.15.0 and hook ids: https://github.com/golangci/golangci-lint/releases/tag/v2.15.0 and https://raw.githubusercontent.com/golangci/golangci-lint/main/.pre-commit-hooks.yaml
- pre-commit-opentofu releases (v2.4.2, as of 2026-10): https://github.com/tofuutils/pre-commit-opentofu/releases
- gitleaks v8.30.1: https://github.com/gitleaks/gitleaks/releases/tag/v8.30.1