Use hooks as deterministic guardrails
PLAgent 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.
Which checks belong in a hook?
Section titled “Which checks belong in a hook?”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:
| Risk | Lifecycle event | Hook responsibility | Independent backstop |
|---|---|---|---|
| Editing generated, vendored, or test-oracle files | PreToolUse (file writes) | Block the write and name the source file to edit instead | Permission deny rules + CODEOWNERS |
| Running destructive or production commands | PreToolUse (shell) | Block and ask a human to run the command | OS sandbox, absent production credentials, CI deploys |
| Breaking formatting or lint rules | PostToolUse (file writes) | Format silently (fail open), feed lint errors back to the agent | Required lint gate in CI |
| Leaving credentials in the working tree | Stop | Refuse completion unconditionally until the secret is removed | Git pre-commit secret scan + CI secret scanning |
| Declaring “done” with broken types or tests | Stop | Run scoped checks once; block on failure, then hand off via stop_hook_active | Required 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.
Build the four layered hook scripts
Section titled “Build the four layered hook scripts”Keep hook logic in concise, executable repository scripts (chmod +x) so every developer and agent session runs identical checks.
-
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 ifjqorfile_pathis missing:.claude/hooks/protect-paths.sh #!/usr/bin/env bashset -uo pipefailblock() { 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." ;;esacexit 0 -
Guard production and destructive commands (
PreToolUse). Inspect shell commands for high-risk patterns (terraform apply, force pushes,--remoteproduction mutations) and block with exit2. Treat command pattern matching strictly as a typo-catcher: wrappers likesh -cor scripts bypass regexes, so absent production credentials remain the real wall. -
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 tostderrand exit2so the agent fixes them immediately while the edit is still in context. -
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, inspectstop_hook_activeso 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 bashset -uo pipefailblock() { 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; thenblock "Secret detected in uncommitted changes. Remove it and use environment variables."fi[ "$again" = "true" ] && exit 0if ! out=$(pnpm check:changed 2>&1); thenblock "Checks failed. Fix the root cause:\n$(printf '%s' "$out" | tail -n 40)"fiexit 0Because a stop gate inspects uncommitted changes, pair it with a Git
pre-commitsecret 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.
{ "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.
Register project hooks in .codex/hooks.json or config.toml. Note two important differences from Claude Code:
- Explicit trust: Project hooks remain inactive until reviewed and trusted (and must be re-trusted after edits), unless shipped as managed hooks by administrators.
- Patch-based file edits: Codex applies edits through patch payloads rather than single
file_pathfields, so adapt path-guard scripts to parse patch headers and run lint checks in theStopgate.
See the OpenAI Codex docs for current hook event schemas and trust settings.
Cursor supports stdio JSON hooks that observe, block, or modify agent actions alongside project rules and CI checks. Keep all critical invariants (secret scanning, protected-path diff checks, typecheck, lint, tests) enforced as required CI gates and Git pre-commit hooks, then layer Cursor-specific hooks using the current schema in the Cursor docs.
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):
#!/usr/bin/env bashset -euo pipefailcheck() { 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: Runnpx @wondelai/harness-auditto audit Station 2 (Harness), confirming lifecycle hooks andstop_hook_activeloop guards (harness audit guide).- Live matcher check: On a scratch branch, verify the CLI invokes each registered hook and returns your message.
CODEOWNERSreview: Protect hook scripts and settings files with code-owner review because hooks run with developer and CI credentials.
When agent hooks fail silently
Section titled “When agent hooks fail silently”- The guard silently stops running. A typo in a path, missing
chmod +x, missingjq, or an accidentalexit 1makes the CLI fail open. Run your fixture suite in CI and exit2on every detectable error. - The stop gate loops forever. Tests fail for an environment issue the agent cannot fix. Check
stop_hook_activeso 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 exit2only 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
--redactto 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).
Official docs and next steps
Section titled “Official docs and next steps”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.
What will you do with it?
How did it read?
What got in the way? Pick any that apply
Your role?
Thanks. I read every answer. Michał Jaskólski
Did this guide help?
One tap each. Close whenever you like.
no sign-in
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.