← ~/pillars / deterministic-policy / hooks-as-hard-gates

Hooks as hard gates

Using Claude Code's hook system as deterministic enforcement: blocking events, exit-code versus JSON control, and securing the hooks themselves.

updated 2026-07-05 ~4 min read pattern 02/06 Deterministic Guardrails

on this page

Context. You have rules that must hold on every tool call (protected paths, forbidden commands, mandatory validations), and you want them enforced by code that runs whether or not the model remembers them.

Forces. Hooks run with your full OS permissions and no interactive terminal, so a badly written hook is itself a liability. Blocking too eagerly stalls legitimate work; blocking too late (after the tool ran) only limits damage. And the hook configuration is just files in a repo: anyone with write access can change it.

Resolution. Build gates on the small set of lifecycle events that can actually block, choose the right control channel (exit code or JSON), and treat hook configuration as security-sensitive code.

The blocking events that matter

The hook system spans 30+ lifecycle events (hooks reference), but most are observability. For enforcement, these carry the weight:

EventBlocksUse it for
PreToolUseYes: before the tool runsThe workhorse. Deny edits to protected paths, dangerous commands, suspicious MCP calls.
UserPromptSubmitYes: before Claude sees the promptReject prompts that violate policy; inject context.
PermissionRequestYes: before the dialog appearsProgrammatic allow/deny instead of a human clicking.
PostToolUseTool already ranValidation feedback: decision: "block" sends the failure back to Claude for another turn.
StopYes: Claude cannot finishForce verification (tests, lint) before the turn ends.
ConfigChangeYes: blocks the changeStop mid-session edits to settings and hook config; the audit point for compliance environments.
SubagentStopYesSame as Stop, for subagents.

PreToolUse is the only one of these that prevents the side effect entirely. PostToolUse and Stop are feedback loops: valuable, but the file was already written. Put prevention in PreToolUse, validation in PostToolUse.

Exit codes versus JSON: pick one

Two control channels, with one rule that trips everyone up (hooks reference):

  • Exit 2: blocking error. stderr becomes the message Claude sees; stdout is ignored, including any JSON in it.
  • Exit 0 + JSON on stdout: structured control. For PreToolUse: permissionDecision of allow, deny, ask, or defer, plus permissionDecisionReason and optionally updatedInput.
  • Any other exit code: non-blocking error, logged and skipped.

Never mix the two: JSON printed by a hook that exits 2 is silently discarded. Use exit 2 when you want a simple veto with a human-readable reason; use exit 0 + JSON when you need allow/ask/defer or want to rewrite the tool input.

Two interaction rules from the permissions docs define what hooks can and cannot do:

  1. A hook’s "allow" decision skips the prompt but does not override deny rules: managed and settings-level denies still block.
  2. A hook’s exit 2 does override allow rules: the block lands before permission evaluation.

Hooks are reliable hard denials, unreliable hard approvals. When several hooks return decisions for the same event, the most restrictive wins (deny over defer over ask over allow), and all sibling hooks run to completion regardless.

Matchers

Matchers select which tool calls a hook sees: "Edit|Write" for a pipe-separated list, "*" or omitted for everything, and anything with other characters is evaluated as a JavaScript regex: "mcp__memory__.*" for one MCP server, "mcp__.*__write.*" for write-shaped tools on any server. The if field narrows further using permission-rule syntax, e.g. "if": "Bash(git *)" to fire only on git commands.

Securing the hooks themselves

Hooks execute with the same OS permissions as Claude Code and no controlling terminal. Three findings from the security docs shape how to deploy them:

  • Argument patterns are bypassable. A matcher or if condition that tries to constrain Bash arguments by pattern is fragile: flag reordering, alternative protocols, and shell variables all dodge it. Validate inside the hook script with real parsing of the JSON input, not with a regex on the command string.
  • Project hooks are repo-trust. .claude/settings.json hooks run as the local user, and anyone with repo write access can add or edit them. A hook referenced by path (${CLAUDE_PROJECT_DIR}/.claude/hooks/...) is exactly as trustworthy as the repo. For security-critical gates, deploy managed settings with allowManagedHooksOnly: true, which disables all user, project, and plugin hooks, and prefer inline command strings over repo-resident scripts.
  • Audit config drift in-session. The ConfigChange event fires when a configuration file changes during a session and can block the change with exit 2, the documented pattern for compliance environments. The /hooks command gives a read-only browser of every active hook with its origin.

Worked example

The block-prod-config-edits artifact is the full pattern in one config: a PreToolUse hook matched on Edit|Write, a script that parses tool_input.file_path from stdin JSON, and an exit-2 deny with the reason on stderr when the path matches a protected pattern (Terraform, workflow files, Spring production profiles). Claude receives the stderr text, explains the block to the user, and moves on. The rule held without ever occupying a token of prompt-space. Pair it with permission deny rules on the same paths so the policy survives even if the hook script is removed: hooks for legibility, deny rules for durability.

// sources