# 28.5 Hooks as deterministic enforcement (/building-ai-workers/guardrails-and-agent-security/hooks-as-deterministic-enforcement)

---
type: Document
title: "28.5 Hooks as deterministic enforcement"
description: "What the payment hook does, which route it guards and which it misses, and how to correct a hook configuration that looks right."
status: stable
order: 328.05
ksor:
  owner: team:panaversity
  audience:
    - public
  approval:
    by: process:panaversity
    at: 2026-11-30T10:59:25Z
chapter: '28'
part: III
expert_status: builder-only
concepts: [ "28.5" ]
last_verified: '2026-11-30'

sources:
  - id: anthropic-ccdv-f-exam-guide
    title: Claude Certified Developer - Foundations Exam Guide, version 1.1, effective December 7, 2026 (Anthropic, accessed 2026-11-30)
    resource: https://cc.sj-cdn.net/instructor/6nizmqk8tpzpfjvt6qmmav7rh/public/1794946771/Claude_Certified_Developer_-_Foundations_Exam_Guide_Updated_Dec_7.pdf
  - id: claude-code-hooks-guide
    title: Automate workflows with hooks (Anthropic, accessed 2026-11-30)
    resource: https://code.claude.com/docs/en/hooks-guide
  - id: claude-code-hooks
    title: Hooks reference (Claude Code, Anthropic, accessed 2026-11-30)
    resource: https://code.claude.com/docs/en/hooks
  - id: claude-agent-sdk-hooks
    title: Control execution with hooks (Claude Agent SDK, Anthropic, accessed 2026-11-30)
    resource: https://code.claude.com/docs/en/agent-sdk/hooks
  - id: claude-code-memory
    title: Manage Claude's memory (Claude Code, Anthropic, accessed 2026-11-30)
    resource: https://code.claude.com/docs/en/memory
generated:
  at: 2026-11-30T10:59:25Z
  by: esl-rewrite/1.2.0+ksor.1
trust_tier: unverified
build_id: sha256:d6ce3f28a2cf8e492a60bae1b426b7cc6466e35e83d70c3b9763db2c55009f4b
dirty: true
ksor_version: 0.0.60
---

**In everyday life.** An office building has a front desk. The receptionist writes every visitor's name in the visitor book, and turns away anyone who has no appointment. The receptionist does this for every visitor, and no visitor can talk their way past the book. But the building has other doors: the loading dock, the parking garage and the fire stairs. So the cash office on the third floor has its own lock, and it opens only for a signed slip from the manager, whichever door the visitor came in by. In this section, the front desk is a hook, the visitor book is the evidence line, the other doors are other routes to the money, and the cash office's lock is the payment tool's own check.

**What you will learn.** You practice this in Lab 28, Task 3, and prove it in Task 4.

- What makes a hook deterministic, when an instruction is not?
- What does the payment hook do, and in what order?
- Which route does the hook guard, and which routes does it miss?
- What does the hook cost?
- How do you correct a hook configuration that looks right?

**Why it matters.** The exam guide asks for "hooks as deterministic enforcement so that destructive actions cannot execute even under adversarial instruction".[^anthropic-ccdv-f-exam-guide] A hook does that on its own route.

**At work.** This section builds the hook that would deny the 9:00 call in the overview, and shows the routes on which it never runs.

<!-- OPEN: recorded run. What the model does with V005's note at 9:00 comes from a recorded run, and none is recorded yet. If the model does not take the bait, Lab 28, Task 4's run in which Ana tells the worker to pay INV-8305 shows the hook's deny instead (spec, "What the drafter leaves OPEN"). -->

### What makes a hook deterministic, when an instruction is not?

**A hook runs every time its event fires, and the model has no say in it.** *Deterministic* here means two things: it always runs, and the same call always meets the same check. Anthropic's guide says hooks give "deterministic control: certain actions always happen rather than relying on the LLM to choose to run them."[^claude-code-hooks-guide]

An instruction is text the model reads, in a system prompt, a skill or a `CLAUDE.md` file. Claude Code's documentation says these files "aren't enforced configuration. To block an action regardless of what Claude decides, use a PreToolUse hook instead."[^claude-code-memory] So a written rule guides, and only a setting, a hook or a permission enforces it. A fooled model can ignore "never pay without an approval". It cannot skip a hook, because the hook is not in its context at all. That puts the hook in the second tier.

