# Use hooks as deterministic guardrails

URL: https://developertoolkit.ai/en/workflows/harness/agent-hooks/
Description: Layer deterministic agent hooks across Claude Code, Codex, and Cursor: guard protected paths, block risky commands, lint edits, and enforce stop gates.

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.

## 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

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](/en/workflows/harness/permissions-and-sandboxing/).

## 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.

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:

   ```bash title=".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:

   ```bash title=".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

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

**Claude Code**

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](/en/org/managed-policy/).

```json title=".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](https://code.claude.com/docs) and [Claude Code hooks automation](/en/claude-code/automate/hooks-automation/).

**Codex**

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_path` fields, so adapt path-guard scripts to parse patch headers and run lint checks in the `Stop` gate.

See the [OpenAI Codex docs](https://developers.openai.com/codex) for current hook event schemas and trust settings.

**Cursor**

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](https://cursor.com/docs).

## 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`):

```bash title="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](/en/workflows/harness/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.

**Copy-paste prompt: design a fail-closed hook with fixtures**

```text
Read AGENTS.md and pick the highest-risk mechanical rule still enforced only in prose.
Design one fail-closed bash hook (event, matcher, JSON field) exiting 2 with an
actionable stderr message on policy violations and parse/dependency errors. Add
allow, deny, near-miss, and malformed-input fixtures. Do not register it yet.
```

## When agent hooks fail silently

- **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](/en/org/agent-identity-and-secrets/)).

## Official docs and next steps

Consult official docs for current hook events, JSON payloads, and managed-hook policies: [Claude Code docs](https://code.claude.com/docs), [OpenAI Codex docs](https://developers.openai.com/codex), and [Cursor docs](https://cursor.com/docs).

- [Permissions and sandboxing](/en/workflows/harness/permissions-and-sandboxing/) — Build the OS sandbox and egress boundaries that hooks complement.
- [Protecting the oracle](/en/workflows/test/protect-the-oracle/) — Lock acceptance tests and CI workflows so agents cannot weaken checks.
- [Managed policy](/en/org/managed-policy/) — Distribute non-overridable hooks and guardrails across teams.
- [Claude Code hooks automation](/en/claude-code/automate/hooks-automation/) — Explore deeper Claude Code lifecycle events and hook patterns.
