Skip to content
Domain 1Task 1.4

Workflow Enforcement and Handoff

Learn this interactively

What You Need to Know

Some agent workflows have steps that must run in a set order. Prompt-based guidance sets that order with a system prompt instruction, such as "Always verify the customer's identity before processing a refund". Programmatic enforcement sets it in code: hooks, prerequisite gates or code-level checks that block downstream tools (the tools that run later) until their prerequisites complete. A prerequisite gate is a programmatic check that blocks a tool from executing until a prior condition is met. Task Statement 1.4 makes a strict distinction between the two.

This lesson uses one made-up example throughout: a tree surgeon whose agent answers client enquiries and books work. Before the agent books a tree felling, it must check whether the tree is protected. Before the agent refunds a deposit, it must verify the client's identity. The agent also formats quote emails, where a mistake costs nothing.

Prompt Guidance Versus Programmatic Enforcement

A prompt instruction works most of the time, perhaps in 90-95% of cases. It still has a non-zero failure rate, because the model is probabilistic. Sometimes the model skips steps, reorders them or reads the instruction loosely. A stronger system prompt, firmer instructions and few-shot examples (examples that show the correct workflow) all improve accuracy. None of them gives a deterministic guarantee. For low-stakes operations, that failure rate is fine.

A gate works every time. It is code, not a prompt instruction, so it is deterministic. Whatever the model decides, the gate prevents the wrong execution order. A prompt can tell the tree surgeon's agent to check protection first, but the agent could still skip that check on an occasional job. The agent cannot skip a gate on the booking tool.

Which Operations Need a Gate

The choice depends on what a single failure costs.

  • Financial operations (refunds, transfers, payments): programmatic enforcement. A single unverified refund to the wrong account is a financial loss.
  • Security operations (identity verification, access control): programmatic enforcement. A single bypass of identity verification is a security breach.
  • Compliance operations (AML (anti-money laundering) checks, regulatory requirements): programmatic enforcement. A single missed compliance check can result in legal penalties.
  • Low-stakes operations (formatting preferences, style guidelines, output ordering): prompt-based guidance is acceptable. A formatting inconsistency is not a business risk.

For the tree surgeon, the deposit refund is financial, the identity check is security and the protection check is compliance. All three have gates. Quote formatting is low stakes, so a prompt instruction is enough.

Key Concept

Prompt-based guidance is probabilistic. Programmatic enforcement is deterministic. The decision rule: if a single failure would cause financial loss, a security breach or a compliance violation, use programmatic enforcement.

How a Prerequisite Gate Works

Consider an agent with get_customer, lookup_order and process_refund tools. A gate on process_refund works like this.

  1. The gate checks whether get_customer has returned a verified customer ID for this session.
  2. If yes, process_refund executes normally.
  3. If no, process_refund returns an error. The error says that the customer's identity is not verified, and it tells the model to call get_customer first.

The model cannot bypass the gate by deciding to skip verification. The gate blocks even a direct call to process_refund, and the error forces the model to verify identity first.

Production data on such an agent shows that it processes refunds without verifying account ownership in 8% of cases. Its system prompt instructs: "Always verify the customer's identity before processing any refund." The prompt works 92% of the time and fails 8% of the time. That 8% has already resulted in refunds processed on wrong accounts. A refund is a financial operation with real monetary consequences.

The fix is the programmatic prerequisite gate above. The gate prevents the incorrect execution order. In this way, it eliminates the 8% failure rate entirely, without improving the prompt at all.

The tree surgeon's booking tool works the same way. When the session has no protection check result, the booking tool returns an error that names the check. The agent runs the check, then retries the booking.

Subagent Lifecycle Hooks: SubagentStart and SubagentStop

The Claude Agent SDK provides lifecycle hook events to manage subagents. They complement the PreToolUse and PostToolUse hooks covered in Task Statement 1.5. They are useful background, but the exam does not test them. Suppose that the tree surgeon's coordinator spawns a quote-drafting subagent. The coordinator is the agent that spawns subagents and receives their results.

SubagentStart fires when the coordinator spawns a subagent via the Task tool. Claude Code v2.1.63 renamed this tool to Agent. SubagentStart receives the subagent's type and id, and it cannot block the spawn. It can add context. Return additionalContext in its JSON output, and that string is placed in the subagent's context before its first prompt. This is the documented way to give a newly spawned subagent an instruction that applies to all its work. To enforce rules on the spawn itself, attach a PreToolUse hook to the Agent tool. Examples of such rules are rate limits or a check that the coordinator passed required context. That hook can deny or rewrite the outgoing invocation before the subagent starts.

