Skip to content

Agent hooks are deterministic scripts that Claude Code, Codex, and Cursor execute at fixed lifecycle events regardless of what the model decides. Developers and tech leads layer four hooks—protected-path guards, command guards, post-edit linting, and stop gates—to enforce mechanical invariants that prose instructions drop during long sessions.

Your AGENTS.md states “never edit src/generated/” and “run tests before finishing”. The agent obeys both for a week, then during a long refactor edits a generated client, declares “all done”, and leaves a failing test and a hardcoded API key in the diff. Context instructions advise; hooks execute every time.

A hook earns its maintenance cost when the check is mechanical, fast, and expensive to miss. Place each safeguard at the earliest lifecycle event that can stop or repair it, and always pair local hooks with CI enforcement:

RiskLifecycle eventHook responsibilityIndependent backstop
Editing generated, vendored, or test-oracle filesPreToolUse (file writes)Block the write and name the source file to edit insteadPermission deny rules + CODEOWNERS
Running destructive or production commandsPreToolUse (shell)Block and ask a human to run the commandOS sandbox, absent production credentials, CI deploys
Breaking formatting or lint rulesPostToolUse (file writes)Format silently (fail open), feed lint errors back to the agentRequired lint gate in CI
Leaving credentials in the working treeStopRefuse completion unconditionally until the secret is removedGit pre-commit secret scan + CI secret scanning
Declaring “done” with broken types or testsStopRun scoped checks once; block on failure, then hand off via stop_hook_activeRequired CI check suite

Separate repair from security. A formatter crash should fail open so work continues—CI catches formatting later. A path guard or secret scanner crash must fail closed because a missed block can destroy state or leak credentials.

The exit-code contract and why hooks fail open by default

Section titled “The exit-code contract and why hooks fail open by default”

Across Claude Code and Codex hooks, the core contract is simple: exit 0 allows execution, while exit 2 blocks the action (or continues the turn on Stop) and sends stderr back to the model as corrective feedback. Crucially, non-zero crashes (exit 1), missing scripts, missing dependencies like jq, or timeouts fail open in host CLIs—meaning the guarded action proceeds silently.

Write every security or boundary hook to catch every detectable error explicitly and exit 2. Because a timeout still fails open, never treat hooks as your sole security wall; keep hard containment inside permissions and sandboxing.

Keep hook logic in concise, executable repository scripts (chmod +x) so every developer and agent session runs identical checks.

  1. Guard protected paths (PreToolUse). Inspect the target path from hook JSON input and reject writes into generated, vendored, secret, or locked test paths. Normalize separators and fail closed if jq or file_path is missing:

    .claude/hooks/protect-paths.sh
    #!/usr/bin/env bash
    set -uo pipefail
    block() { printf 'protect-paths: %s\n' "$1" >&2; exit 2; }
    command -v jq >/dev/null 2>&1 || block "jq missing; cannot verify file path."
    path=$(jq -er '.tool_input.file_path // empty' 2>/dev/null) || block "missing file_path."
    path=${path//\\//}
    case "$path" in
    */src/generated/*|*/vendor/*|*/.env|*/.env.*)
    block "$path is protected. Edit the source schema or ask a human." ;;
    esac
    exit 0
  2. Guard production and destructive commands (PreToolUse). Inspect shell commands for high-risk patterns (terraform apply, force pushes, --remote production mutations) and block with exit 2. Treat command pattern matching strictly as a typo-catcher: wrappers like sh -c or scripts bypass regexes, so absent production credentials remain the real wall.

  3. Format and lint edits (PostToolUse). Run the formatter fail-open (|| true) on modified source files, then run your fast linter. If lint fails, print the condensed errors to stderr and exit 2 so the agent fixes them immediately while the edit is still in context.

  4. Enforce a stop gate with loop protection (Stop). Scan uncommitted diffs and untracked files for secrets unconditionally—always blocking on leaks. For typecheck and scoped tests, inspect stop_hook_active so an unfixable environment error blocks once and then hands control back to a human rather than spinning forever:

    .agent-hooks/stop-gate.sh
    #!/usr/bin/env bash
    set -uo pipefail
    block() { printf 'stop-gate: %s\n' "$1" >&2; exit 2; }
    again=$(jq -r '.stop_hook_active // false' 2>/dev/null || echo false)
    root=$(git rev-parse --show-toplevel 2>/dev/null) || block "not inside a Git repo."
    cd "$root" || block "cannot enter repository root."
    command -v gitleaks >/dev/null 2>&1 || block "gitleaks missing; cannot scan diff."
    if ! { git diff HEAD 2>/dev/null; git ls-files -z --others --exclude-standard | xargs -0 -r cat; } \
    | gitleaks stdin --redact --no-banner >/dev/null 2>&1; then
    block "Secret detected in uncommitted changes. Remove it and use environment variables."
    fi
    [ "$again" = "true" ] && exit 0
    if ! out=$(pnpm check:changed 2>&1); then
    block "Checks failed. Fix the root cause:\n$(printf '%s' "$out" | tail -n 40)"
    fi
    exit 0

    Because a stop gate inspects uncommitted changes, pair it with a Git pre-commit secret scanner whenever agents are permitted to commit.

