Chapter 11

Use Hooks for Events, Not for Reasoning

A hook runs at a specific point in the agent loop and fits format, audit, policy check, or context injection. It must not turn into a second opaque agent and doesn't replace CI or server-side authorization.

Which event fits which action - and where the limit is - is convenient to see in a table.

Event · Practical action · Limit

  • Before shell/tool - Check the command, path, domain, or side-effect risk; The parser must parse structured input, not scan for a dangerous word with a naive regex
  • After edit - Run a formatter or write an audit event; Don't run the full suite after every character
  • Before stopping - Check the focused test or that a report exists; Needs a repeat limit, or a loop is possible
  • Session start - Add brief runtime context; Don't dump secrets and huge logs into context

Product differences matter here, and configs can't be carried between them. Claude Code configures hooks in settings JSON and documents lifecycle events, including PreToolUse, PostToolUse, and Stop. Cursor keeps project hooks in .cursor/hooks.json, passes JSON over stdio, and documents events like beforeShellExecution and afterFileEdit. Codex has its own hook system and trust model - take the syntax from the current Codex documentation.

Pay special attention to failure behavior.

Check the fail behavior. In the current Cursor documentation, a command hook with exit code 2 blocks the action, while other non-zero codes count as a hook error and the action continues by default. If your policy must fail closed, implement and test exactly that contract rather than assuming it.

And a security boundary, because a hook is executable code.

A hook runs code. A project hook is an executable surface of the repository. It needs trust controls, review of config changes, minimal permissions, and a safe parser. Don't run a hook from an untrusted repository blindly.

Events are under control. But even perfect hooks are useless if the environment isn't reproducible - which is where we turn next.

Links