The exam also asks for "hook configurations so that required actions execute deterministically rather than at the model’s discretion".[^anthropic-ccdv-f-exam-guide] So a hook can make an action always happen, and it can stop one. The payment hook does both.

### What does the payment hook do, and in what order?

**It writes an evidence line first, then it asks for the approval and denies the call if none matches.** It is one **callback**, a function of yours that the SDK calls, registered in the orchestrator's own code on the event before every tool call, `PreToolUse`:

```ts
// src/agents/month-end-orchestrator.ts, a sketch. The kit names the server.
const paymentGuard: HookCallback = async (input) => {
  const call = input as PreToolUseHookInput
  await writeEvidenceLine(call)               // 1. always, for every proposed payment
  const row = await getApproval(call)         // 2. the connector's get_approval, on the run's token
  if (!row) {
    return {
      hookSpecificOutput: {
        hookEventName: "PreToolUse",
        permissionDecision: "deny",
        permissionDecisionReason: `No approval on record for ${invoiceOf(call)}`,
      },
    }
  }
  return {}                                   // 3. no decision: the other checks still decide
}

const options = {
  hooks: {
    PreToolUse: [
      { matcher: "mcp__ap__schedule_payment", hooks: [paymentGuard], onFailure: "block" },
    ],
  },
}
```

<!-- OPEN: the connector's key in `mcpServers`, which sets the full tool name (`mcp__<server>__schedule_payment`), comes from Lab 28's kit. This sketch writes `ap`. The names `writeEvidenceLine`, `getApproval` and `invoiceOf` stand in for the kit's own. -->

Read it in order.

1. **The evidence line comes first.** It is one line in `evidence/payments.jsonl` (proposed). The line records which tool, which invoice, which amount, which run, and when. It must exist for every call, allowed or denied. That is the exam's "required action". The portal's approval page lists the line as a proposal only when the run's token carries `ap:pay` ([28.4](least-privilege.md)), the scope that means "may propose a payment".
2. **Then the hook asks.** It calls `get_approval` with the run's own token. The model cannot call that tool, because the orchestrator denies it by name ([28.4](least-privilege.md)). No matching row, and the hook denies, with a reason the model reads.
3. **A match is no decision.** When a row matches, the hook returns `{}`, which decides nothing. The call goes on to the rest of the checks in 22.5's order, and then to the connector, which checks it again. This is what "the hook lets the call through" means everywhere in this chapter. The hook never returns "allow", because it is not the last guard.

Why one callback and not two hooks? Hooks that match one event "run in parallel", and "completion order is non-deterministic".[^claude-agent-sdk-hooks] Two hooks could deny before the evidence line was written. Inside one callback, the order is the order of the lines.

The **matcher** is the pattern that says which tools a hook runs for. A matcher made only of letters, digits, `_`, `-`, spaces, commas and `|` is read as an exact name, or a list of exact names. So `schedule_payment` alone is compared as an exact string and matches no tool, because the tool's full name carries the connector's prefix. A matcher with any other character is a **regular expression**, a pattern in which some characters stand for many, so `mcp__ap__.*` matches every tool on that server.[^claude-code-hooks] The Agent SDK's "matchers follow the same rules as matchers in settings files".[^claude-agent-sdk-hooks] The last setting, `onFailure: "block"`, is [28.6](fail-closed.md)'s.

### Which route does the hook guard, and which routes does it miss?

**One route: a tool call that this orchestrator's model makes.** The hook does nothing if its matcher misses, if it is not loaded, or if the payment is reached another way. Figure 28.3 shows four routes:

- *The orchestrator's tool call.* The hook is here, and only here.
- *The workflow's own code*, `src/workflows/month-end.ts`. It calls the connector with no model in between, so no hook runs.
- *A script* on someone's laptop, holding a token, as at 9:40. Nothing in the orchestrator runs.
- *A hosted session.* A hosted worker runs no process of yours, so it has no hooks ([23.6](../hosted-agents/what-travels.md)).

