Skip to content
CCAR-F Prep

Task Statement 1.4·Domain 1 — 27% of exam

Workflow Enforcement and Handoff

Implement multi-step workflows with enforcement and handoff patterns

Jump to practice →

Official Exam Guide Objectives

The objectives below are quoted from Anthropic's Claude Certified Architect – Foundations exam guide, v1.1. Read the exam guide summary for the full blueprint.

Task 1.4: Implement multi-step workflows with enforcement and handoff patterns.

Knowledge of

  • The difference between programmatic enforcement (hooks, prerequisite gates) and prompt-based guidance for workflow ordering
  • When deterministic compliance is required (e.g., identity verification before financial operations), prompt instructions alone have a non-zero failure rate
  • Structured handoff protocols for mid-process escalation that include customer details, root cause analysis, and recommended actions

Skills in

  • Implementing programmatic prerequisites that block downstream tool calls until prerequisite steps have completed (e.g., blocking process_refund until get_customer has returned a verified customer ID)
  • Decomposing multi-concern customer requests into distinct items, then investigating each in parallel using shared context before synthesizing a unified resolution
  • Compiling structured handoff summaries (customer ID, root cause, refund amount, recommended action) when escalating to human agents who lack access to the conversation transcript

What You Need to Know

Task Statement 1.4 draws a hard line between two approaches to controlling agent behaviour: prompt-based guidance and programmatic enforcement. The first official sample question in the exam guide turns on exactly this distinction, and its explanation is blunt about it wherever an error has financial consequences.

The whole task statement compresses into one sentence: a prompt is a request, and a gate is a guarantee.

The Enforcement Spectrum

Two genuinely different mechanisms for making a workflow happen in the right order:

Prompt-based guidance places the requirement in the system prompt — "Always verify the customer's identity before processing a refund." It is not weak: most runs will follow it. But a language model is probabilistic, so a share of runs will read the instruction loosely, reorder the steps, or skip one under an unusual request. The exam guide's wording is that prompt instructions alone have "a non-zero failure rate". Where an occasional miss is merely untidy, that is a perfectly sound trade.

Programmatic enforcement places the requirement in code — a hook, a prerequisite gate, a check that refuses to run the downstream tool until its precondition is satisfied. process_refund cannot execute until get_customer has returned a verified customer ID. There is no success rate to quote, because the model's judgement is not part of the mechanism: whatever it decides to attempt, the gate holds.

The Exam Decision Rule

The guide's own example of "deterministic compliance" is identity verification before financial operations, and sample question 1 rejects both prompt-based options because they "rely on probabilistic LLM compliance, which is insufficient when errors have financial consequences". Generalised into a rule you can apply to any stem:

  • Financial operations (refunds, transfers, payments): programmatic enforcement. One refund reaching the wrong account is a real loss, and an average across the other runs does not offset it.
  • Security operations (identity verification, access control): programmatic enforcement. One bypass is a breach, and breaches are counted individually rather than as a rate.
  • Compliance operations (AML checks, regulatory requirements): programmatic enforcement. One skipped check is the finding a regulator writes up, regardless of how many were performed correctly.
  • Low-stakes operations (formatting preferences, style guidelines, output ordering): prompt-based guidance is acceptable. An inconsistent heading costs nothing, and a gate here is machinery built to enforce a preference.

The same reasoning extends to anything where a single violation cannot be absorbed: personal data, legal commitments, and actions that cannot be undone.

Expect the high-stakes items to offer a better prompt among the options. Stronger wording, few-shot examples of the correct sequence, a restructured system message — each genuinely raises the success rate and none changes the shape of what you have. Where the scenario names money, security or compliance, the answer is the gate.

The rule cuts both ways. Official sample question 3 (Task 5.2) describes an agent that escalates easy cases and attempts hard ones, and its keyed answer is a prompt change: explicit escalation criteria with few-shot examples, described as "the proportionate first response before adding infrastructure". The problem there is an unclear decision boundary, which is a matter of judgement, not a rule that must hold on every run. Read the stakes and the kind of requirement in the stem before reaching for code.

Reading the Stem: Requirement Words, and Selection versus Ordering

Most items on this task statement can be answered from two things in the stem: the words used for the requirement, and what kind of mistake the agent is making.

Signal in the stemMechanism to chooseWhy
"must", "always", "before any", "guaranteed", "policy requires"Programmatic gate (a hook or prerequisite check)The requirement is deterministic, so the mechanism has to be
Money, identity, personal data, legal exposure, an irreversible actionProgrammatic gateOne violation is already unacceptable
A measured violation rate ("in 12% of cases…") that has to reach zeroProgrammatic gatePrompting lowers a rate; it cannot make it zero
"prefer", "usually", "when appropriate", "should generally"System prompt, with few-shot examples where the boundary is fuzzyThis is judgement, not compliance
The agent picks the wrong tool for the request (tool selection)Better tool descriptions (Task 2.1)Descriptions are what the model selects on; official sample question 2 keys this
The agent calls the right tools in the wrong order, or skips one (tool ordering)Programmatic gateOrdering is an enforcement problem; official sample question 1 keys this
One specific tool must be the first call of a single requestForced tool_choice (Task 2.3)It controls one response, not the session

Selection and ordering are the pair most often confused. If the stem says the agent "calls get_customer when the user asks about an order", the tool chosen is wrong and the fix lives in the descriptions. If it says the agent "skips get_customer and goes straight to lookup_order", the tools are right and the sequence is wrong, and the fix is a gate.