SubagentStop fires when a subagent finishes and returns its results to the coordinator. It receives the subagent's id and final message, so it can validate output and log completion to monitor performance. Validation can fail, for example because the output does not conform to the expected schema. The hook then exits with code 2, which prevents the subagent from stopping and makes it continue its work. Exit code 2, or a top-level decision: "block" with a reason, keeps the subagent running. A quote draft that is missing a required field would make its subagent continue its work.

SubagentStop does not transform the returned output. The hooks reference documents no field on any event that rewrites a tool result in place. The coordinator reshapes the output afterwards.

SubagentStartSubagentStop
Fireswhen the coordinator spawns a subagent via Task (Agent)when the subagent finishes and returns its result
Receivesthe subagent's type and idthe subagent's id and its final message
Can blocknoyes: exit code 2 sends the subagent back to work
Can add contextyes: additionalContext goes into the subagent's context before its first promptno
Can rewrite the resultnono
Typical usean audit log of spawns, or a standing instruction for every subagentvalidate the result against a schema before the coordinator acts on it
To enforce insteada PreToolUse hook on the Agent tool, which can deny or rewrite the spawna PostToolUse hook on the Agent tool, which acts on the returned result

You configure both events like any other hook event, in settings.json or in a subagent's frontmatter (the block of settings at the top of the subagent's file):

json
{
  "hooks": {
    "SubagentStart": [
      { "hooks": [{ "type": "command", "command": "echo \"subagent started $(date)\" >> .claude/spawns.log" }] }
    ],
    "SubagentStop": [
      { "hooks": [{ "type": "command", "command": ".claude/hooks/validate-subagent-output.sh" }] }
    ]
  }
}

The first script only appends a line. To add context instead, print JSON with an additionalContext field. The second script reads the result on stdin and exits 2 if the schema check fails. Exit code 2 is one of SubagentStop's two ways to keep the subagent running.

Subagents can also define their own hooks in their frontmatter. The frontmatter supports all hook events, including PreToolUse and PostToolUse. These hooks are scoped to the component's lifetime. So they only intercept tool calls made by that subagent, not by the coordinator or other subagents. This lets you enforce a separate policy for each subagent. A billing subagent might have a PreToolUse hook that blocks refunds above a threshold, while a technical support subagent has no such restriction.

Stop hooks in a subagent's frontmatter are automatically converted to SubagentStop events, because SubagentStop is the event that fires when a subagent completes. You can therefore define cleanup or validation logic in the subagent's own configuration and rely on it to run when the subagent completes.

Key Concept

SubagentStart observes spawning, can add context and cannot block. SubagentStop uses exit code 2 to block completion. Neither rewrites subagent output. Subagents can define hooks in their own frontmatter, scoped to their execution. Stop hooks there auto-convert to SubagentStop.

Multi-Concern Request Handling