"Not loaded" is real in this build. The orchestrator runs with `settingSources` empty, and the Agent SDK loads hooks from settings files only when the matching `settingSources` entry is on.[^claude-agent-sdk-hooks] So a hook in `.claude/settings.json` never reaches it.

So the action itself checks too, with the scope, the row and the run key of [28.4](least-privilege.md). The hook stops the model early and explains why. The connector's check is the guarantee. A fooled model changes nothing for the hook, which reads the call, not the model's reasons. But it checks only what it was written to check. At 10:15, only the connector caught Priya's missing scope, and her run proposed nothing.

<!-- FIGURE 28.3: Four horizontal lanes, left to right, all ending at one box on the right edge labeled "The connector's check: ap:pay, an approvals row, one payment per approval". Lane 1, top, labeled "The orchestrator's tool call": a box "model proposes schedule_payment", an arrow to a shield labeled "hook: evidence line, then get_approval", an arrow on to the connector box. Lane 2: "The workflow's own code", a straight arrow to the connector box, no shield. Lane 3: "A script with a token", a straight arrow, no shield. Lane 4: "A hosted session", a straight arrow, no shield, with a small note "no hooks travel". A brace under lanes 2 to 4 reads "the hook never sees these". The connector box is drawn heavier than everything else, and a caption line under it reads "decides on every route". The hook's shield carries the label "decides on one route". Alt text must name all four lanes, say that only lane 1 has the hook, and say that all four meet at the connector's check. -->

*Figure 28.3. Four routes to one payment. The hook stands on one. The connector's check stands where all four meet.*

### What does the hook cost?

**A call to `get_approval` before every proposed payment, a line in a file, and code you must test.** The real cost is a configuration mistake. A matcher that is too wide puts the approval check on read tools, and denies them, which breaks the agent's function. So a hook needs tests on both sides: one that proves it denies, and one that proves the read tools still work.

### How do you correct a hook configuration that looks right?

**Read where it runs, what it matches, and what it does on every path, before you change anything.** Here is a configuration a builder wrote. Name each fault in your own words before you read on. The broken configuration in Lab 28, Task 3 has three other faults, so these do not tell you its answers.

```ts
const paymentGuard: HookCallback = async (input) => {
  const call = input as PostToolUseHookInput
  const row = await getApproval(call)
  if (!row) {
    await writeEvidenceLine(call)
    return { hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: "No approval on record" } }
  }
  return {}
}

const options = {
  hooks: {
    PostToolUse: [{ matcher: "mcp__ap__.*", hooks: [paymentGuard] }],
  },
}
```

Three faults, and one missing setting that [28.6](fail-closed.md) names:

1. **It runs after the tool.** `PostToolUse` fires when the tool has already returned. By then the payment is made, and a message to the model cannot take it back. Move the hook to `PreToolUse` and return a `deny`.
2. **It matches too much.** `mcp__ap__.*` is a regular expression that matches every tool on the server, so `find_vendor` and `list_open_invoices` would meet the approval check too. Name the one tool in full, `mcp__ap__schedule_payment`.
3. **The required action runs only sometimes.** The evidence line is written only when no approval is found, so a payment that goes ahead leaves no line. Write the line first, on every path.

The missing setting is `onFailure`.

**The operating rule:** put a required action and a deny in one `PreToolUse` callback, in that order. Name the tool in full. And never treat the hook as the last guard: it decides on its own route, and the connector decides on every route.

**Do this now.** Ask your coding agent to list the routes to one action in your own project. Copy this line:

> Pick the one tool in this project that changes something. List every way a call can reach it: a model's tool call, my own code, a script, a hosted session. For each one, name every check the call meets and the file and line where each check lives. Mark which checks run on every route. Change no file.

If no check runs on every route, that tool has no guarantee, only guards.

[^anthropic-ccdv-f-exam-guide]: Claude Certified Developer - Foundations Exam Guide, version 1.1, Anthropic.
[^claude-code-hooks-guide]: Automate workflows with hooks, Anthropic.
[^claude-code-memory]: Manage Claude's memory, Claude Code, Anthropic.
[^claude-agent-sdk-hooks]: Control execution with hooks, Claude Agent SDK, Anthropic.
[^claude-code-hooks]: Hooks reference, Claude Code, Anthropic.