Same Requirement, Three Strengths: Prompt, tool_choice, Gate

tool_choice is a Messages API request parameter that controls whether and which tool Claude must call in that response. Its forced form, {"type": "tool", "name": "get_customer"}, looks like enforcement, which is why it appears beside the gate in answer options. Compare what each mechanism actually covers for the requirement "verify the customer before any order or refund operation":

MechanismWhat it looks likeWhat it guarantees
Prompt"Always call get_customer before lookup_order or process_refund." in the system promptNothing. Compliance is high and not 100%
Forced tool_choicetool_choice={"type": "tool", "name": "get_customer"} on one requestThat this one response starts with a get_customer call. It says nothing about later turns, and nothing about whether the lookup came back verified
Prerequisite gateCode that checks session state before the gated tool runsThat the gated tool cannot run in any turn of the session until the condition holds

Forced tool_choice answers a different question — "make sure this tool is called first, then carry on in follow-up turns" — which belongs to Task 2.3.

Prerequisite Gates in Practice

A prerequisite gate is a programmatic check that blocks a tool from executing until a prior condition is met. In a customer support agent:

  1. The agent has access to get_customer, lookup_order, and process_refund tools.
  2. Before process_refund runs, a gate inspects session state: has get_customer returned a verified customer ID?
  3. Where it has, the call proceeds exactly as normal — the gate is invisible on the happy path.
  4. Where it has not, the call never executes. The agent receives an error instead: "Cannot process refund — customer identity not verified. Please call get_customer first."

What makes this work is that step 2 runs in code, so the model is not consulted and cannot reason its way past it, misread it, or treat this case as an exception. Returning the refusal as a tool result rather than failing silently matters too: the agent reads the error, calls get_customer, and retries without human intervention.

Which tools sit behind the gate depends on where the damage starts. The guide's skill bullet gates process_refund. Official sample question 1 gates lookup_order as well, because in that scenario the agent was looking orders up "using only the customer's stated name", and the wrong account was chosen before any refund was attempted.

Six design points separate a gate that works from one that only looks like it:

  • Give the gate something structured to read. get_customer should return two separate fields: a customer ID and a verification status. An ID on its own does not prove the caller was confirmed as its owner, since a lookup can find a record without verifying anybody. A bare true/false says a verification happened without saying whose. Free text that the gate scans for a phrase puts interpretation back into a mechanism whose whole point is to have none.
  • Key it on the result, not the call. The condition is "get_customer returned a verified customer ID", not "get_customer was called". A lookup that fails, or returns several possible matches, has verified nobody and must not open the gate.
  • Hold the state in code, per session. The invariant spans the whole conversation, so the state lives outside any single request; and it must not outlive the conversation, or one verified customer unlocks refunds for the next. State that exists only as a line in the system prompt, or that is inferred from what was said earlier in the conversation, is not state at all: it is one more instruction the model is free to skip.
  • Act on the ID the code holds. Issue the refund against the verified customer ID in the gate's own state, and refuse a call whose customer_id differs from it. An ID supplied by the model is a claim, not a fact. For the same reason, knowing who the caller is does not settle what they own: a refund on an order belonging to a different account needs its own check in code.
  • Write the refusal for the model, not for a log. The message has to name the missing prerequisite and the way out: call get_customer, and if the customer cannot be identified from what they have given, ask them for another identifier. A bare "denied" gives the agent nothing to act on, and the usual result is the same call retried blindly.
  • Verify once, reuse everywhere. One verified identity serves every later tool call in the session. Re-verifying before each operation is waste; verifying for none is the failure the gate exists to stop.

How do you know the gate works? Not by watching the agent behave. An agent that never attempts the unverified refund has shown that the prompt worked on that run; the gate is proven only by a call that is made and refused. So test it in two layers. First call the gate directly, with no model involved, and check four things: a refund before verification is refused; a lookup that comes back unverified does not open the gate; a verified lookup does; and a second session is still locked. Then push the agent with an urgent "refund this immediately" message and read the tool-call log: any blocked attempt must be followed by get_customer, and only then by a refund that succeeds.

Blocked once, verified, then let through The agent calls process_refund without prior verification. A gate checks the session's verified_customer_id, finds it null, and blocks the call — the refusal returns as a tool_result the agent can read, not a silent failure, so the agent can act on it. The agent calls get_customer, which returns a verified ID and records it in session state. The agent retries the identical process_refund call. The gate checks the same session state again, now finds cus_9214, and the refund proceeds. Nothing about the gate changed between the two checks — only the state it was reading did. process_refund(150) checks verified_customer_id → null ✕ BLOCKED Call get_customer first a tool_result, not a silent failure get_customer(...) → verified: cus_9214 process_refund(150) checks verified_customer_id → cus_9214 ✓ Refund processed $150.00
1 / 6Swipe diagram ↔

Blocked once, verified, then let through, step 1: The agent calls process_refund directly — no verification yet

Subagent Lifecycle Hooks: SubagentStart and SubagentStop

The Claude Agent SDK provides lifecycle hook events specifically for subagent management. These complement the PreToolUse and PostToolUse hooks covered in Task Statement 1.5.

