Every task here asks one question: who decides what happens next, the model or your code?
The model decides (adaptable, non-deterministic)
Your code decides (guaranteed, inflexible)
The agentic loop (1.1)
Prompt chaining (1.6)
Coordinator routing and delegation (1.2)
Programmatic prerequisite gates (1.4)
Adaptive decomposition (1.6)
Hooks (1.5)
Subagent selection by description (1.3)
Fixed pipelines
Move a decision to the code side exactly when one violation has a cost you cannot accept: money moved, identity unverified, a required order, a policy breach.
Leave everything else with the model; that side adapts, the code side does not.
1.1 — Agentic Loops
stop_reason
Handling
tool_use
Run the tool(s), return result(s), continue loop
end_turn
Use the response — loop terminates
pause_turn
Server-tool loop hit its limit (default 10 iterations per request): append the response unchanged, re-request with the same tools and no new user message — NOT done
max_tokens
Raise max_tokens or continue the response
stop_sequence
Read stop_sequence field to see which fired
refusal
Read stop_details, retry on a fallback model (arrives as HTTP 200, not an error)
model_context_window_exceeded
Treat as truncated
Loop exits on any value other than tool_use. Exit ≠ task complete.
Streaming: stop_reason is null in message_start, set in message_delta.
A tool_use pass appends two messages: the assistant response unchanged (it holds the tool_use ids), then one user message with every tool_result.
tool_result lives in a user message; must immediately follow the tool_use message; all tool_result blocks before any text.
Parallel calls: one tool_result per tool_use, all in one user message. Skipped call still needs is_error: true.
Failed or invalid call (e.g. missing parameter) → tool_result with is_error: true naming the problem; Claude can call again, so limit retries. strict: true removes invalid calls.
Anti-patterns: NL parsing of "I'm done"; iteration caps as primary stop mechanism (safety net only — SDK: max_turns); checking content[0].type == "text" (text can accompany tool_use).
Cap reached → raise or alert, never return the last response as the answer. SDK reports it as result subtypeerror_max_turns with no result; subtype (success, error_max_turns, error_max_budget_usd, error_during_execution, error_max_structured_output_retries) is how the SDK says why the loop ended.
A tool call such as escalate_to_human is a business event, not a stop signal: stop_reason is still tool_use, so return the result and let the model reach end_turn.
One step needs a guarantee → gate that step, keep the loop model-driven (not a decision tree).
Exam: tool_choice: "any" forces a tool call and is the wrong fix for termination. Current docs: any/tool return a 400 on Fable 5.2, Mythos 5.2, Opus 5.5, Sonnet 5.5, Fable 5.1, Mythos 5.1.
All inter-subagent comms flow through the coordinator → observability, consistent error handling, controlled information flow. (Current product also allows nested spawning and SendMessage between named agents; exam answer is still "through the coordinator".)
Isolation: no inherited history, no shared memory between invocations — the coordinator writes what each subagent needs into its prompt.
Token cost: agents ≈ 4x chat; multi-agent ≈ 15x chat. Only justified when task value clears that premium.
Two parallelization levels: lead spins 3-5 subagents in parallel; each subagent runs 3+ tools in parallel.
Narrow decomposition failure: coordinator never assigns a whole category → no subagent can cover it. Root cause = coordinator, not subagents. Incomplete report → read the coordinator's logged subtasks first.
Duplicated-work failure: vague per-subagent task descriptions → same topic researched twice, another missed. Fix: objective + output format + source guidance + boundaries per subagent.
Partition scope by subtopic or by source type, boundaries stated in each brief.
Refinement loop: evaluate synthesis for gaps → re-delegate the gaps only → re-synthesise; stop on sufficient coverage or a round limit, then annotate what is still missing.
Latency fix the exam accepts = a scoped cross-role tool for the frequent simple case (verify_fact); complex cases still go through the coordinator. Never subagent-to-subagent calls.
Coordinator briefs state goals and quality criteria, not step-by-step procedure.
Poor fit: shared-context/high-dependency domains, most coding tasks, real-time cross-agent coordination.
1.3 — Subagent Invocation & Context Passing
Exam answer: allowedToolsmust include Task/Agent for the coordinator to spawn subagents. Current docs: allowedTools only pre-approves; Agent runs "whether or not you list" it, and disallowedTools is what removes a tool.
Coordinator does the work itself → check, in order: spawning tool in allowedTools → the subagent's description → whether the prompt names the subagent.
AgentDefinition: description (req), prompt (req, not systemPrompt), tools (opt — omit = all tools available to subagents), model (opt — fable/opus/sonnet/haiku/inherit/full ID; omitted = by default the model of the conversation that starts it), plus other optional fields (disallowedTools, skills, maxTurns, …); Python keeps these camelCase.
description decides whether it is picked · prompt how it behaves · tools what it can do.
3 ways to define: programmatic (agents option) > filesystem (.claude/agents/) > built-in general-purpose. Programmatic wins name clashes.
Claude auto-selects a subagent from its description; can also be named explicitly.
Context isolation: only the Agent tool's prompt string crosses parent→subagent. No history, no system prompt, nothing else unless written into that prompt. Intermediate tool calls stay inside the subagent — only the final message returns. A non-fork subagent also starts with its own system prompt, tool definitions and project CLAUDE.md; a forked subagent (subagent_type: "fork") inherits the whole conversation.
Parallel subagents finish in time of the slowest, not the sum — spawn via multiple Agent/Task calls in one coordinator response (exam answer; current docs: spawns run in the background by default, status: "async_launched", report in a later turn).
Default limits: depth 3 layers, 20 concurrent subagents, no spend cap unless max_budget_usd is set.
Structured context passing: separate content (claim) from metadata (source_url, document_name, page_number, publication date, evidence excerpt) or downstream agents can't attribute claims.
fork_session/forkSession (bool, default false): forks resume to a new session ID; copies history to that point; original ID/history unchanged → two independent sessions. Branches the conversation, not the filesystem.
Three things called "fork": forked session (copy of saved history) · forked subagent (whole parent conversation) · skill context: fork (skill content only, no history).
Deny rule blocks even under bypassPermissions. Hook allow does NOT skip deny/ask rules.
canUseTool runs only when no earlier step resolves the call — skipped by acceptEdits/bypassPermissions/allow rules. For a check that must run on every call → use a PreToolUse hook instead (runs before every other step; deny applies even under bypassPermissions).
disallowedTools: ["Bash"] removes the tool entirely. disallowedTools: ["Bash(rm *)"] keeps it visible, denies only matching calls, in every mode.
Sample Q1: agent skips get_customer in 12% of cases → programmatic prerequisite blocking lookup_order and process_refund until a verified customer ID. Prompt/few-shot options only lower a rate; routing classifier fixes availability, not ordering.
Tool selection → descriptions; tool ordering → gate. Forced tool_choice = this tool first in one response; gate = an order for the whole session.
A gate's refusal goes back to the agent as a tool result naming the missing prerequisite and the way out (not a bare "denied", a logged warning, or an exception that ends the run). Act on the ID the gate holds, not one the model supplies.
A crashing guard callback fails open unless the matcher sets on_failure="block" (onFailure: "block" in TypeScript).
Handoff summary — the guide names four fields: customer ID, root cause, refund amount, recommended action; a short issue summary and the actions already taken are useful additions. Human agent has NO transcript access.
Multi-concern requests: decompose → investigate in parallel with shared context → synthesise one unified resolution.
Partial escalation: one concern stuck → resolve the others, escalate only that one with a structured handoff, tell the customer which is which.
TypeScript-only: every other event (23 today), including SessionStart and SessionEnd; in Python those two exist only as shell command hooks in a settings file.
HookMatcher.matcher tests against the tool name (e.g. "Write|Edit", or regex ^mcp__); no matcher = fires for every event of that type. MCP tools are named mcp__<server>__<tool> — a bare process_refund matches nothing. Matchers see names only, not arguments (check tool_input in the callback).
updatedInput + allow → auto-approves the rewritten call.
updatedInput alone (no decision) → still applies, flows through normal evaluation. With defer it is ignored.
updatedInput sits inside hookSpecificOutput and replaces the whole input (include unchanged fields).
permissionDecisionReason is read by the model on deny, the user on ask, the debug log on allow/defer.
defer → tool does not run; turn ends with stop_reasontool_deferred, resume later (only -p runs, single tool call).
Selection rule: absolute rule → deny with a reason naming the alternative · a person can approve while the agent waits → ask · approval arrives later, out of band → defer · arguments mechanically wrong or need scoping → rewrite (updatedInput, usually with allow). Never clamp a financial value silently (capping a $900 refund to $500 instead of escalating is wrong).
PostToolUse output: additionalContext (appends alongside original) vs updatedToolOutput (replaces result before Claude sees it — right choice for normalisation; built-in and MCP tools, both SDKs). Fires only after a successful call; failures fire PostToolUseFailure, which cannot rewrite the result.
Decision priority:deny > defer > ask > allow. One hook's deny blocks the tool call; matching hooks run in parallel, so no hook may rely on another having run.
{} = allow unchanged. Every hook output can carry systemMessage (shown to the user, not the model) and continue/continue_ (false stops the run but does not block the pending PreToolUse call).
A callback that throws lets the action go ahead unless the matcher sets on_failure="block".
can_use_tool is skipped for pre-approved calls → not a compliance gate; use PreToolUse.
PostToolUse = after exec (normalise data). PreToolUse = before exec (block/redirect). Using PostToolUse to block is always wrong — the action already happened.
Distinct categories handled differently (cheap vs capable model)
Independent subtasks in parallel
Parallelization — sectioning
e.g. guardrail screening separate from main response
Same task run N times
Parallelization — voting
Diverse outputs / confidence (multiple vuln reviews). Not a consensus filter: 2-of-3 agreement over whole-PR runs is the wrong option D of sample Q12
Generate + critique loop
Evaluator-optimizer
Clear eval criteria, refinement adds value (translation)
Classifying question: can the subtasks be listed before the work starts? Yes → prompt chaining. No → dynamic decomposition.
Listable but findings may change the approach → hybrid: plan adaptively, then execute as a chain.
A plan is adaptive only with a feedback edge (discoveries change the remaining plan); planned once and never revised = a fixed pipeline.
Prompt chaining trades latency for accuracy; supports gates (programmatic checks between steps).
Adaptive decomposition needs ground truth from the environment each step, plus a stopping condition (safety bound, not completion signal).
Attention dilution: too many items in one pass → inconsistent depth, same pattern flagged in one file/approved in another. NOT fixed by a bigger model or context window — fix is multi-pass: per-item local passes + a separate cross-item integration pass.
Per-file pass asks "within this file alone, what is wrong?"; integration pass asks "across these files, what breaks?" Both are needed.
Attention dilution (too many targets in one pass → split the passes) ≠ context degradation (too many tokens accumulated → /compact, scratchpad, delegate).
Batching without a cross-file integration pass still misses cross-cutting issues.
1.7 — Session State, Resumption & Forking
Storage: ~/.claude/projects/<encoded-cwd>/*.jsonl (cwd with non-alphanumerics → -).
--resume <id> searches the current project and its worktrees, then every other project on the machine (v2.1.223+); names resolve across the current repository; --continue is tied to the current directory.
Resume restores: full history (tool calls + results), model, agent, permission mode (with conditions), goals, unexpired scheduled tasks. On a terminal resume plan comes back as plan mode; bypassPermissions does not and must be enabled again at launch. Launch flags (--mcp-config, --add-dir, --settings) are not restored.
--continue: most recent session in cwd, no ID tracking; run interactively it skips claude -p and Agent SDK sessions. --resume <id|name>: specific session, ID must be tracked (capture via --output-format json → .session_id).
Naming: --name/-n at start, /rename mid-session, or Ctrl+R in the picker; then --resume <name>.
Fork = new session ID + copy of history to the fork point; original ID/history unchanged → two independently resumable sessions, separate picker rows. Branches the conversation, not the working tree.
Sessions persist conversation only, not files. File revert = checkpointing (separate system; one checkpoint per prompt that starts a turn, 100 most recent kept; a file that only Bash commands changed is not tracked; most subagent edits are not tracked).
Stale context problem: resuming after file edits leaves old tool results in history — agent gives contradictory advice unless told which files changed; a re-read adds the new contents without removing the old.
Fix: context mostly valid and changes listable → resume and name the changed files (targeted re-analysis). Tool results stale as a body → fresh session + injected structured summary + list of changed files. fork_session fixes neither (it inherits the same stale history).
Summary to inject: established findings, files changed since, open questions, next step — conclusions, not raw tool output.
Decision rule: prior context still or mostly valid → resume (declare what changed). Comparing divergent approaches → fork once per approach. Tool results stale/context degraded → fresh start + summary.