Customers often put several issues in one request, such as "I want to return my order, update my shipping address, and ask about my loyalty points". Handle it in three steps.

  1. Decompose the request into distinct items (return, address update, loyalty enquiry).
  2. Investigate each in parallel using shared context (the customer's account information is relevant to all three).
  3. Synthesise a unified resolution that addresses all items in a single response.

It is wrong to handle the items sequentially in separate conversations. It is also wrong to address only the first item and forget the rest. A tree surgeon's client might ask to move a felling date, query an invoice and ask about stump grinding. The agent separates the three requests, checks each against the client's account and sends one reply.

Structured Handoff Protocols

When an agent cannot resolve an issue and must escalate to a human agent, the handoff must follow a structured protocol. The human agent does not have access to the conversation transcript. They cannot scroll through the chat history. The handoff summary is the only information they receive, so it must be self-contained. It must include these fields.

  • Customer ID, so the human agent can open the account.
  • Conversation summary: what the customer asked for and what the agent has attempted.
  • Root cause analysis: the agent's assessment of the underlying issue.
  • Refund amount (if applicable): the specific financial figure, not a vague reference.
  • Recommended action: what the agent believes the human agent should do.

If the summary is incomplete, the human agent must ask the customer to repeat everything. That is a poor experience. When the tree surgeon's agent cannot resolve a disputed charge, its handoff contains all five fields, including the exact refund figure.

In the exam

The exam tests the distinction between prompt-based guidance and programmatic enforcement repeatedly. It uses one decision rule across multiple scenarios. A wrong answer on high-stakes scenarios will cost you marks. When the scenario involves money, security or compliance, the answer is always programmatic enforcement.

Exam Trap

The exam consistently presents "add stronger instructions to the system prompt" or "include few-shot examples showing the correct workflow" as wrong options for high-stakes scenarios. Reject them. They improve probability but do not eliminate the failure rate. For financial, security, and compliance operations, only programmatic enforcement is correct.

The exam also tests how agents should handle compound requests.

Beyond the guide

Task Statement 1.4 covers programmatic enforcement, prerequisite gates and structured handoff. The guide's appendix scopes Agent SDK hooks to PostToolUse and tool-call interception. The subagent lifecycle events above are background reading, not exam content. Verified against the hooks reference on 16 September 2026.

Exam Traps

Exam Trap

Enhanced system prompt instructions or few-shot examples as the fix for high-stakes compliance failures

A stronger prompt and few-shot examples both improve accuracy, but the model is still probabilistic, so the failure rate stays above zero. For financial, security and compliance operations, use programmatic enforcement, which gives a deterministic guarantee.

Exam Trap

Handling a multi-concern request one item at a time, across separate replies or follow-up interactions

Sequential handling gives the customer several replies and risks a later concern being lost. Decompose the request into distinct items, investigate each in parallel using shared context such as the customer's account, then send one unified resolution.

Exam Trap

Routing classifiers proposed to fix per-agent compliance issues

A routing classifier determines which agent handles a request. The compliance failure occurs within the agent execution sequence, not at the routing level. Add a prerequisite gate that blocks the downstream tool until the prerequisite step has completed.

Exam Trap

Handoff summaries that omit critical fields like customer ID or recommended action

Human agents do not have access to the conversation transcript. The handoff summary must be self-contained with all required fields: customer ID, conversation summary, root cause analysis, refund amount if applicable, and recommended action.

Practice Scenario

Production data shows that in 8% of cases, a customer support agent processes refunds without verifying account ownership, occasionally leading to refunds on wrong accounts. The system prompt already tells the agent to check ownership first, and the company needs that order to hold on every refund. What is the most appropriate fix?

Build Exercise

Build Exercise

Build a Prerequisite Gate for Financial Operations

Difficulty
60 minutes

What you'll learn

  • Why programmatic enforcement is required for financial operations instead of prompt-based guidance
  • How prerequisite gates block tool execution until preconditions are met
  • The difference between the 8% prompt failure rate and 0% gate failure rate
  • How to implement structured handoff protocols with all required fields
  • How multi-concern requests should be decomposed and handled in parallel
  1. Create a customer support agent with three tools: get_customer (returns customer ID and verification status), lookup_order (returns order details), and process_refund (processes a refund for a given amount)

    Why: These three tools create the exact scenario the exam uses for the 8% failure rate question. The workflow dependency between get_customer and process_refund is where programmatic enforcement becomes essential.

    You should see: Three tool definitions with proper JSON Schema input_schema. get_customer accepts a name or email, lookup_order accepts an order ID, and process_refund accepts a customer ID and amount.

  2. Implement a programmatic prerequisite gate that blocks process_refund from executing until get_customer has returned a verified customer ID in the current session

    Why: This is the core exam concept: prompt instructions work 92% of the time but fail 8%. A prerequisite gate provides 100% deterministic enforcement. The exam always rejects prompt-based solutions for financial operations.

    You should see: A session-level state tracker that records whether get_customer has returned a verified customer. The process_refund handler checks this state before executing and returns an error if verification has not occurred.

  3. Test that the gate works by prompting the agent to skip verification and process a refund directly — verify the gate blocks the attempt

    Why: Testing the bypass attempt demonstrates the difference between prompt-based and programmatic enforcement. Even when the model decides to skip verification, the gate blocks the action — which is the entire point of deterministic enforcement.

    You should see: The agent attempts to call process_refund without prior verification. The gate returns a blocked error message. The agent then calls get_customer before retrying the refund successfully.

  4. Implement a structured handoff protocol: when the agent cannot resolve an issue, it compiles a self-contained summary with customer ID, conversation summary, root cause analysis, refund amount, and recommended action

    Why: Human agents do NOT have access to the conversation transcript. The handoff summary is the only information they receive. The exam tests whether you include all five required fields: customer ID, summary, root cause, amount, and recommended action.

    You should see: A handoff function that produces a structured object with all five fields populated. No field should be empty or contain placeholder text.

  5. Test the handoff with a multi-concern request (return plus billing dispute plus account update) and verify the handoff summary is complete and self-contained

    Why: Multi-concern requests test whether the agent decomposes the request into distinct items and addresses all of them. The exam expects decomposition, parallel investigation, and unified resolution — not sequential handling or forgetting items.

    You should see: The agent identifies all three concerns, investigates each one, and produces a handoff summary that covers all three issues with specific details for each. No concern is omitted.

Sources