Wire hooks across Claude Code, Codex, and Cursor

Section titled “Wire hooks across Claude Code, Codex, and Cursor”

Share scripts where tool input shapes match, and write thin per-tool registrations against each vendor’s current schema:

Register project hooks in .claude/settings.json using ${CLAUDE_PROJECT_DIR} so paths resolve cleanly from subdirectories. Organization-wide non-overridable checks belong in managed hooks deployed through managed policy.

.claude/settings.json
{
"hooks": {
"PreToolUse": [
{ "matcher": "Edit|Write", "hooks": [{ "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/protect-paths.sh", "timeout": 10 }] },
{ "matcher": "Bash", "hooks": [{ "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.agent-hooks/guard-commands.sh", "timeout": 10 }] }
],
"PostToolUse": [
{ "matcher": "Edit|Write", "hooks": [{ "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/post-edit-lint.sh", "timeout": 60 }] }
],
"Stop": [
{ "hooks": [{ "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.agent-hooks/stop-gate.sh", "timeout": 300 }] }
]
}
}

Inspect active hooks and debug firing behaviour via Claude Code’s built-in hook tools; see the Claude Code hooks docs and Claude Code hooks automation.

Verify every hook with fixtures instead of trust

Section titled “Verify every hook with fixtures instead of trust”

An untested hook is wishful thinking. Commit a fixture script that pipes representative JSON payloads directly into each blocking hook and runs in CI (allow, deny, near-miss allow, and malformed input returning exit 2):

scripts/test-hooks.sh
#!/usr/bin/env bash
set -euo pipefail
check() {
local want=$1 script=$2 payload=$3 got=0
printf '%s' "$payload" | "$script" >/dev/null 2>&1 || got=$?
[ "$got" -eq "$want" ] || { echo "FAIL $script: wanted $want, got $got"; exit 1; }
}
check 0 .claude/hooks/protect-paths.sh '{"tool_input":{"file_path":"/repo/src/app.ts"}}'
check 2 .claude/hooks/protect-paths.sh '{"tool_input":{"file_path":"/repo/src/generated/api.ts"}}'
check 0 .claude/hooks/protect-paths.sh '{"tool_input":{"file_path":"/repo/src/generator/api.ts"}}'
check 2 .claude/hooks/protect-paths.sh 'malformed-json'

Pair fixture tests with three additional checks:

  • @wondelai/harness-audit: Run npx @wondelai/harness-audit to audit Station 2 (Harness), confirming lifecycle hooks and stop_hook_active loop guards (harness audit guide).
  • Live matcher check: On a scratch branch, verify the CLI invokes each registered hook and returns your message.
  • CODEOWNERS review: Protect hook scripts and settings files with code-owner review because hooks run with developer and CI credentials.
  • The guard silently stops running. A typo in a path, missing chmod +x, missing jq, or an accidental exit 1 makes the CLI fail open. Run your fixture suite in CI and exit 2 on every detectable error.
  • The stop gate loops forever. Tests fail for an environment issue the agent cannot fix. Check stop_hook_active so tests block once and hand off cleanly, keeping unconditional blocking for secrets only.
  • A formatter crash halts every edit. Let repair steps fail open (|| true) and exit 2 only on actionable lint or policy violations.
  • A hook logs the secret it caught. Never print matched values or full shell commands. Print only the rule name and file, pass --redact to secret scanners, and rotate anything exposed.
  • Untrusted PRs execute attacker hooks in CI. Never load project hooks or settings from a fork inside a secret-bearing CI job (agent identity and secrets).

Consult official docs for current hook events, JSON payloads, and managed-hook policies: Claude Code docs, OpenAI Codex docs, and Cursor docs.

Did this guide help you?

One tap, no sign-in.

not at all a lot

Frequently asked questions

What are the four layers of deterministic agent hooks?

A deterministic guardrail layers four hooks across the agent loop: blocking edits to protected paths, blocking risky production commands, formatting and linting edits, and refusing to stop while secrets or failing checks remain.

Why must a Stop hook check stop_hook_active?

When a Stop hook blocks completion, the agent continues working and triggers the hook again. Checking stop_hook_active prevents an infinite loop when tests fail for reasons the agent cannot resolve on its own.