SubagentStart fires when a subagent is spawned via the Task tool (the exam guide's name; the tool was renamed Agent in Claude Code v2.1.63, and Task(...) references still work as aliases). Its role is observational: it receives the subagent's type and id, and can record the spawn or add context to the run. It cannot stop the spawn or alter it. Enforcing anything about spawning itself — a rate limit, or a check that the coordinator supplied the context it was supposed to — belongs on a PreToolUse hook attached to the Agent tool, which can deny or rewrite the invocation before it leaves.

SubagentStop fires when a subagent finishes execution and returns its results to the coordinator. It receives the subagent's id and final message, which is enough to validate the output and record completion for performance monitoring. Where validation fails — the output does not match the expected schema, say — the hook returns decision: "block" with a reason, and the subagent resumes work instead of finishing. What it cannot do is transform what comes back: reshaping or redacting the output is a PostToolUse hook on the Agent tool call, whose updatedToolOutput field replaces the tool result before the model reads it. The Deep Dive lists the cases where the final message or the Agent tool's result is not what this description suggests, such as background subagents.

Subagent-scoped hooks: A subagent defined as a markdown file may declare its own hooks, PreToolUse and PostToolUse among them, in that file's YAML frontmatter. Those hooks run only while that subagent is active — not for the coordinator's tool calls, and not for its siblings'. That scoping is what makes per-subagent policy possible: a billing subagent can carry a PreToolUse hook refusing refunds above a threshold while a technical support subagent operates without any such restriction. The reverse does not hold: a hook registered for the whole session also runs before every tool a subagent uses, which is where a rule that must cover every path belongs.

Stop hook auto-conversion: Stop hooks declared in a subagent's frontmatter are converted to SubagentStop events at runtime. Cleanup and validation logic can therefore live in the subagent's own configuration and still fire at the correct point in the lifecycle, without the coordinator having to register anything on its behalf.

SubagentStart watches; SubagentStop can send work back Four checkpoints run in order around a subagent's lifecycle. PreToolUse on the Agent tool fires before the subagent spawns and can deny or rewrite the invocation — that hook belongs to Task Statement 1.5. SubagentStart fires when the subagent is spawned: it observes and can add context, but it cannot stop the spawn or alter it. SubagentStop fires when the subagent finishes: it can block completion, returning decision block with a reason that sends the subagent back to work, but it cannot transform what the subagent returns. PostToolUse on the Agent tool fires after the result returns to the coordinator and can transform or redact the output — again a Task 1.5 hook. Reshaping output is a Pre or PostToolUse job, never SubagentStart's or SubagentStop's. PreToolUse (Agent) — before spawn ✓ can deny or rewrite the invocation (covered in Task 1.5) SubagentStart — subagent is spawned ✓ observes: records the spawn, adds context ✕ cannot block or alter it SubagentStop — subagent finishes ✓ can block — sends it back to work ✕ cannot transform what it returns PostToolUse (Agent) — after it returns ✓ can transform or redact the output (covered in Task 1.5) reshaping output belongs to Pre/PostToolUse, not Start or Stop
1 / 6Swipe diagram ↔

SubagentStart watches; SubagentStop can send work back, step 1: PreToolUse on the Agent tool fires before the subagent spawns

Multi-Concern Request Handling

Customers rarely ask one thing at a time: "I want to return my order, update my shipping address, and ask about my loyalty points" is a single message carrying three jobs. The exam tests what an agent should do with it.

The correct approach:

  1. Decompose the request into distinct items (return, address update, loyalty inquiry).
  2. Investigate each in parallel using shared context — the account details bear on all three, so there is no reason to fetch them three times or to make one item wait on another.
  3. Synthesise a unified resolution that answers every item in one response.

The failures are the predictable pair: handling each item in its own separate conversation, which makes the customer restate context they already supplied; or answering the first item competently while the remaining two are quietly dropped.

Decompose every concern — don't just answer the first One customer message carries three concerns: returning an order, updating a shipping address, and a loyalty points question. An agent that answers only the return and stops leaves the address change and the loyalty question never addressed — the same request, silently reduced to one item. The correct handling decomposes the request into all three items, investigates them in parallel against shared account context, and synthesises one response that resolves all three, with nothing dropped. the request ① return order ORD-789 ② update shipping address ③ loyalty points question ✕ ✕ agent response "Return started for ORD-789." ✕ ② and ③ never addressed agent response Return started · address updated · 340 loyalty points available ✓ all three addressed, one response decompose → parallel investigation → synthesis
1 / 6Swipe diagram ↔

Decompose every concern — don't just answer the first, step 1: One message, three concerns: return, address, loyalty points

A worked example. The customer writes: "My order #4417 arrived damaged, I was charged twice for #4390, and I want to update the card on file." That is three concerns on three different tool paths, and one customer identity:

  1. Resolve identity once. get_customer returns a verified customer ID. This is the shared context: the same ID, account tier and history serve all three items, and the gate is satisfied for the rest of the session.
  2. Investigate the three items side by side. The damaged item needs lookup_order on #4417 and leads to a replacement. The duplicate charge needs lookup_order on #4390 plus the billing record and leads to refunding one charge. The card change needs the account tool. None depends on another's result, so the lookups can be requested together.
  3. Reply once. One response covers all three, with each item's outcome stated separately so the customer can see that nothing was skipped.
DoDo not
Split the message into distinct items and track each oneAnswer the first concern and drop the rest
Reuse the single verified identity across every itemRe-verify for each item (wasteful), or verify for none (unsafe)
Investigate independent items in parallelRun independent lookups one after another
Write one reply covering every item, each with its own outcomeSend three disconnected replies
Escalate only the item that needs a human, and resolve the othersEscalate the whole conversation because one item is hard

The last row is partial escalation: one concern the agent cannot resolve does not make the others unresolvable. The handoff for the stuck item should still say what was done about the others, so the human does not redo them.

Structured Handoff Protocols

When an agent can't resolve an issue and must escalate to a human agent, the handoff must follow a structured protocol. One constraint shapes the whole format: the human agent does NOT have access to the conversation transcript. There is no scrollback to consult, so whatever the summary contains is the entire briefing.

The exam guide names four fields a handoff summary carries. Learn these four as the exam's list:

  • Customer ID — without it the human's first act is asking who they are speaking to.
  • Root cause — the agent's reading of what is actually wrong, rather than the symptom the customer reported or what the customer believes happened.
  • Refund amount (if applicable) — the figure itself, not a reference to a refund having been discussed.
  • Recommended action — what the agent believes should happen next.

Omit any one of these and the human reconstructs it from the customer, who is now explaining the same problem for a second time — which is the outcome the escalation was supposed to avoid.

A handoff is the whole briefing, not a partial one The human agent taking an escalation has no access to the conversation transcript — this summary is the entire briefing. conversation_summary, root_cause_analysis and refund_amount are filled in, but customer_id and recommended_action are left blank, so the human's first act is asking the customer who they are and starting the diagnosis over. Filling in every field — customer_id, conversation_summary, root_cause_analysis, refund_amount and recommended_action — leaves nothing for the human to reconstruct, and the handoff resolves the case without the customer explaining anything a second time. Human agent sees only this summary — no transcript escalate_to_human customer_id — missing — customer_id cus_4471 conversation_summary wrong item shipped, wants refund root_cause_analysis warehouse sent SKU-221, not SKU-118 refund_amount $84.00 recommended_action — missing — recommended_action approve refund, flag SKU mix-up ✕ human must ask who, and what to do ✓ human can act immediately the customer explains everything again resolved without asking the customer again
1 / 6Swipe diagram ↔

A handoff is the whole briefing, not a partial one, step 1: The human agent has no transcript — only this summary

A handoff that carries only those four is the minimum, and the guide's knowledge bullet speaks more broadly of "customer details, root cause analysis, and recommended actions". The fields below are not listed in the guide; they are design reasoning that makes the same summary harder to misread, and they are the kind of detail a more demanding option may include:

Additional fieldWhy it earns its place
A short issue summary, two or three factual sentencesSays what was asked for, in the customer's terms, before the analysis starts
Actions already taken, in order, each with its outcomeStops the human repeating a step — above all a refund that has already gone through
Escalation reason as a fixed set of values (customer asked for a human, policy gap or exception, no progress, limit exceeded)A fixed set can be counted and compared across thousands of escalations; free text cannot
The customer's stated expectation, word for wordSummaries are where what the customer actually asked for gets blurred; the guide lists "customer-stated expectations" among the things progressive summarisation loses (Task 5.1)
How to reach the customer, and any policy clauses the agent consultedThe human can reply on the right channel and can see which rule the agent was applying
Order IDs, and each amount as a whole number of minor units plus a currency code8400 and USD cannot be misread; "about eighty-four dollars" can, and a formatted string has to be parsed again

The shape matters as much as the content. A free-text note along the lines of "customer upset about a refund, please assist" is a handoff in name only: it loses the transactional facts, and the human has to interview the customer again. Give the escalation tool a schema with named, required fields, so that a missing fact is a validation error instead of a gap somebody discovers later.

A complete handoff for a single stuck concern looks like this. customer_id, root_cause_analysis, refund_amount_cents and recommended_action are the guide's four fields; the rest are the additions from the table:

{
  "customer_id": "cus_4471",
  "conversation_summary": "Customer received the wrong item on order ORD-789 and wants a refund instead of a replacement.",
  "root_cause_analysis": "Warehouse shipped SKU-221 in place of SKU-118. The order record shows the correct SKU, so the error was at picking.",
  "refund_amount_cents": 8400,
  "currency": "USD",
  "recommended_action": "Approve the full refund without requiring a return, and flag the SKU mix-up to the warehouse.",
  "order_ids": ["ORD-789"],
  "actions_taken": [
    "get_customer: verified cus_4471",
    "lookup_order ORD-789: delivered, SKU-118 ordered",
    "process_refund: refused, amount is above the agent's limit"
  ],
  "escalation_reason": "limit_exceeded",
  "customer_stated_expectation": "I want my money back, I am not waiting for another parcel."
}

A schema's required list only guarantees that a field is present. It does not stop "n/a", "see above" or "the issue discussed earlier" being written into it, and the last of those is the worst, because it points the human at a conversation they cannot see. Check the payload in code before it is sent: no required field empty, none holding a placeholder, none referring back to the conversation, and no amount without its currency.

For a multi-concern message the same payload has three more things to get right. Every concern appears in it, each with its own specifics, not only the first. The customer was verified once, and that one verified ID served all the concerns. And only the item the agent could not resolve is left for the human in the recommended action; the items it did resolve are listed under the actions taken, with their outcomes.

Practical Example: The 12% Skip Rate

This is official sample question 1 (dissected option by option under How This Is Tested). Production data shows that in 12% of cases the customer support agent skips get_customer entirely and calls lookup_order using only the customer's stated name, "occasionally leading to misidentified accounts and incorrect refunds".

So the agent verifies identity in 88% of cases, and some of the remaining 12% has already produced refunds on the wrong accounts. That makes this a financial operation with realised losses rather than a hypothetical risk.

A better prompt or a set of few-shot examples might cut the 12% substantially, to 3 or 4% say. That is a real improvement and still not a fix when each remaining failure moves money. A prerequisite that blocks lookup_order and process_refund until get_customer has returned a verified customer ID removes the failure outright, by making the wrong order impossible rather than unlikely.

Put as arithmetic over 1,000 conversations, with one invented assumption (that a rewritten prompt removes 70% of the skips):

MechanismConversations where verification is skippedUnverified order or refund calls that execute
Current behaviourabout 120about 120
Rewritten prompt, few-shot examplesabout 36about 36
Programmatic prerequisitewhatever the model does0

The last row does not depend on the skip rate. Change the 12% to 30% or to 1% and it stays at zero, because what the model decides is no longer part of the mechanism. That independence is what "deterministic" means in the official explanation.

A gate holds where a prompt only usually works Two bars, each representing 100 refund requests. Under prompt-based guidance alone, 88 requests are verified correctly and 12 go through before identity is verified — real refunds sent before the customer was confirmed. Under a programmatic prerequisite gate, all 100 are verified, because the gate holds regardless of what the model decides to attempt; there is no run where it can skip the check. A prompt shifts a probability toward compliance; a gate supplies a guarantee. The question worth asking is not whether the prompt is good enough, but what a single failure costs. Prompt-based guidance 88 of 100 — verified correctly 12 of 100 sent before identity verified Programmatic enforcement 100 of 100 — verified, every time 0 of 100 — the gate holds regardless a prompt shifts a probability, a gate supplies a guarantee the question is what one failure costs
1 / 6Swipe diagram ↔

A gate holds where a prompt only usually works, step 1: 100 refund requests, prompt-based guidance only

Deep Dive

The permission evaluation order — where "enforcement" actually sits

Programmatic enforcement is not one undifferentiated blob — every tool request passes through a strict, ordered sequence. In the docs' words, "Claude Code checks the call at these steps. Each step can decide the call, send it to your canUseTool callback, or pass it on": hooks, deny rules, ask rules, permission mode, allow rules, then the canUseTool callback. This ordering is the concrete mechanism behind "programmatic enforcement vs prompt-based guidance": prompt-based guidance never appears in this list at all — it only shapes what the model chooses to attempt. Everything in the evaluation order runs regardless of what the model decides, which is exactly why it is deterministic.

Sourcecode.claude.com › permissionsfetched 2026-11-19

Deny beats everything, including bypassPermissions

A deny rule holds in every permission mode. If one matches, "the call is denied and canUseTool isn't called. The call is denied this way even in bypassPermissions mode and when a hook returned allow." And a hook cannot soften this from the other direction either — "A hook that returns allow doesn't skip the deny-rule and ask-rule steps, which are evaluated regardless of the hook result." For a scenario like refund verification, this means a deny rule or a blocking hook is a stronger guarantee than any permission mode the session happens to be running in.

One documented exception is worth knowing so that "nothing can override a deny" is not overstated. A mod is a plugin extension that can answer tool-approval checks after the hooks have run. In a setup with no managed settings and no Team or Enterprise login, the Claude Code permissions page says "the mod can approve a call that a PreToolUse hook blocked, and some calls that a deny rule refuses." It is an installation choice, not something the model can do, so it does not change the exam answer; it is a reason to control what is installed in a production agent's environment.

Sourcescode.claude.com › permissionscode.claude.com › permissionsfetched 2026-11-19

canUseTool is not a universal enforcement point — hooks are

A common mistake is assuming a custom canUseTool callback enforces a rule on every tool call. It does not: "Auto-approved tools never reach canUseTool. A tool call approved at any earlier step, by acceptEdits or bypassPermissions, or by an allow rule, skips your canUseTool callback, so permission checks you put there are silently bypassed for that tool." The documented fix for a check that must also cover those calls: "To check calls that an allow rule, acceptEdits, or bypassPermissions approves, use a PreToolUse hook, which runs for those calls too. A hook deny applies even in bypassPermissions mode." This is the precise reason prerequisite gates (like blocking process_refund until get_customer succeeds) belong in a hook rather than in a permission callback that might never fire.

Sourcecode.claude.com › permissionsfetched 2026-11-19

Why hooks are the documented answer to "must never fail"

Anthropic's own framing of what hooks are for maps directly onto the exam's decision rule. With hooks you can "Block dangerous operations before they execute, like destructive shell commands or unauthorized file access", "Log and audit tool calls for compliance, debugging, or analytics", "Transform inputs and outputs to sanitize data, inject credentials, or redirect file paths", "Require human approval for sensitive actions like database writes or API calls", and "Track session lifecycle to manage state, clean up resources, or send notifications". The first four are each a scenario where a single silent failure has a real-world cost — financial, security, or compliance — which is exactly the exam's threshold for choosing programmatic enforcement over a system-prompt instruction.

Sourcecode.claude.com › hooksfetched 2026-11-19

A second enforcement lever: scoped deny rules on the tool itself

Prerequisite gates are not the only programmatic mechanism. disallowed_tools offers a coarser but still deterministic lever, and its two forms behave differently. With the bare form, disallowed_tools=["Bash"], "The Bash tool definition is removed from the request." With the scoped form, disallowed_tools=["Bash(rm *)"], "Bash stays available. Calls matching rm * as written are denied in every permission mode, including bypassPermissions. Other Bash calls, including /bin/rm, fall through to the permission mode." That last clause is a reminder that a pattern rule blocks what it matches and nothing else.

Know what a deny rule can express. It can name a tool, a command or path pattern, or an exact input value: "Deny and ask rules can match a top-level input parameter on any built-in tool with Tool(param:value)", and such a rule "matches when Claude calls the tool with that parameter set to that exact value". Nothing in that syntax compares a number against a limit or looks at what happened earlier in the session. A refund ceiling ("no refund above $500") or a prerequisite ("only after get_customer returned a verified ID") therefore cannot be written as a deny rule, and belongs in a PreToolUse hook. The two levers are complementary: a deny rule for "never this tool, or never this exact call", a hook for anything that needs arithmetic or state.

Sourcescode.claude.com › permissionscode.claude.com › permissionsfetched 2026-11-19

What a hook denial returns, and what happens when several hooks answer

A PreToolUse gate blocks a call by returning a hookSpecificOutput object containing hookEventName, permissionDecision: "deny" and a permissionDecisionReason. The docs spell out who each field is for: "permissionDecision: 'deny' stops the tool call", "permissionDecisionReason tells the model why", and the top-level systemMessage "shows the user what happened". The hooks reference says the same of the reason: for a deny it is "shown to Claude". That is why the reason is the place to put the recovery instruction — it is the only part of the denial the agent reads. The same channel carries a redirect to another workflow: a refund-limit hook's reason can say that refunds above the limit need human approval, tell the agent to call escalate_to_human with a structured handoff, and tell it to let the customer know a specialist is reviewing the request (the pattern itself is Task 1.5). To let a call through, "Return {} to allow the operation without changes."

Per-session state has a ready key: "All hook inputs share session_id, cwd, and hook_event_name."

A gate is rarely the only hook. "When an event fires, the matching hooks run in parallel. For permission decisions, the most restrictive result applies. One hook's deny blocks the tool call. Because completion order is non-deterministic, write each hook to act independently rather than relying on another hook having run first." The full ranking when hooks disagree is "deny takes priority over defer, which takes priority over ask, which takes priority over allow." For the support agent this means a verification gate and a refund ceiling are two separate hooks, each correct on its own, and an auto-approving hook elsewhere cannot outvote either of them.

Sourcescode.claude.com › hookscode.claude.com › hooksfetched 2026-11-19

A guard that crashes fails open unless you tell it not to

A gate is only a guarantee while its code runs. By default it does not fail safe: "On most events, if a callback throws or returns output that fails validation, the action goes ahead", and specifically "A PreToolUse guard that crashes then lets the tool call reach the normal permission flow." A code path with no return counts as a failure too. The fix is one option on the matcher: "To block the action instead, set onFailure: "block" in TypeScript or on_failure="block" in Python on the matcher. Requires TypeScript Agent SDK v0.3.317 or later, or Python Agent SDK v0.2.177 or later." A timeout is handled the safe way without any setting: when a PreToolUse callback exceeds its timeout, "Claude Code blocks the tool call."

For a rule about money, set the option, and let errors propagate out of the guard instead of catching them and returning {} — the docs note that "A callback that catches its own error and returns {} isn't failing".

Sourcecode.claude.com › hooksfetched 2026-11-19

Naming MCP tools in a gate

The scenario's four tools are MCP tools, so a hook does not see them as process_refund. "MCP tools use the pattern mcp__<server>__<action>, where <server> is the key you use in the mcpServers configuration". With the server registered under the key support, the refund tool is mcp__support__process_refund, and that is the string a matcher and a gate compare against.

Matchers have two evaluation paths. A value made only of letters, digits, _, -, spaces, commas and the pipe character is compared as an exact string or a list of exact strings; anything else is treated as an unanchored JavaScript regular expression. Hence the rule for covering a whole server: "To match every tool from a server, append .* to the server prefix. The .* is required". And a matcher only ever looks at the name: "Matchers only match tool names, not file paths or other arguments", so a check on the refund amount or on session state happens inside the callback.

Sourcescode.claude.com › hookscode.claude.com › hooksfetched 2026-11-19

A prerequisite gate as Agent SDK hooks

With the Claude Agent SDK the gate is a pair of hooks: a PostToolUse hook records the verification and a PreToolUse hook refuses the gated tools. The tool names carry the MCP prefix (here the server key is support), the state is keyed by the session_id every hook input carries, and on_failure="block" makes a crashing guard refuse the call instead of letting it through:

import type {
  HookCallback,
  Options,
  PostToolUseHookInput,
  PreToolUseHookInput
} from "@anthropic-ai/claude-agent-sdk";

const GET_CUSTOMER = "mcp__support__get_customer";
const GATED = new Set(["mcp__support__lookup_order", "mcp__support__process_refund"]);
const verified = new Map<string, string>(); // session_id -> verified customer ID

// Written for the model: names the missing step and the way out.
const NOT_VERIFIED =
  "Customer identity is not verified. Call get_customer and obtain a verified customer_id " +
  "before any order or refund operation. If the customer cannot be identified, ask them " +
  "for another identifier.";

const recordVerification: HookCallback = async (input) => {
  const post = input as PostToolUseHookInput;
  // tool_response is whatever the tool returned; its shape depends on the tool.
  const customer = readCustomer(post.tool_response);
  if (customer.verified && customer.customer_id) verified.set(post.session_id, customer.customer_id);
  return {};
};

const requireVerifiedCustomer: HookCallback = async (input) => {
  const pre = input as PreToolUseHookInput;
  if (!GATED.has(pre.tool_name) || verified.has(pre.session_id)) return {}; // {} allows the call
  return {
    hookSpecificOutput: {
      hookEventName: "PreToolUse",
      permissionDecision: "deny",
      permissionDecisionReason: NOT_VERIFIED // shown to Claude
    }
  };
};

const options: Options = {
  hooks: {
    PreToolUse: [{ matcher: "mcp__support__.*", hooks: [requireVerifiedCustomer], onFailure: "block" }],
    PostToolUse: [{ matcher: GET_CUSTOMER, hooks: [recordVerification] }]
  }
};

The code holds three invariants: only a verified result opens the gate, the state belongs to one session, and the refusal tells the agent what to do next. readCustomer (read_customer in Python) stands for your own parsing of the tool's result. If you run the tool loop yourself with the Messages API instead, the same check sits in the function that executes each tool_use block, and the refusal goes back as a tool_result with is_error set — the flag the docs say to "Set to true if the tool failed or the call was invalid".

Sourcescode.claude.com › hooksplatform.claude.com › handle-tool-callsfetched 2026-11-19

Forced tool_choice controls one response

tool_choice has "four possible options": auto "allows Claude to determine whether to call any provided tools" and is the default when tools are provided; any "tells Claude that it must use one of the provided tools"; tool "forces Claude to always use a particular tool"; none "prevents Claude from using any tools". The forced forms act on the response being generated: "When tool_choice is any or tool, the API makes Claude's response start with a tool call." Nothing carries over to the next request unless you send the parameter again, which is why it cannot stand in for a session-long ordering rule.

Forced tool use is also not universal. "Not every model and setting supports forced tool use. Where it isn't supported, tool_choice: {"type": "any"} and tool_choice: {"type": "tool", "name": "..."} fail". The page lists manual extended thinking, where the two forced forms "are not supported and result in an error", and Claude Fable 5.2, Mythos 5.2, Opus 5.5, Sonnet 5.5, Fable 5.1 and Mythos 5.1, where they "return a 400 error".

Sourceplatform.claude.com › define-toolsfetched 2026-11-19

Subagent hook details that matter in practice

SubagentStart fires more often than "once per spawn": it "Runs when Claude spawns a subagent with the Agent tool, when Claude resumes a subagent, and each time an in-process agent team teammate handles a new message." Its limit is stated outright: "SubagentStart hooks can't block subagent creation, but they can inject context into the subagent."

SubagentStop blocks through the same format as a Stop hook: "Returning decision: "block" with a reason keeps the subagent running and delivers reason to the subagent as its next instruction." Two caveats apply to reading the subagent's output there. The final text arrives in last_assistant_message, but on Claude Code v2.1.271 or later a subagent that reports through the SubagentHandback tool delivers its report in that tool call, and last_assistant_message "then holds the subagent's closing text, if any, which is not the delivered report". And "Not every SubagentStop event comes from a subagent Claude spawned", because Claude Code's internal agents fire it too; use a matcher on the agent type.

Rewriting what a subagent returns through a PostToolUse hook on the Agent tool works for a foreground subagent, whose result arrives in tool_response with status "completed". A background subagent's Agent call returns as soon as the task moves to the background, with status: "async_launched" and no result to rewrite. For updatedToolOutput in general, "The value must match the tool's output shape", and for built-in tools "a value that doesn't match the tool's output schema is ignored and the original output is used."

On scope: hooks in a subagent's frontmatter "only run while that specific subagent is active and are cleaned up when it finishes", while session-wide hooks reach inside: "a PreToolUse hook in settings.json also runs before every tool a subagent uses." The Agent SDK's programmatic AgentDefinition type has no hooks field in either the Python or the TypeScript reference, so for subagents defined in code the hook goes in the session's hooks option, where the input's agent_id and agent_type "are populated when the hook fires inside a subagent" and let one callback apply a per-subagent rule.

Sourcescode.claude.com › hookscode.claude.com › sub-agentscode.claude.com › hookscode.claude.com › pythoncode.claude.com › typescriptfetched 2026-11-19

Quick Reference

FactValue
Official sample question 1The agent skips get_customer in 12% of cases; the keyed answer is a programmatic prerequisite that blocks lookup_order and process_refund until get_customer has returned a verified customer ID
Why the prompt options lose in sample question 1They "rely on probabilistic LLM compliance, which is insufficient when errors have financial consequences"
Why the routing classifier loses in sample question 1It "addresses tool availability rather than tool ordering"
Handoff fields the exam guide namesCustomer ID, root cause, refund amount, recommended action
Why the handoff must stand aloneThe human agent lacks access to the conversation transcript
Multi-concern requestDecompose into distinct items → investigate each in parallel using shared context → synthesise one unified resolution
Permission evaluation orderHooks → deny rules → ask rules → permission mode → allow rules → canUseTool callback
Deny rule strengthDenies the call even in bypassPermissions mode, and even when a hook returned allow
Hook allow resultDoes NOT skip the deny-rule and ask-rule steps — those still run
canUseTool — when it firesOnly when no earlier step resolves the call; calls approved by acceptEdits, bypassPermissions, or an allow rule skip it
Check that must run on every callUse a PreToolUse hook, not canUseTool — hooks are the first step and run for auto-approved calls too
PreToolUse hook deny strengthApplies even in bypassPermissions mode
Shape of a hook denialhookSpecificOutput with permissionDecision: "deny" and permissionDecisionReason; the reason is shown to Claude. {} allows the call unchanged
Several PreToolUse hooks disagreedeny > defer > ask > allow; matching hooks run in parallel, in no guaranteed order
A guard callback that throwsThe call goes ahead by default; set on_failure="block" (Python) or onFailure: "block" (TypeScript) on the matcher to block instead
MCP tool name in a hook matchermcp__<server>__<tool>; every tool from one server is mcp__<server>__.*
What hooks are documented forBlocking dangerous ops pre-execution, audit logging, input/output transformation, requiring human approval, tracking session lifecycle
Bare disallowed_tools entry (e.g. "Bash")Removes the tool definition from the request
Scoped disallowed_tools entry (e.g. "Bash(rm *)")Tool stays available; only matching calls are denied, in every mode
Forced tool_choice ({"type": "tool", "name": "..."})Makes one response start with that tool call; not a session-wide ordering guarantee; returns a 400 error on the newest models listed in the Deep Dive
SubagentStartCannot block the spawn; can add context to the subagent
SubagentStopdecision: "block" with a reason keeps the subagent working; cannot rewrite its output
Decision rule (from What You Need to Know)Financial / security / compliance = programmatic enforcement; formatting / style = prompt guidance is fine

Exam Traps

More wrong answers, and why each fails

The tempting answerWhy it failsWhat to choose instead
A gate that logs a warning and lets the call throughThe audit trail reads like enforcement while the money still movesRefuse the call; log as well if you want the record
A gate that raises an exception and stops the runThe refund is blocked, and so is the rest of the customer's conversation; the agent gets no chance to verify and retryReturn the refusal to the agent as a tool result
Give the human agent the transcript, or a link to itThe task statement assumes human agents who lack access to the transcript, and raw history would still leave them to work out the root cause and next stepPut the conclusions in the handoff itself

How This Is Tested

Items on this task statement describe a symptom and ask for the most effective change. The stem almost always tells you which idea it is testing.

What the stem saysThe answerThe wrong-answer pattern beside it
"In 12% of cases the agent skips verification…" — a measured rate on a rule that must always holdA programmatic prerequisite that blocks the downstream tools until the verifying tool has returned a verified resultA stronger system prompt; few-shot examples; a routing classifier
"A refund above $500 must never be issued autonomously"A PreToolUse hook that denies the call and redirects the agent to escalation (the mechanics are Task 1.5)A prompt rule with examples either side of the limit; a canUseTool check
"Escalated cases take 8 extra minutes because human agents re-interview the customer"A structured handoff carrying customer ID, root cause, amounts, actions already taken and a recommended actionTranscript access for the human; a free-text note
"A customer raises three issues; the agent answers one"Decompose into distinct items, investigate each in parallel using the shared customer context, synthesise one unified resolutionA separate conversation per issue; resolve the most urgent and ask the customer to come back; escalate the lot
"One of the three concerns needs a policy exception"Resolve the two the agent can, escalate only the third with a structured handoffEscalate the whole conversation
"Which change would most effectively address this?" with a deterministic requirement in the stemThe gate. Once the requirement is "must", no quality of prompt competes with itWhichever option improves the prompt most convincingly

Official sample question 1, option by option

Production data shows that in 12% of cases, your agent skips get_customer entirely and calls lookup_order using only the customer's stated name, occasionally leading to misidentified accounts and incorrect refunds. What change would most effectively address this reliability issue?

Read the stem for three facts before looking at the options. There is a measured rate (12%). The mistake is one of order: a required tool is skipped, not confused with another. And the consequence is financial ("incorrect refunds").

OptionVerdictWhy
A. "Add a programmatic prerequisite that blocks lookup_order and process_refund calls until get_customer has returned a verified customer ID."CorrectThe official explanation: "When a specific tool sequence is required for critical business logic (like verifying customer identity before processing refunds), programmatic enforcement provides deterministic guarantees that prompt-based approaches cannot." Note that it blocks both downstream tools, and that the condition is a verified customer ID returned, not a call made
B. "Enhance the system prompt to state that customer verification via get_customer is mandatory before any order operations."WrongIt would help, and it stays probabilistic. The explanation groups it with C: both "rely on probabilistic LLM compliance, which is insufficient when errors have financial consequences"
C. "Add few-shot examples showing the agent always calling get_customer first, even when customers volunteer order details."WrongSame reason as B. The detail about customers volunteering order details makes it sound targeted at the exact failure, which is what makes it tempting
D. "Implement a routing classifier that analyzes each request and enables only the subset of tools appropriate for that request type."WrongIt works on the wrong axis. The explanation: it "addresses tool availability rather than tool ordering, which is not the actual problem". A refund request still gets all three tools, and the agent can still skip the first

Two habits carry over to every variant of this item. First, sort the options into "changes the odds" and "removes the possibility" before judging their detail; B and C are in the first group however well they are written. Second, when an option adds a new component (a classifier, a router, a reviewing agent), ask which property it controls and whether that is the property the stem says is broken.

Practice Scenario

The gate you added holds: process_refund never runs until get_customer has returned a verified customer ID. Three refunds last month still went astray, each issued against an order belonging to a different account from the verified caller. The system prompt does tell the agent to confirm the order belongs to that caller. What change would most effectively address this?

Practice Questions

Exam simulator

Question 1 of 13

Scenario · Customer Support Resolution Agent

Your gate blocks process_refund until get_customer has been called in the conversation. A fraud review finds refunds that passed it anyway: the agent called get_customer with a name the customer gave, got "no matching customer", then refunded against an order number the customer typed. What change would most effectively close this gap?

Sources