What you will be able to do
- Explain why identity verification before a refund must be enforced by a hook rather than requested in the system prompt
- Build a prerequisite gate that records a successful get_customer in PostToolUse and denies process_refund in PreToolUse until that record exists
- Scope hook matchers so a gate fires on exactly the tools that move money and on nothing else
- Split a multi-concern customer request into parallel investigations that share the case context, then synthesize one resolution
- Compile a handoff summary a human agent can act on without reading the transcript
Key concept
Programmatic prerequisite gate — Code that records when a prerequisite step has actually succeeded and blocks a downstream tool call until that record exists. The model can still plan the order, but it cannot skip the step, because the decision is made outside the model.
1.Why workflow ordering for money needs enforcement, not instructions
A support agent that issues refunds has one ordering rule that cannot bend: confirm who the customer is before any money moves. A system prompt can state that rule, and the model will usually follow it. Usually is the problem. The model chooses its own tool calls in every turn, so an instruction that says "always call get_customer first" only shapes that choice. A long conversation, a persuasive customer or an ambiguous request can still produce a turn where process_refund comes first. Prompt instructions have a non-zero failure rate, and for a financial operation any non-zero rate means some refunds go to unverified callers.
The general rule is covered in deterministic hooks vs probabilistic prompt instructions: hooks run in code on every matching event, while prompts only guide. Workflow ordering is where that rule matters most. A PreToolUse hook fires before the tool executes and can refuse the call, so the refund cannot run whatever the model decided. Keep the instruction in the prompt as well, because it helps the model plan the right order. The hook is what makes that order compulsory.
The same idea shows up in fixed workflows. Prompt chaining puts programmatic checks between steps, so a step that went wrong stops the chain before the next LLM call builds on it. A prerequisite gate is that check, moved to the boundary of one tool call inside a model-driven loop.
Checkpoint 1 of 7· Check yourself
A refund agent's system prompt says "always call get_customer before process_refund". Audits show that a small share of refunds still go out without the customer's identity being verified first. What fix makes verification before a refund guaranteed?
Prompt changes and bigger models only shape what the model chooses, so the failure rate stays above zero. A PreToolUse hook runs in code before the tool executes and can refuse the call, so the refund cannot run without verification. A check that runs after process_refund comes too late, because the money has already moved.
“PreToolUse | Before a tool call executes. Can block it”Source: code.claude.com
2.Building the gate: record in PostToolUse, block in PreToolUse
A prerequisite gate has two parts: one hook records that the prerequisite succeeded, and another blocks the downstream call when that record is missing. Hooks are ordinary callbacks in your application, so both can read and write the same session state, such as a dictionary keyed by session or a small store.
The record has to be written by PostToolUse, after get_customer has succeeded and returned a verified ID. The block happens in PreToolUse on process_refund. That hook looks at the record and denies the call if no verified ID exists. The SDK callback below shows the denial pattern. It inspects the tool input and returns permissionDecision "deny" with a reason, and returns an empty object to let the call through. A refund gate has the same shape, with a check for the verified customer in place of the .env filename test.
async def protect_env_files(input_data, tool_use_id, context):
# Extract the file path from the tool's input arguments
file_path = input_data["tool_input"].get("file_path", "")
file_name = file_path.split("/")[-1]
# Block the operation if targeting a .env file
if file_name == ".env":
return {
"hookSpecificOutput": {
"hookEventName": input_data["hook_event_name"],
"permissionDecision": "deny",
"permissionDecisionReason": "Cannot modify .env files",
}
}
# Return empty object to allow the operation
return {}Two hooks that rely on each other have to be designed around when they actually fire. A matcher means a hook runs only when its tool is invoked. A hook on get_customer therefore does nothing if the model never calls get_customer. It cannot force the call to happen first. For this reason the process_refund gate must fail closed: no record, or a record it cannot read, means deny. Hooks that match the same event also run in parallel, in no guaranteed order, so a design that needs one hook to finish before another starts is broken from the outset.
A gate can be no more reliable than the evidence it checks. Suppose the gate reads a boolean is_verified that a separate step sets, and a bug sets it to true after get_customer found no matching customer. The gate then lets the refund through. A stronger gate stores what get_customer actually returned, the customer ID, when the PostToolUse hook runs. The PreToolUse input includes tool_input, so the process_refund hook can compare the customer ID in the refund arguments with the stored ID, and deny the call when they differ or when none is stored. The check then ties the refund to one specific verified customer instead of a flag that anything can flip. Adding a PostToolUse hook on process_refund as a backstop does not solve this. By the time PostToolUse runs, the money has already moved.
First, the marker is written before get_customer executes, so a failed or empty lookup still leaves it set. Second, if the model never calls get_customer, nothing writes the marker, and a process_refund hook that treats a missing or stale file as acceptable lets the call through. Writing the marker in PostToolUse and having the gate deny when the marker is missing fixes both.
Checkpoint 2 of 7· Fill the gap
This PreToolUse callback is the pattern your process_refund gate will copy. Which value in the blank makes the hook refuse the tool call?
async def protect_env_files(input_data, tool_use_id, context):
# Extract the file path from the tool's input arguments
file_path = input_data["tool_input"].get("file_path", "")
file_name = file_path.split("/")[-1]
# Block the operation if targeting a .env file
if file_name == ".env":
return {
"hookSpecificOutput": {
"hookEventName": input_data["hook_event_name"],
"permissionDecision": " ? ",
"permissionDecisionReason": "Cannot modify .env files",
}
}
# Return empty object to allow the operation
return {}A PreToolUse hook refuses the call by returning permissionDecision "deny" with a reason. "ask" sends the call to the user for approval, so it does not block, and returning an empty object lets the call through.
Source: code.claude.comCheckpoint 3 of 7· Check yourself
An engineer registers two PreToolUse hooks on process_refund. Hook A loads the verification record into a shared variable, and Hook B reads that variable and denies the call if it is empty. In testing, some refunds are wrongly denied and the failures look random. What is the design flaw?
Hooks on the same event run in parallel and their order is non-deterministic, so a design where one hook depends on another is broken from the outset. Moving the check to PostToolUse would come too late, and failing open would let unverified refunds through.
“Since hooks run in parallel, the order is non-deterministic.”Source: code.claude.com
3.Scoping the gate to exactly the right tools
How a matcher is evaluated depends on the characters it contains. A matcher made only of letters, digits, underscores, hyphens, spaces, commas and pipes is treated as an exact tool name, or a list of exact names. If it contains any other character, it becomes a JavaScript regular expression. That regular expression is unanchored, so it matches anywhere in the tool name.
| Matcher value | Evaluated as | Fires on |
|---|---|---|
| "*", "", or omitted | Match all | Every occurrence of the event |
| Bash | Exact string | Only the Bash tool |
| Edit|Write | List of exact strings | Edit or Write, exactly |
| ^Notebook | Unanchored JavaScript regex | Any tool whose name starts with Notebook |
| mcp__memory__.* | Unanchored JavaScript regex | Every tool from the memory server |
Unanchored regexes are the usual source of over-matching. The matcher .*refund contains a dot and an asterisk, so it is read as a regex and matches any tool name containing refund: process_refund, but also issue_refund_note, a harmless internal comment tool, which then gets gated too. Anchoring the pattern as ^process_refund$ limits it to the one tool. The plain exact-string form process_refund avoids regex altogether. Matching is also case-sensitive, so Process_refund will not match process_refund.
MCP tools are named in the form mcp__server__action, where the server part is the key used in the mcpServers configuration. Suppose a billing server exposes three tools that move money alongside several read-only lookups. One registration can cover the three by listing their full names with pipes between them. That value contains only permitted characters, so it is read as a list of exact names. A broad pattern for the whole server would catch the read-only tools as well.
Checkpoint 4 of 7· Check yourself
A gate is registered with the matcher .*refund. The agent has three tools: process_refund, issue_refund_note and get_customer. Which of them does the gate fire on?
A character outside the plain-name set turns the matcher into an unanchored JavaScript regular expression, so any tool name containing refund matches. get_customer does not contain the substring, and the asterisk only means match-all when it is the whole matcher.
“JavaScript regular expression, unanchored”Source: code.claude.com
4.Decomposing a multi-concern request into parallel investigations
A single customer message often contains several separate problems. For example: "I was charged twice, my shipping address is wrong, and my discount never applied." If one pass handles all three, its attention is spread across them and one concern tends to get dropped. When a task has several considerations, the model usually does better when each one gets a separate LLM call. The first step is to split the request into distinct concerns, each of which can be investigated and resolved on its own.
Each concern then gets its own investigation, and they run in parallel. The coordinator spawns one subagent per concern with the Task (Agent) tool for spawning subagents. Subagents run concurrently, so the total time is that of the slowest investigation, not the sum of all three. A subagent starts with a fresh conversation and does not see the coordinator's turns. Shared context is therefore something the coordinator has to provide: every prompt carries the same case facts, such as the verified customer ID, order numbers and the customer's own words, so no subagent has to re-verify the customer or guess which account it is looking at.
Run the investigations in parallel and the actions in sequence. Lookups are independent and read-only, so they are safe to run concurrently. Refunds and address changes have side effects and ordering requirements, and they still pass through the prerequisite gate. The coordinator waits for every finding before it writes anything to the customer. A SubagentStop hook fires as each subagent completes, which gives the coordinator a point where it can confirm all investigations have finished and collect their results. It then writes one unified resolution. Three separate replies could contradict each other, for example by crediting the discount in one and refunding the same amount in another.
Checkpoint 5 of 7· Check yourself
A coordinator splits a three-part complaint and spawns one subagent per concern. The address subagent keeps asking which customer account it is working on. What explains this, and what is the fix?
A subagent starts with a fresh conversation and sees only its own prompt, so the case facts must be passed explicitly. Running sequentially would not give it the parent's history either.
“It does not see the parent’s turns, and only its final response returns to the parent.”Source: code.claude.com
5.Structured handoff when escalating to a human
Some cases need a human partway through: a policy exception, a refund above an authorised limit, a dispute the agent cannot settle. Hooks can enforce this by requiring human approval before a sensitive action. The person who takes over, however, has not seen the conversation. A human picking up a case from a queue is in the same position as a subagent's parent: all they have is what was handed to them.
The handoff should therefore be a structured summary that the human can act on without asking the customer to repeat anything. It needs four fields:
- Customer ID, verified, so the human can open the right account without checking identity again
- Root cause, the finding from the investigation (for example, a duplicate charge caused by a retried payment), not the customer's description of the symptom
- Amounts: the disputed charge, the proposed refund and any credit already applied, so the human does not have to recalculate them
- Recommended action and the reason it needs a human, so the human can approve, change or reject a specific proposal
A summary that just says "customer upset about billing, please review" fails because it points to information that only exists in the transcript, and the human cannot see it. A full transcript dump fails the other way, because the human has to work out the root cause again from scratch. The structured version passes on conclusions along with the evidence for them, much as a subagent returns a concise result and not every file it read.
Checkpoint 6 of 7· Exam question
A team wants to enforce that get_customer must run before process_refund, and registers two separate PreToolUse hooks: one matched to get_customer that writes a "verified" marker to a session file, and one matched to process_refund that reads that same file. A reviewer worries this design assumes the hooks run in a guaranteed order relative to each other. Is that assumption safe, and why?
Correct answer: D — It is unsafe, because each hook runs only when its matched tool is invoked, but nothing guarantees that get_customer is invoked before process_refund. The model could skip the prerequisite tool entirely, causing the process_refund hook to read a file that may not exist or contain valid data.
- A. Incorrect. Hooks are not executed in parallel for every tool call; they only run when their matchers (e.g., a regex on
tool_name) match the invoked tool. This behavior is documented in Anthropic Claude Code hook lifecycle rules, where hooks are triggered precisely by matching events, not indiscriminately. - B. Incorrect. Hooks run with the user's full permissions and can read/write the filesystem. They can share state through files, environment variables, or other IPC mechanisms. The real issue is not the lack of shared state but the absence of a guarantee that
get_customerwill execute beforeprocess_refund. - C. Incorrect. There is no alphabetical ordering of hook execution based on tool names. Hook fire order is determined solely by the sequence in which the matched tools are invoked by the model, not by any naming convention. This claim is not supported by Anthropic's documentation.
- D. Correct. The hook mechanism only ensures that a hook fires when its tool is called; it does not enforce that
get_customeris called first. Without a programmatic gate, the model might directly callprocess_refund, leading to a missing or stale file. Anthropic's certification guidance emphasizes implementing programmatic prerequisites or hooks that block downstream calls until prerequisite steps complete, rather than relying on prompt engineering or implicit ordering.
Checkpoint 7 of 7· Exam question
A developer implements a PreToolUse hook that gates the process_refund tool by checking a boolean flag is_verified. The flag is expected to be set to true by a separate mark_verified tool after a human reviewer approves a photo ID. In an incident, the mark_verified tool executed and the human reviewer explicitly rejected the ID, but due to a software bug the is_verified flag was incorrectly set to true. The PreToolUse hook consequently allowed process_refund, resulting in an unauthorized refund. What change to the PreToolUse hook would best prevent this category of failure?
Correct answer: C — Modify the PreToolUse hook to inspect the explicit verification result included in the process_refund tool call parameters, confirming that the human review expressly passed, instead of relying on a separate boolean flag that can be set incorrectly.
- A. PreToolUse hooks execute once before tool invocation and are not designed for periodic re-checks; the flag value would remain unchanged, so this does not prevent the failure.
- B. PostToolUse hooks fire after tool execution, by which time the model has already received and processed the tool’s response. This approach reverses the unauthorized action rather than preventing it, adding complexity without true prevention.
- C. Embedding the verification outcome as a parameter to
process_refundallows the PreToolUse hook (which has access to tool inputs) to deterministically confirm the actual review result. This follows Anthropic’s recommended practice of using explicit, self-contained tool interactions to avoid reliance on decoupled, mutable global state that can be corrupted. - D. Agent safety relies on deterministic architectural controls rather than probabilistic model reasoning. A larger model may still misinterpret context and cannot provide the same level of guarantee as a structured parameter check in a hook.
Sources
(7)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://code.claude.com/docs/en/hooksOfficial docs
“Before a tool call executes. Can block it”
↩︎ Why workflow ordering for money needs enforcement, not instructions“JavaScript regular expression, unanchored”
↩︎ Scoping the gate to exactly the right tools“JavaScript regular expression, unanchored”
↩︎ Exam trap 4 - 2.https://www.anthropic.com/engineering/building-effective-agentsSecondary source
“selecting appropriate tools, and determining what information to retain.”
↩︎ Why workflow ordering for money needs enforcement, not instructions“on any intermediate steps to ensure that the process is still on track.”
↩︎ Why workflow ordering for money needs enforcement, not instructions“For complex tasks with multiple considerations, LLMs generally perform better when each consideration is handled by a separate LLM call”
↩︎ Decomposing a multi-concern request into parallel investigations - 3.https://code.claude.com/docs/en/hooks-guideOfficial docs
“After a tool call succeeds”
↩︎ Building the gate: record in PostToolUse, block in PreToolUse“Since hooks run in parallel, the order is non-deterministic.”
↩︎ Building the gate: record in PostToolUse, block in PreToolUse“PostToolUse hooks can’t undo actions since the tool has already executed.”
↩︎ Building the gate: record in PostToolUse, block in PreToolUse“Matchers are case-sensitive”
↩︎ Scoping the gate to exactly the right tools“After a tool call succeeds”
↩︎ Exam trap 1“PostToolUse hooks can’t undo actions since the tool has already executed.”
↩︎ Exam trap 2“Since hooks run in parallel, the order is non-deterministic.”
↩︎ Exam trap 3“PreToolUse | Before a tool call executes. Can block it”
↩︎ Checkpoint - 4.https://code.claude.com/docs/en/agent-sdk/hooksOfficial docs
“Use a shared variable or session state to track whether”
↩︎ Building the gate: record in PostToolUse, block in PreToolUse“PreToolUseHookInput includes tool_name and tool_input”
↩︎ Building the gate: record in PostToolUse, block in PreToolUse“MCP tools use the pattern mcp__<server>__<action>, where <server> is the key you use in the mcpServers configuration.”
↩︎ Scoping the gate to exactly the right tools“Aggregate results from parallel tasks”
↩︎ Decomposing a multi-concern request into parallel investigations“Require human approval for sensitive actions like database writes or API calls”
↩︎ Structured handoff when escalating to a human“Block dangerous operations before they execute, like destructive shell commands or unauthorized file access”
↩︎ Key concept - 5.https://code.claude.com/docs/en/agent-sdk/subagentsOfficial docs
“independent subtasks finish in the time of the slowest one rather than the sum of all of them”
↩︎ Decomposing a multi-concern request into parallel investigations“The parent receives a concise summary, not every file the subagent read.”
↩︎ Structured handoff when escalating to a human - 6.https://code.claude.com/docs/en/agent-sdk/agent-loopOfficial docs
“It does not see the parent’s turns, and only its final response returns to the parent.”
↩︎ Decomposing a multi-concern request into parallel investigations - 7.
“Tools with side effects, shared state, or ordering requirements might be better run sequentially.”
↩︎ Decomposing a multi-concern request into parallel investigations