Working with Claude Code Subagents
Learning objectives
By the end of this chapter, you will be able to:
- Explain what a Claude Code subagent is — a specialized assistant with its own system prompt, its own isolated context window, and selective tool access — and how it differs from the main agent: it does not see the conversation history and returns only a single condensed summary.
- Create a subagent with the `/agents` command (guided / 'generate with Claude' / manual) and read or author its Markdown definition: the required `name` and `description`, the `tools` allowlist (omit to inherit all), `model` (including `inherit`), and where it lives — `.claude/agents/` (project) versus `~/.claude/agents/` (user).
- Invoke a subagent several ways — automatic delegation driven by the `description`, naming it in natural language, `@`-mentioning it, or running a whole session as it (`claude --agent <name>` or the `agent` setting; `--agents` JSON for session-only definitions) — and explain why Claude runs multiple subagents sequentially unless the prompt makes their independence explicit.
- Explain why subagents keep the main context lean — the subagent starts in a fresh, isolated window (it does not see the prior conversation, invoked skills, or files already read), Claude hands it a delegation message describing the task, and it returns one condensed summary — and connect this to finite context limits, context pollution, and the model's attention budget.
- Shape a subagent through its two levers — the `description` (which controls when it is invoked and how the main agent prompts it) and the system-prompt body (its internal logic) — apply least privilege to its `tools` (avoiding tool pollution), and recognize the security risk of an untrusted subagent definition.
- Describe how concurrent subagents scale exploration through the Infinite Agentic Loop pattern — one high-order ('meta') prompt that fans out to parallel subagents via the Agent tool to generate many variations from a single spec for human selection — and judge when this multi-agent approach is worth its token cost.
Before we start — agents, subagents, context windows, and "meta" prompts
Skim this if you're already comfortable with what a subagent is, what a context window is and why it fills up, the difference between a system prompt and a user prompt, and what people mean by a "prompt that writes prompts." If any of that is fuzzy, read it first — the whole chapter rests on these ideas.
The main agent. Everything in Chapters 1–6 was one Claude Code agent: the session you type into. It reads files, runs commands, edits code, and holds the whole conversation in its memory.
A subagent is a second, specialized assistant that the main agent can hand a single, well-scoped job to. Three things make it a subagent rather than just "more prompting":
- It has its own system prompt — a set of standing instructions you write that define its personality, its job, and how it works.
- It runs in its own context window, separate from your main conversation. It does not see your chat history or the files you've already opened; it sees only the one prompt the main agent hands it. When it finishes, it returns one condensed summary — not its whole transcript.
- It has selective tool access — you decide which tools it may use (read files, search, run shell commands, call MCP servers), and it gets only those.
A context window is the model's working memory: the maximum number of tokens (chunks of text — roughly ¾ of a word each) it can consider at once. Models have a finite limit — commonly around 200,000 tokens today, larger on some models. Every message, file, and tool result you add eats into that budget. Two bad things happen as it fills: you eventually hit the ceiling (and must /compact or /clear), and — more subtly — quality degrades well before the ceiling, because the model has a limited attention budget and starts to lose track of what matters. This degradation is the core problem subagents solve.
System prompt vs user prompt. A user prompt is a single request ("review this file"). A system prompt is the standing instruction set that frames every request ("you are a meticulous code reviewer; always group findings by severity"). A subagent's definition is a system prompt — it shapes how the subagent behaves on every job it's given. That distinction matters in this chapter because you tune a subagent by editing its system prompt, not by re-typing requests.
Concurrent / parallel. Two pieces of work run concurrently (in parallel) when they happen at the same time rather than one-after-another (sequentially). Subagents can run in parallel — but, as you'll see, Claude only does that when it's confident the jobs don't depend on each other.
A "meta" or high-order prompt. Most prompts ask for an answer. A high-order prompt (the chapter's capstone) asks the model to write more prompts — to read one specification and dynamically generate the individual prompts for a whole wave of subagents. If you've met "higher-order functions" (functions that take or return functions), this is the same idea with prompts.
Where this sits relative to Chapter 6. Chapter 6 ended by naming three senses of "multiple agents": separate terminal instances (what it demonstrated), subagents (deferred to "the next chapter"), and agent teams. This is that next chapter. A subagent is in-session delegation: one conversation, one specialized helper, its own context, a summary back.
How to read this chapter. Each numbered section ends with an > Analogy — … box that restates the idea in plain language. Lean on them or skim them as you like.
Why this chapter matters
A single Claude Code session has one context window, and that window is the bottleneck on everything ambitious you try to do. Point Claude at a big task — explore an unfamiliar codebase, review a sprawling diff, research five libraries — and the useful work (the answer you wanted) arrives buried under thousands of tokens of search results, file dumps, and logs you'll never read again. Those tokens don't just risk hitting the ceiling; they crowd the model's attention and make it worse at the very task you care about. As Anthropic's context-engineering guidance puts it, context must be treated as "a finite resource with diminishing marginal returns."
Subagents are the structural fix. Instead of doing the messy work in your main conversation, the main agent delegates it to a specialist that works in a separate context window and hands back only the conclusion. Your main thread stays lean; the specialist does the heavy reading in a room of its own. That single move — context isolation — buys two things at once: your conversation stays sharp for longer, and because each specialist has its own window, you can run several of them in parallel to explore more than one idea at a time.
This chapter builds that up in order. First, what a subagent is and the file that defines it. Then how you create, invoke, and shape one — including the security implications of the very flexibility that makes them powerful. Finally, the capstone: spinning up many subagents at once with the community's Infinite Agentic Loop pattern to generate competing implementations and pick the best. The honest counterweight runs throughout — this power costs tokens, and you'll learn when it's worth spending them.
Lesson
1. What a subagent is — and the file that defines it
A subagent is a specialized assistant Claude Code can delegate a task to. The official documentation's framing is precise about when to reach for one: use a subagent "when a side task would flood your main conversation with search results, logs, or file contents you won't reference again" — the subagent does that work in its own context and returns only the summary. Each one "runs in its own context window with a custom system prompt, specific tool access, and independent permissions."
Three properties define every subagent:
- Its own system prompt. You write it, and you fully control it — what the agent does, what it may do, and how. This is the source of its specialization.
- Its own, isolated context window. A freshly-spawned subagent "does not see your conversation history, the skills you've already invoked, or the files Claude has already read." Claude hands it a delegation message describing the task, and it works from there in a clean window — so the tokens it burns are not counted against your main conversation. (Its startup context isn't literally empty — exactly what loads is in §4 — and a forked subagent is the exception that inherits the parent conversation.)
- Selective tool access. You grant only the tools the job needs. A code-reviewer needs to read files and search — it has no business writing files or running arbitrary shell commands. Restricting it to read-only tools follows the principle of least privilege: give a component just enough to do its job and nothing more. (Tool access spans both Claude Code's native tools and any integrations exposed through MCP servers. Skills — introduced in Chapter 3 and explored in depth in Chapter 9 — sit at a different layer: they package capabilities rather than grant raw tool permissions.)
Subagents are reusable: define one once, then use it across projects and share it with your team. And they are defined as plain Markdown files with a YAML frontmatter block — the same kind of file-based configuration Claude Code uses elsewhere. Here is a clean, current example:
---
name: code-reviewer
description: Reviews code for quality, security, and convention violations. Use after any code change.
tools: Read, Grep, Glob, Bash
model: inherit
---
You are a meticulous code reviewer. When invoked:
1. Run `git diff --staged` and `git diff` to capture all pending changes,
and read the surrounding code so you understand how they fit in.
2. Use Grep/Glob to find every consumer of changed functions, types, or
exports, and flag call sites that need updating.
3. Report findings grouped by severity. For each: the file:line, a
one-sentence issue, the impact if ignored, and a concrete fix.
The two halves do different jobs. The frontmatter is configuration; the body below the --- becomes the subagent's system prompt. Importantly, the subagent runs on its own system prompt (plus basic environment details like the working directory) — not Claude Code's full main system prompt. The only fields that are required are name and description; everything else is optional:
name— lowercase-with-hyphens; how you and Claude refer to the agent.description— the single most important field. It tells the main agent when to delegate to this subagent. Write it well and delegation "just works."tools— a comma-separated allowlist. Omit it and the subagent inherits every tool the main conversation has. List specific tools and it is restricted to exactly those. (A companion field,disallowedTools, is a denylist for subtracting tools.) A subtle but important point: for subagents,toolsgenuinely restricts capability — unlike a Skill'sallowed-tools, which only pre-approves tools without blocking the rest.model—sonnet,opus,haiku,fable, a full model ID, orinherit(use the main conversation's model). If you omit it, it defaults toinherit. This is where you can route cheap, high-volume work to a fast model like Haiku and keep an expensive model for the orchestration.
The frontmatter supports many more fields than the book lists — among them color, permissionMode, skills (skills to preload), mcpServers, memory, and isolation: worktree (run the subagent in its own throwaway git checkout so parallel edits can't collide — the same worktree isolation Chapter 6 introduced, here built into the subagent itself). Check code.claude.com/docs/en/sub-agents for the current, full schema; the set grows between releases.
Finally, where the file lives sets its scope — and it's the same hierarchy Claude Code uses for other config:
.claude/agents/ # project scope — committed to the repo, shared with the team
~/.claude/agents/ # user scope — available across all your projects
(Beyond these two, organization-managed settings and plugins can also supply subagents; project files win over user files when names collide. The two directories above are the ones you'll create yourself.)
Analogy — the specialist with a sealed brief A subagent is a specialist you keep on call — a translator, say. You don't sit them in on your entire day of meetings; you hand them one document with a short brief ("translate this contract, flag anything ambiguous"), they go to their own office to work, and they come back with the finished translation and a note. They never saw the rest of your day, and your desk never filled up with their scratch paper. The Markdown file is their job card: their name, when to call them, and which tools they're issued.
2. Configuring your first subagent
The command that manages subagents is /agents. Run it and Claude opens a panel; on a fresh project you'll see "no agents found" except for the built-in agents Claude Code ships with (a general-purpose agent, plus read-only helpers like Explore and Plan). From here you choose a scope — project (so the config can be committed and shared) or user — and a creation method:
- Generate with Claude — describe what you want in plain English and let Claude write the definition. The simplest path.
- Manual configuration — write the Markdown file yourself.
The book walks through generate-with-Claude. You describe the agent and, crucially, when it should fire — a keyword trigger to bake into the description:
A funny, senior staff software engineer that reviews the code provided to
them. Use this agent when the input looks like "funny review".
Claude turns that into a full configuration: a system prompt (here, an elaborate "roast the code with love, using memes and movie quotes" persona), a tool selection, a model, and a color. You're walked through each choice. Tool selection is the step that matters most: for a code-review agent you keep read-only tools and leave Edit and execution tools off — there's no reason a reviewer should be able to write files or run shell commands. Model selection offers Sonnet (balanced — the book's pick), Opus (most capable), Haiku (fast and cheap), or Inherit from parent. The result is saved as a file like code-comedy-carl.md:
---
name: code-comedy-carl
description: >
Use this agent when you want a humorous, entertaining code review that
combines genuine technical feedback with comedy. Activate when users
request "funny review", "roast my code", or mention Carl / CodeComedy Carl.
tools: Glob, Grep, Read, LS, NotebookRead, WebFetch, TodoWrite, WebSearch,
mcp__context7__resolve-library-id, mcp__context7__get-library-docs
model: sonnet
color: yellow
---
You are CodeComedy Carl, a senior engineer who delivers insightful technical
reviews wrapped in programming humor... (system prompt continues)
Notice what's not there: no Write, Edit, or Bash. The reviewer can read code, search, fetch docs (including via the Context7 MCP server configured earlier), and keep a to-do list — and nothing else. That's least privilege, applied at creation time.
A definition created through /agents takes effect immediately — no restart. (If you instead add or edit an agent file on disk directly, restart the session so Claude picks it up.) And one useful trick from the book: if a description or system prompt feels too vague, don't hand-tune it — ask a separate Claude instance to improve the prompt, then paste the result back. You're using Claude to write Claude's instructions.
Analogy — filling out the job requisition Creating a subagent is filling out a hiring card. You write the role ("code reviewer"), the trigger for when HR should call this person in ("when someone says 'funny review'"), the tools they're issued (a badge that opens the reading room but not the server room), and their seniority level (Sonnet — solid and affordable, not the most expensive principal on staff). /agents is the HR portal that turns your description into a filed, reusable req.
3. Invoking a subagent — and why "parallel" isn't automatic
A subagent gets used in several ways, escalating from "let Claude decide" to "force it for the whole session":
- Automatic delegation. Claude reads your request, compares it against every subagent's
description, and delegates on its own when there's a match. This is why thedescriptionis load-bearing — it's the routing signal. (Phrases like "use proactively" in a description nudge Claude to reach for it more readily.) - Naming it in natural language. "Use the code-reviewer subagent on
@main.py." You name it; Claude does the rest. @-mentioning it. Typing@and picking the agent (or@agent-<name>) requests that specific subagent for one task. It controls which agent runs, not the prompt it receives.- Running a whole session as it.
claude --agent <name>starts a session where the main thread itself takes on that subagent's system prompt, tool restrictions, and model (CLAUDE.md and project memory still load normally); setagentin.claude/settings.jsonto make it a project's default. You can also define throwaway, session-only subagents inline with the--agentsJSON flag.
These aren't a fixed menu of exactly three or four — they're points on a scale from "Claude decides" to "you pin it for the session."
The book demonstrates the natural-language path: funny review @main.py spawns the review agent, which reads the file in its own context and reports back. Ask for two reviews of the same file and Claude spawns two instances of the agent — and here is the chapter's most important practical lesson:
Those two instances run sequentially, not concurrently. Claude Code does not assume tasks are independent. When it's unsure whether two jobs might depend on each other, it plays it safe and runs them one after another.
You can influence this with phrasing. To get genuine parallelism, make independence explicit in the prompt. Instead of "review this PR," say "review these files in parallel" or "create separate review agents for each file." Structuring the request so that independence is obvious is what increases the odds of concurrent execution. (This is the same independent-vs-dependent judgment from Chapter 6, now expressed in how you word the request rather than how you split terminals.)
One housekeeping note on watching a subagent work: while it runs, a panel below the prompt input shows the active subagent(s), and the /agents command's Running tab lists live and recently-finished subagents so you can open or stop them. To see a subagent's detailed tool calls and execution inline, open the transcript viewer with Ctrl+O. (Don't confuse /agents with claude agents — the separate Agent View for background sessions, where Ctrl+R renames a session.)
Analogy — the cautious dispatcher Hand a dispatcher two work orders and, if they can't tell whether the second job depends on the first, they'll send one crew, wait for it to finish, then send the next — safe, but slow. If you know the jobs are independent, you tell them so: "these don't touch each other — send both crews now." Claude is that cautious dispatcher. The default is sequential; the words "in parallel" or "a separate agent for each" are how you authorize it to send everyone at once.
4. Why subagents work — context flow and the lean main thread
This is the heart of the chapter. When the main agent decides to use a subagent, it writes a delegation message — a summary of the task — and hands it off. The subagent starts in a fresh, isolated context window: it does not see your conversation history, the skills you've already invoked, or the files Claude has already read. It works independently, calls whatever tools it needs, and returns a single condensed response.
"Fresh" doesn't mean "empty," though — it's worth being precise about what does reach a subagent at startup. Besides Claude's delegation message, a (non-fork) subagent's initial context includes its own system prompt (its definition body, plus environment details) — not Claude Code's full system prompt — along with every level of your CLAUDE.md / memory hierarchy the main conversation loads, a git-status snapshot, and the full content of any skills preloaded through its skills field. The two built-in research agents, Explore and Plan, are the exception: they skip CLAUDE.md and git status to stay fast and cheap. What a subagent doesn't get is the back-and-forth of your conversation — and that asymmetry is the point: the verbose history stays out of its window, and its verbose work stays out of yours. (One further exception: a forked subagent deliberately inherits the parent conversation instead of starting fresh.)
The payoff is that the main thread stays lean. A subagent might read tens of thousands of tokens internally and hand back a one-page summary; that internal sprawl never lands in your main conversation. Anthropic's context-engineering write-up quantifies the shape of it: a subagent "might explore extensively, using tens of thousands of tokens or more, but returns only a condensed, distilled summary of its work (often 1,000–2,000 tokens)... The detailed search context remains isolated within sub-agents, while the lead agent focuses on synthesizing and analyzing the results." The book's own illustration is the same idea: a subagent burns ~100K tokens of internal work and returns a ~25K summary — and the main context is preserved.
Why does this matter so much? Because a context window is finite and fills up across a session. The book's worked picture: turn by turn, usage climbs — 30K, 90K, 140K, 180K — until you hit the ceiling and have to /compact, /clear, or start fresh. And well before the ceiling, context pollution sets in: so much accumulated, now-irrelevant text that the model's answers degrade. Anthropic's framing of the same effect is that the model has an "attention budget" it draws on as it parses context, and "as the number of tokens in the context window increases, the model's ability to accurately recall information from that context decreases."
Subagents sidestep both problems. Each runs in its own window, so the expensive exploration happens outside your main budget, and only the distilled result comes back. This is why, with subagents, you reach for /compact and /clear far less often — the main thread simply doesn't bloat the way a single-agent session does. The official docs name this benefit directly: subagents preserve context, enforce constraints (limited tools), reuse configurations, specialize behavior, and control costs (route work to cheaper models).
Analogy — the assistant who hands you a one-page memo You ask an assistant to digest a 300-page regulatory filing. The bad version dumps all 300 pages on your desk "for reference" — now your desk is buried and you can't find anything. The good version reads all 300 pages at their own desk and hands you a crisp one-page memo with the three things that matter. The reading still happened; it just didn't happen on your desk. A subagent is that good assistant: the heavy reading stays in their office, and your workspace stays clear enough to keep thinking.
5. Shaping a subagent — the description, the system prompt, and a security warning
A subagent gives you two distinct levers, and knowing which one to pull is the real skill. The book demonstrates both by building a mermaid-diagram-generator agent (it turns text descriptions into Mermaid diagram code) and refining it when the first results come out cluttered.
**Lever 1 — the description: it controls when the agent fires, and it shapes the task prompt Claude writes for it. Claude reads the description (together with your request and the current context) to decide when to delegate to this subagent. And because Claude composes the delegation prompt** it hands the subagent — based on your request and the agent it picked — the wording of the description also steers how that task gets framed. So editing the description changes both when the agent is chosen and what reaches it: when the book adds "always simplify the concept to the gist, and include a small ASCII sketch" to the description, the delegation prompts the subagent receives become gist-level and pre-simplified — and the diagrams improve. Good descriptions often include concrete <example> blocks (sample user inputs and when to trigger) to make both the routing and the prompting sharper.
**Lever 2 — the system-prompt body: it controls the subagent's internal logic.** Shaping the incoming prompt only goes so far. When the Mermaid agent kept returning a summary of the diagram instead of the diagram code, the fix wasn't in the description — it was in the body: an explicit step like "always respond with only the complete Mermaid code, no fluff," plus numbered procedure steps. That part of the Markdown defines how the subagent executes, and it affects only the subagent, never the main agent.
description shapes the prompt the main agent writes; the body shapes how the subagent executes. Tune the right one for the problem you have. Pedagogical diagram by this training, not from the book.Two warnings ride along with this power.
Tool pollution. When the book first creates the Mermaid agent, it leaves read, edit, and execution tools enabled — far more than a "turn text into diagram syntax" job needs. That's tool pollution: every tool definition you attach adds tokens to the subagent's context and widens its capabilities for no reason. Over-provisioning costs context overhead and creates needless security exposure. The discipline is the same least-privilege rule from §1 — grant the minimum set of tools and nothing more.
Untrusted definitions are dangerous. A subagent definition is far more than a system prompt: it can specify the agent's tools, its permission mode, lifecycle hooks, MCP servers, memory, and the description that steers when and how Claude delegates to it. So a definition you copied from an untrusted source could quietly grant itself dangerous tools, attach a malicious hook, loosen permissions, or carry instructions that change how work is routed and prompted — even if you only ever invoke it for something innocuous. Treat a subagent's Markdown like any other code you'd run: read it before you install it, and be wary of definitions from sources you don't trust. (This echoes Chapter 5's prompt-injection caution: the model will act on text it's given, so where the text came from matters.)
Analogy — the recipe card and the cook's training You can change what a line cook produces in two places. You can rewrite the order ticket that reaches them ("make it simple — three ingredients, plate it clean") — that's the description shaping the prompt the kitchen sends back. Or you can change the cook's training manual ("always taste before plating; always send the dish, never a description of the dish") — that's the system-prompt body. Pull the ticket lever for what to make; pull the training lever for how it's made. And never hire a cook whose résumé you didn't read — a sentence buried in it might tell your whole kitchen to do something you'd never approve.
6. Scaling with concurrent subagents — the Infinite Agentic Loop
Everything so far used one subagent at a time. The real leverage shows up when you spawn many at once, each producing its own implementation, then evaluate the results and keep the strongest. The book builds this on a community pattern called the Infinite Agentic Loop — an open-source repository by IndyDevDan (GitHub handle disler), explained in his "Infinite Agentic Loop with Claude Code" video.
This is a community pattern, not an official Anthropic feature. It's one engineer's demonstration of pushing Claude Code's own primitives — a custom.claude/commands/slash command plus the Agent tool — to spawn waves of parallel subagents. We use it as an illustrative capstone. The concept is durable; the exact command syntax is version-dated, so verify it against the current docs before relying on it. (The book writes the creator's name as "IndieDevDan / IndieDev.com"; the correct handle is IndyDevDan, atagenticengineer.com.)
The pattern lives in one slash command, invoked with three inputs:
/infinite <spec_file> <output_dir> <count>
spec_file— a Markdown spec describing what to generate.output_dir— where each generated variation is written.count— a number (1…N) or the literal wordinfinite.
The book's worked example asks for variations of a web app's Hero component. It extracts the existing hero into its own file, asks Claude to write a Hero.spec.md from it, copies the infinite.md command into .claude/commands/, restarts Claude so the command loads, and runs /infinite against the spec. Claude Code then launches six parallel subagents, each generating a distinct hero variation — minimal, centered, waveform, particles, terminal, gradient-mesh — written side by side into the output directory. The human then renders all six on the page, compares them, and keeps the best one (the book picks the "terminal" hero), clearing the context before the final cleanup commit.
That last move is the whole philosophy in one line: you scale by spending compute. As the book puts it, "the number of tokens we are willing to spend determines how much parallel exploration we can afford." You're no longer writing one implementation and hoping it's good; you're generating several in parallel and selecting.
The honest counterweight — which the book flags and Anthropic's research reinforces — is cost. The book deliberately gives no price estimate (pricing moves) and simply says: monitor token usage, because each agent generates and may test its own code. Anthropic's multi-agent research backs the scale of this: in their internal evaluation, agents used about 4× more tokens than chat, and multi-agent systems about 15× more — so the approach "require[s] tasks where the value of the task is high enough to pay for the increased performance." They also caution that "most coding tasks involve fewer truly parallelizable tasks than research." Translation: reach for a swarm of subagents when the work genuinely forks into independent paths and the payoff justifies the spend — not for everything.
infinite mode the orchestrator keeps launching waves until its context budget is spent. Pedagogical diagram by this training, not from the book.Analogy — six architects, one brief Instead of asking a single architect to design your house and hoping you like it, you hand the same brief to six firms at once and commission a concept from each. A week later you spread all six on the table, compare them, and build the one you love — maybe borrowing a staircase from a runner-up. You paid six design fees instead of one, which only makes sense for a decision big enough to justify it. The Infinite Agentic Loop is that competition: one spec, six (or sixty) parallel designs, your pick at the end — and a bill that scales with how many you commission.
7. Under the hood — the infinite prompt as a high-order prompt
The capstone idea is how one command spawns all those agents. Open infinite.md and you find not a normal prompt but a high-order prompt — a prompt whose job is to generate other prompts. The book calls this meta-prompting, by analogy to higher-order functions in programming (functions that take or return functions). Here, one prompt takes a spec as input and emits many subagent prompts as output.
It opens by switching the main agent into deep reasoning —
Think deeply about this infinite generation task. You are about to embark
on a sophisticated iterative creation process.
— then declares its inputs and lets the model itself parse them (there is no parsing code; the LLM does it every time the command runs):
spec_file: $ARGUMENTS output_dir: $ARGUMENTS count: $ARGUMENTS
From there it runs four phases — and this structure is worth learning, because it's a clean template for any "generate many candidates" workflow:
- Specification analysis — read and deeply understand the spec: what to generate, and how each iteration should build on the last.
- Output-directory reconnaissance — scan the output directory: what already exists, the highest iteration number so far, how prior iterations evolved, and where the gaps are. (This is what makes runs resumable and additive — a second run continues where the first left off.)
- Iteration strategy — decide the starting iteration number and how each new one stays unique; if
countisinfinite, prepare to keep generating until context limits force a stop. - Parallel agent coordination — spawn the subagents via the Agent tool (the tool formerly called Task). For counts of 1–5, launch all at once; for
infinite, launch waves of three to five, monitoring context and starting new waves until the budget runs out.
Each spawned subagent receives a tightly structured assignment packet: the spec context, a directory snapshot (so it knows what already exists), its iteration assignment (its number and creative direction), a uniqueness directive (explicitly: don't duplicate existing iterations), and quality standards. The orchestrator then manages the wave — launching simultaneously, monitoring completion, reassigning numbers if an agent fails, and ensuring no duplicates.
A precise note the book glosses: this is divergent generation, not an automatic tournament. There's no built-in "score all six and crown a winner" step. "Selection" is distributed — each agent is told to make its output different from the others — and the human reviews the resulting set and picks. The loop maximizes useful variety; you supply the judgment. (In the language of Anthropic's Building Effective Agents, this is the orchestrator-workers pattern: a central agent dynamically breaks a job into subtasks, delegates them to workers, and the results are combined — here, by you.)
Analogy — the manager who writes the tickets, not the code Picture a project manager who never writes a line of code. You give them one brief, and their entire skill is turning it into a stack of well-scoped work tickets — one per engineer — each saying exactly what to build and how it must differ from the others. They hand the tickets out all at once, track who's done, and re-issue any that get dropped. The infinite prompt is that manager rendered as text: a prompt whose output is more prompts. It does almost no object-level work itself; its product is the orchestration.
The whole chapter in one image — delegate, isolate, then multiply
Analogy — pedagogical summary, drawing on all seven sections
Run your work like a consulting partner, not a soloist.
You take the meeting; you delegate the digging. A client asks a big question. You don't read every document yourself — you'd drown in paper and lose the thread (context pollution). You brief an associate with one sealed task, they research in their own office, and they hand you a one-page memo (a subagent: its own context, a condensed summary back). Your desk stays clear enough to keep thinking.
You staff each job deliberately. Every associate has a job card — their specialty, when to call them, which rooms their badge opens, their seniority (the definition file: name, description, tools, model). You issue the reading room, not the server room (least privilege), and you read anyone's résumé before you hire them off the street (untrusted definitions are dangerous).
You tune them on two dials. Rewrite the order ticket to change what reaches them (the description shaping the prompt), or update their training manual to change how they work (the system-prompt body). And you tell the cautious dispatcher when jobs are independent — "send all the crews now" — or they'll send them one at a time.
For the biggest decisions, you run a competition. You commission six firms from one brief, spread the concepts on the table, and build the best (the Infinite Agentic Loop). It costs six fees instead of one, so you do it only when the decision is worth it. And the thing orchestrating all of it is a manager who writes tickets rather than code — a prompt that writes prompts. Delegate, isolate, then multiply: that's the whole chapter.
Activity — Design a subagent on paper
Ten minutes, individual, no setup required. You'll design (not build) one subagent for a task you actually do — sharpening the judgment the practical exercise then exercises live.
- Pick a recurring side-task that floods your main work with output you don't keep — e.g., "review a diff," "summarize what a module does," "draft a commit message," "audit dependencies for a known CVE."
- Write the frontmatter. Give it a
name, then a one-to-two sentencedescriptionthat says when the main agent should delegate to it (include a trigger phrase or an<example>-style cue). Remember the description does double duty — it also shapes the prompt the agent receives. - Apply least privilege. List the
toolsit genuinely needs and, explicitly, the ones you're withholding and why. (If it only reads and reports, it should not haveWrite,Edit, orBash.) Pick amodeland justify it — could a fast/cheap model do this job? - Write one body instruction that controls output format — the lever-2 line that guarantees the agent returns the artifact you want, not a summary of it (e.g., "respond with only the commit message, no preamble").
- Decide parallelism. Would you ever run several instances of this agent at once? Write the one sentence you'd type to make their independence explicit so Claude runs them concurrently rather than sequentially.
Keep the result — steps 2–4 are literally a subagent definition file, and step 5 is the phrasing that unlocks parallelism. You'll build something very close to this next.
Practical exercise — Build, shape, and parallelize a subagent
~35–45 minutes. Hands-on. No web framework, nonpm, no accounts — just Claude Code,git, and a tiny throwaway sandbox. You'll create a real subagent with/agents, watch context isolation in action, tune it with both levers, then run several instances in parallel — a safe, local taste of the Infinite Agentic Loop without cloning anything or spending a swarm's worth of tokens.
Everything happens in a throwaway sandbox — nothing here touches the training repo.
Setup (5 min). Create a sandbox with three small, independent Python files to review (plain stdlib — no installs):
mkdir -p ~/cct-ch7-lab && cd ~/cct-ch7-lab
git init -q
cat > prices.py <<'PY'
def total(cart):
t = 0
for item in cart:
t = t + item["price"] * item["qty"]
return t # no rounding; floats will drift
PY
cat > auth.py <<'PY'
def check(token, allowed):
# returns True if token is allowed
return token in allowed # constant-time comparison not used
PY
cat > slugify.py <<'PY'
def slugify(s):
return s.lower().replace(" ", "-") # doesn't strip punctuation
PY
git add . && git commit -q -m "init review sandbox"
Part 1 — create a least-privilege subagent (10 min). Start claude in the sandbox and run:
/agents
Create a project-scoped agent with Generate with Claude. Describe it so the trigger is clear, e.g.:
A careful senior code reviewer. Use it when I say "review" and name a file.
It reads the code and reports bugs, security issues, and risky patterns,
grouped by severity, each with a file:line, the impact, and a concrete fix.
At the tool step, select read-only tools only (Read, Grep, Glob — and LS if offered); leave Edit/Write and execution tools off. Pick Sonnet (or Haiku, to feel the cost lever). Save.
Expected outcome: a file appears at .claude/agents/<name>.md. Open it and confirm: name and description are set, tools lists only read/search tools (no Write/Edit/Bash), and a model is set. You've applied least privilege at creation time.
Part 2 — invoke it and watch context isolation (10 min). Ask the main agent to use it on one file, naming it explicitly:
Use the code-reviewer subagent on @prices.py.
Expected outcome: the subagent spawns, reads the file in its own context, and the main thread shows a condensed summary (it should flag the float-rounding issue). Open the transcript viewer with Ctrl+O to see its detailed tool calls and execution (and watch the subagent panel below the prompt, or /agents → Running tab, to track it). Then run /context (or check the context indicator) and note how little the main conversation grew — the subagent's reading didn't land in your main window. That gap is the benefit.
Part 3 — pull both levers (10 min). First, lever 2 (the body). Edit .claude/agents/<name>.md and add a final instruction to its system prompt, e.g. "End every review with a one-line VERDICT: SHIP or BLOCK." Save, then restart Claude (file edits on disk need a restart; /agents edits don't) and re-run the review — the verdict line should now appear. Next, lever 1 (the description). Tighten the description (e.g., add "focus on security issues first") and review @auth.py; notice the main agent now frames the delegated prompt around security (it should surface the non-constant-time token comparison).
Expected outcome: you've changed the output format by editing the body and changed what the agent emphasizes by editing the description — the two levers from §5, felt directly.
Part 4 — parallelize (10 min). Now force concurrency. First, deliberately phrase it the sequential way and watch the default:
Review prices.py, then auth.py, then slugify.py with the code-reviewer.
Then phrase it so independence is explicit:
Review prices.py, auth.py, and slugify.py in parallel —
spawn a separate code-reviewer subagent for each file.
Expected outcome: the second phrasing spawns three reviewers that run concurrently, each in its own context, each returning its own summary — three files reviewed without bloating the main thread. That's the §3 lesson and the seed of the Infinite Agentic Loop: independent work, fanned out, summarized back.
Success checklist
- [ ] You created a subagent with
/agentsand can point to its file under.claude/agents/. - [ ] Its
toolsare read-only — noWrite/Edit/Bash— and you can explain why (least privilege). - [ ] Invoking it returned a condensed summary, and
/contextshowed the main thread barely grew (context isolation). - [ ] Editing the body changed the output format (after a restart); editing the description changed what the agent emphasized — you used both levers.
- [ ] The "in parallel / a separate agent for each" phrasing ran multiple reviewers concurrently, while the "then … then …" phrasing ran them sequentially.
Common pitfalls - Granting every tool "just in case." That's tool pollution — wasted context tokens and needless capability. Give a reviewer read-only tools; it never needs to write or run shell commands. - Editing the agent file and expecting an instant change. Edits made on disk need a session restart; only agents created/edited through/agentstake effect immediately. - Expecting parallelism by default. Claude runs subagents sequentially when it can't confirm independence. If you want concurrency, say so — "in parallel," "a separate agent for each." - Tuning the wrong lever. If the agent fires at the wrong times or gets a vague prompt, fix the description. If it does the work but formats the result wrong, fix the system-prompt body. They're different controls. - Installing a subagent you didn't read. A definition carries more than instructions — it can set the agent's tools, permission mode, hooks, MCP servers, and memory, and itsdescriptionsteers how Claude routes and prompts work. An untrusted one can influence all of that. Read any third-party definition before you use it. - Reaching for a swarm when one agent (or none) would do. Parallel subagents multiply token cost ~15× over a chat in Anthropic's internal numbers; they pay off for genuinely independent, high-value work — not routine edits.
Knowledge check — try the quiz
Once you've read the lesson and worked the lab, take the chapter quiz from the navigation bar. Six questions: five grounded in the book chapter, one synthesis question that ties this chapter's subagents to the broader multi-agent landscape and the orchestrator-workers pattern. Passing score is 5/6 — retake it until you're confident.
Further reading & enrichment sources
- Anthropic docs — "Subagents" (
https://code.claude.com/docs/en/sub-agents). The canonical reference: what a subagent is, the full frontmatter schema (far larger than the book lists —disallowedTools,permissionMode,skills,mcpServers,memory,isolation: worktree,color, and more), the project/user file locations and precedence,toolsas a genuine allowlist (omit = inherit all), automatic vs explicit (@-mention) invocation, and the built-in agents (Explore, Plan, general-purpose). - Anthropic docs — "Run agents in parallel" / agents overview (
https://code.claude.com/docs/en/agents). Where subagents sit among the other surfaces — background agents / Agent view (claude agents), agent teams, dynamic workflows (/workflows),/batch, worktrees — and the note thatclaude agents(the CLI) and/agents(the slash command) are different things. - Anthropic docs — "Agent teams" (
https://code.claude.com/docs/en/agent-teams). The coordinated, multi-session cousin of subagents — "both let you parallelize work, but operate differently"; experimental and disabled by default (CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS). - Anthropic engineering — "How we built our multi-agent research system" (
https://www.anthropic.com/engineering/multi-agent-research-system). The orchestrator-worker architecture in production (a lead agent spawns 3–5 parallel subagents), the headline results from Anthropic's internal evaluation (a multi-agent system outperformed single-agent by ~90% on their research eval), and the honest cost story (agents ~4× chat tokens; multi-agent ~15×). - Anthropic engineering — "Building effective agents" (
https://www.anthropic.com/engineering/building-effective-agents). The taxonomy that names the Infinite Agentic Loop's shape: orchestrator-workers ("a central LLM dynamically breaks down tasks, delegates them to worker LLMs, and synthesizes their results") versus fixed parallelization. - Anthropic engineering — "Effective context engineering for AI agents" (
https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents). Why isolation matters: the "attention budget," context as "a finite resource with diminishing marginal returns," and the subagent compression figure (explore tens of thousands of tokens, return a 1,000–2,000-token summary). - Anthropic cookbook — orchestrator-workers & using sub-agents (
https://platform.claude.com/cookbook/patterns-agents-orchestrator-workers,https://platform.claude.com/cookbook/multimodal-using-sub-agents). Runnable examples of dynamic delegation and using a cheap model (Haiku) as a subagent under a more capable orchestrator. - Community — Infinite Agentic Loop (
https://github.com/disler/infinite-agentic-loop) by IndyDevDan (https://www.youtube.com/@indydevdan,https://agenticengineer.com). The external, MIT-licensed repo behind the chapter's capstone. Read it as a pattern — the/project:infinitesyntax and "Sub Agent" wording reflect an earlier Claude Code naming convention; verify against current docs before relying on the literal command.
Knowledge check
6 questions. Passing score: 5.
Instructor notes & source coverage
Source Ledger — Chapter 7: Working with Claude Code Subagents
Primary source (the book)
- Source PDF:
source-pdfs/07-chapter-07.pdf(57 pages) - Extracted source:
extracted-chapters/07-chapter-07.md(visual transcription, with<!-- page N -->markers for all 57 pages). There is no usable.txtfor this chapter — see the Extraction caveat at the end. - Extraction tool: none of the usual text extractors worked — the Chapter 7 PDF is image-only (each page is composed of rendered images;
pdftotext -layoutandpypdfboth returned 0 characters). The chapter was extracted by rendering all 57 pages to PNG at 150 DPI with PyMuPDF (fitz) intowork/07-chapter-07-pages/and transcribing them visually intoextracted-chapters/07-chapter-07.md. The transcription preserves the book's original wording verbatim — including stale terminology (the "Task tool" name) and the creator's misspelled handle ("IndieDevDan" / "IndieDev.com"). - Book's main sections (from the extract): "Introduction to Claude Code subagents" (pp. 2–7); "Configuring the first subagent" via
/agents— describe / generate-with-Claude / manual, tool selection, model/visual settings, reviewing the generatedcode-comedy-carl.md(pp. 8–13); "Testing our subagent" — Fibonacci file,funny review @main.py, spawning two sequential instances (pp. 13–16); "Context flow while using subagents" + "Context windows in action" — the one-prompt-down / one-summary-back model and the 200K-token worked example (pp. 16–20); "Example: Creating a Mermaid diagram subagent" — tool pollution, the two levers (description vs system-prompt body), the untrusted-definition security warning, refining output to return only the diagram code (pp. 20–35); "Scaling with concurrent subagents" — the Infinite Agentic Loop repo, HookHub setup,/infinite, six parallel Hero variations, human selection (pp. 35–48); "Infinite prompt" — the high-order/meta prompt under the hood, four phases, the Agent ("task") tool, agent assignment protocol (pp. 49–56); "Summary" (pp. 56–57).
Enrichment sources
The lesson silently incorporates material from the official Claude Code documentation, Anthropic's engineering blog, the Anthropic cookbook, and one community pattern repository. Per project convention, no inline > Source: or > Enrichment — ... labels appear in the learner-facing lesson — the only in-lesson labelled callouts are the > Analogy — ... boxes. This source ledger is the single source of provenance.
- [E1] Anthropic docs — Subagents —
https://code.claude.com/docs/en/sub-agents - [E2] Anthropic docs — Run agents in parallel / agents overview —
https://code.claude.com/docs/en/agents - [E3] Anthropic docs — Agent teams —
https://code.claude.com/docs/en/agent-teams - [E4] Anthropic docs — Slash commands —
https://code.claude.com/docs/en/commands - [E5] Anthropic docs — Worktrees —
https://code.claude.com/docs/en/worktrees - [E6] Anthropic engineering — How we built our multi-agent research system —
https://www.anthropic.com/engineering/multi-agent-research-system - [E7] Anthropic engineering — Building effective agents —
https://www.anthropic.com/engineering/building-effective-agents - [E8] Anthropic engineering — Effective context engineering for AI agents —
https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents - [E9] Anthropic cookbook — Orchestrator-workers / using sub-agents —
https://platform.claude.com/cookbook/patterns-agents-orchestrator-workers(andhttps://platform.claude.com/cookbook/multimodal-using-sub-agents) - [E10] Community pattern — Infinite Agentic Loop by IndyDevDan / disler —
https://github.com/disler/infinite-agentic-loop(MIT; creator's sitehttps://agenticengineer.com, channelhttps://www.youtube.com/@indydevdan)
The book is largely current on this chapter's surface (subagents had not drifted far between the book's writing and this build — verified against the canonical docs before authoring; see the Drift / Corrections Applied table). Enrichment is used to (a) complete the picture (the frontmatter schema beyond what the book lists, the built-in Explore/Plan agents, the three invocation methods, the broader scope hierarchy); (b) quantify and ground the context-isolation argument (the ~1,000–2,000-token condensed-summary figure and the "attention budget" framing from [E8]; the ~4×/~15× token multipliers and the orchestrator-worker architecture from [E6]; the orchestrator-workers pattern name from [E7]); and (c) correct two genuine book errors (the creator's name/handle and the framing of the Infinite Agentic Loop as merely "the implementation" rather than a community pattern).
Pedagogical enrichment by the training author
Not from the book and not from the docs — written for this training, inventoried here for separate audit. No inline labels in the lesson except the > Analogy — ... callouts.
- Newcomer preface (
## Before we start — agents, subagents, context windows, and "meta" prompts). Defines the main agent, a subagent (own system prompt / own isolated context window / selective tool access), a context window and why quality degrades before the ceiling (the attention-budget idea), system prompt vs user prompt, concurrent vs sequential, a "meta"/high-order prompt by analogy to higher-order functions, and where this sits relative to Chapter 6's three senses of "multiple agents." Grounded in [E1], [E8]; the higher-order-functions analogy and the Chapter-6 bridge are the chapter's framing devices. - Per-section analogies. Seven
> Analogy — ...callouts, one per numbered section: §1 the specialist with a sealed brief; §2 filling out the job requisition; §3 the cautious dispatcher; §4 the assistant who hands you a one-page memo; §5 the recipe card and the cook's training; §6 six architects, one brief; §7 the manager who writes the tickets, not the code. - Whole-chapter analogy (
## The whole chapter in one image — delegate, isolate, then multiply). A sustained consulting-partner analogy threading all seven sections (take the meeting / delegate the digging → staff each job deliberately → tune on two dials → run a competition for the biggest decisions). - Three SVG diagrams (the book's figures are screenshots and are not reproduced — we do not have rights, and they're image-only screenshots besides):
- Figure 7.A — main↔subagent context flow: one prompt down, one condensed summary (~1–2k tokens) back, the subagent's heavy internal tokens never added to the lean main thread.
- Figure 7.B — the two levers: the
description(read by Claude to decide when to delegate and to write the task prompt it sends the subagent) vs the system-prompt body (sent only to the subagent → controls internal logic and output format). - Figure 7.C — the Infinite Agentic Loop fan-out: one spec + count → main agent as orchestrator → a wave of six parallel subagents (via the Agent tool) → many variations → human review and selection; infinite mode plans further waves until context runs out.
- Each SVG
figcaptionexplicitly notes it is "Pedagogical diagram by this training, not from the book." - Conceptual activity — "Design a subagent on paper." Ten-minute individual exercise: pick a recurring side-task, write the frontmatter (
name+ trigger-bearingdescription), apply least privilege totools(and name what's withheld and why), write one lever-2 body instruction that controls output format, and decide the parallelism phrasing. Grounded in §1/§3/§5. - Practical exercise — "Build, shape, and parallelize a subagent." A ~35–45 min hands-on lab on a framework-free, stdlib-only Python sandbox (three small files with planted defects —
prices.pyfloat-drift,auth.pynon-constant-time comparison,slugify.pymissing punctuation strip), created at~/cct-ch7-lab/outside the training repo. Part 1 creates a least-privilege reviewer with/agents(project scope, generate-with-Claude, read-only tools); Part 2 invokes it on one file and watches context isolation (/context, plus the/agentsRunning tab andCtrl+Otranscript viewer); Part 3 pulls both levers (edit the body for an output-format change requiring a restart; tighten the description for an emphasis change); Part 4 contrasts the sequential phrasing against an explicit "in parallel / a separate agent for each" phrasing to force concurrency. The sandbox deliberately uses nonpm/Node (the book's HookHub is Next.js) so every learner can run it.
Quiz items and learning objectives remain grounded in the book chapter and the labelled enrichment; none of the analogies, diagrams, the activity, or the exercise steps are themselves assessed.
Objective → Source Mapping
| Learning Objective | Source Section (page) | Enrichment | Confidence | Notes |
|---|---|---|---|---|
| Explain what a subagent is — own system prompt, own isolated context window, selective tool access — and how it differs from the main agent (doesn't see the conversation history; returns one condensed summary). | Book "Introduction to Claude Code subagents" (pp. 2–3) + "Context flow while using subagents" (pp. 16–18) | [E1] | High | The three defining properties and the isolation/condensed-summary framing are the book's; [E1]'s "does not see your conversation history, the skills you've already invoked, or the files Claude has already read" sharpens the wording. |
Create a subagent with /agents (guided / generate-with-Claude / manual) and read or author its Markdown definition: required name/description, the tools allowlist (omit → inherit all), model (incl. inherit), and project (.claude/agents/) vs user (~/.claude/agents/) scope. | Book "Configuring the first subagent" → "Reviewing the generated agent configuration" (pp. 8–13) + frontmatter/schema discussion (pp. 6–7) | [E1] | High | Generate-with-Claude vs manual, the code-comedy-carl walkthrough, the two file directories, and "if left empty… granted access to all available tools" are the book's. model defaulting to inherit and the broader 5-level precedence are completed from [E1] (see Drift). |
Invoke a subagent several ways — automatic delegation (description-driven), naming it in natural language, @-mention, and session-wide (claude --agent <name> / the agent setting; --agents JSON for session-only definitions) — and explain why instances run sequentially unless independence is explicit. | Book "Running a code review subagent" + the two-instances note (pp. 14–15) | [E1] | High | The book demonstrates the natural-language path and is explicit on sequential-by-default and the "review these files in parallel" / "separate agents for each file" influence. Automatic delegation, @-mention, and the session-wide --agent/agent/--agents methods are completed from [E1]; the book's "can also be invoked through a slash command" is softened, and the list is framed as a scale rather than a fixed count (see Drift). |
| Explain why subagents keep the main context lean (fresh isolated window from Claude's delegation message; heavy work stays out of the main thread; one condensed summary back) and connect it to finite context, context pollution, and the attention budget. | Book "Context flow…" + "Context windows in action" (pp. 16–20) | [E8], [E1] | High | The book's worked 200K-token growth example and the ~100K-internal → ~25K-summary illustration are preserved (size softened — see Drift). [E8] supplies the ~1,000–2,000-token condensed-summary figure and the "attention budget" / "finite resource with diminishing marginal returns" framing. [E1] "what loads at startup" corrects the book's "only context is the generated prompt": a non-fork subagent also loads its own system prompt+env, CLAUDE.md/memory, git status, and preloaded skills (Explore/Plan skip CLAUDE.md+git; forks inherit the parent) — see Drift. |
Shape a subagent through its two levers — the description (when it fires + the task prompt Claude writes) and the system-prompt body (internal logic) — apply least privilege to tools (avoid tool pollution), and recognize the untrusted-definition security risk. | Book "Example: Creating a Mermaid diagram subagent" → refining description → tool-pollution → security Pro Tip → refining output (pp. 20–35) | [E1] | High | Both levers, tool pollution, and the untrusted-definition concern are the book's, demonstrated on the Mermaid agent. The book's "the description is appended to Claude Code's main agent system prompt" framing is reframed to current docs (Claude uses the description to decide when to delegate and composes the task prompt), and the warning is broadened to an untrusted definition's influence over routing/prompting/tools/permission mode/hooks/MCP/memory (see Drift). The Skills allowed-tools contrast is added from [E1] / the locked-in CLAUDE.md drift note. |
| Describe how concurrent subagents scale exploration via the Infinite Agentic Loop — one high-order ("meta") prompt fanning out to parallel subagents via the Agent tool to generate many variations for human selection — and judge when it's worth the token cost. | Book "Scaling with concurrent subagents" + "Infinite prompt" (pp. 35–56) | [E6], [E7], [E9], [E10] | High — synthesis | The /infinite walkthrough, six Hero variations, "scale via compute," the four phases, and the high-order/meta-prompt framing are the book's. [E7] names the orchestrator-workers pattern; [E6] supplies the ~4×/~15× token multipliers and the cost-justification framing; [E10] is the canonical repo; [E9] is the runnable cookbook analogue. |
Lesson Section → Source Mapping
| Lesson section | Source location | Enrichment | Confidence | Notes |
|---|---|---|---|---|
| Preface — agents/subagents/context windows/"meta" prompts; bridge from Chapter 6's three senses of "multiple agents" | Book pp. 2–3, 16–19 (concepts introduced) | [E1], [E8] | High | Pedagogical re-framing for newcomers. The higher-order-functions analogy and the explicit "this is that next chapter" bridge to Chapter 6 are the lesson's. |
| "Why this chapter matters" — context as the bottleneck; isolation buys both a lean main thread and parallelism | Book intro (p. 1) + pp. 18–19 | [E8] | High | The "finite resource with diminishing marginal returns" quote is from [E8]; the context-pollution motivation is the book's. |
§1 — what a subagent is; the defining file; required name/description; tools allowlist; model incl. inherit; scope directories; broader schema | Book pp. 2–7 (incl. Fig 7.1 file structure and the page-6 schema list) | [E1] | High | The clean code-reviewer example is authored for the lesson (the book's equivalent example on pp. 3–5 is a sprawling project-specific reviewer); fields and behaviour match the book + [E1]. Schema-beyond-the-book (disallowedTools, permissionMode, mcpServers, isolation: worktree, etc.) and the built-in Explore/Plan agents come from [E1] (see Drift). |
| §1 — analogy: the specialist with a sealed brief | n/a — pedagogical | n/a | n/a | Original. |
§2 — configuring with /agents; generate-with-Claude; the funny-reviewer description; tool selection (read-only); model selection (Sonnet); the saved code-comedy-carl.md; immediate effect; the "use Claude to improve the prompt" trick | Book pp. 8–13 — quoted closely | [E1] | High | The walkthrough, the funny-review trigger prompt, the code-comedy-carl frontmatter, and the Pro Tip are the book's. The "created via /agents takes effect immediately; on-disk file edits need a restart" distinction is completed from [E1] / current behaviour. |
| §2 — analogy: filling out the job requisition | n/a — pedagogical | n/a | n/a | Original. |
§3 — invocation methods (automatic delegation / natural-language naming / @-mention / session-wide --agent+agent setting / --agents JSON); sequential-by-default; phrasing for parallelism; watching subagents (/agents Running tab + Ctrl+O transcript viewer) | Book pp. 14–15 — quoted closely | [E1], [E2] | High | Sequential-by-default, the two-instances demo, and the "in parallel" / "separate agents for each" influence are the book's. The invocation methods are completed from [E1] (and framed as a scale, not a fixed count); the book's "can also be invoked through a slash command" is softened (see Drift). Ctrl+R/Cmd+R correction: an earlier draft said Ctrl+R/Cmd+R "expands the agent view to watch subagent activity" — that is wrong. Per [E1]/[E2]/interactive-mode docs, in-session Ctrl+R is reverse-history-search; Ctrl+O toggles the transcript viewer (detailed tool usage); the /agents Running tab lists live subagents; and claude agents (Agent View) is separate, where Ctrl+R renames a background session (see Drift). |
| §3 — analogy: the cautious dispatcher | n/a — pedagogical | n/a | n/a | Original. |
| §4 — context flow; Claude writes a delegation message; "fresh ≠ empty" — what loads at startup (own system prompt+env, CLAUDE.md/memory, git status, preloaded skills; Explore/Plan skip CLAUDE.md+git; forks inherit the parent); one condensed summary back; finite window; context pollution; attention budget | Book pp. 16–20 (Figs 7.8–7.10, the 200K growth example) | [E8], [E1] | High | The book's input/output model and the worked token-growth picture are preserved (size softened — see Drift). The ~1,000–2,000-token summary figure and the "attention budget" / recall-degrades-with-length framing are from [E8]. The book's "the only context the subagent receives is the generated prompt" is corrected from [E1]'s "what loads at startup" (system prompt+env, CLAUDE.md/memory, git status, preloaded skills; Explore/Plan exceptions; fork exception) — see Drift. The five docs-named benefits (preserve context / enforce constraints / reuse configs / specialize / control costs) are from [E1]. |
| §4 — Figure 7.A (one prompt down, one summary back, lean main thread) | n/a — pedagogical diagram | [E8] | n/a | Original SVG. |
| §4 — analogy: the assistant who hands you a one-page memo | n/a — pedagogical | n/a | n/a | Original. |
§5 — two levers; the description is read by Claude to decide when to delegate and to compose the task prompt; <example> blocks; body controls internal logic/output format; tool pollution; untrusted-definition security warning | Book pp. 20–35 (the Mermaid agent: tool pollution p. 22, description-as-prompt-shaper pp. 24–27, security Pro Tip p. 27, body fix for "respond with only the diagram" pp. 30–32) | [E1] | High | The two-levers framing and the Mermaid demonstration are the book's. The book's claim that the description "is appended to Claude Code's main agent system prompt" (extract pp. 24, 27) is reframed to [E1]'s documented behavior — Claude uses the description to decide when to delegate and writes the subagent's task prompt — and the security warning is reframed from a "main-system-prompt hijack" to "an untrusted definition can influence routing, prompting, tools, permission mode, hooks, MCP, memory, or instructions" (see Drift). The contrast with a Skill's allowed-tools (a pre-approval grant, the opposite of a subagent's tools allowlist) is added per [E1] and the locked-in CLAUDE.md drift note. |
| §5 — Figure 7.B (description steers the main agent · body steers the subagent) | n/a — pedagogical diagram | n/a | n/a | Original SVG. |
| §5 — analogy: the recipe card and the cook's training | n/a — pedagogical | n/a | n/a | Original. |
§6 — Infinite Agentic Loop as a community pattern; /infinite <spec> <dir> <count>; six parallel Hero variations; human selection; "scale via compute"; the cost counterweight | Book pp. 35–48 (the HookHub /infinite walkthrough; the six-variation list; "the number of tokens we are willing to spend…"; the cost Note p. 36) | [E6], [E7], [E10] | High | The walkthrough and the six named variations (minimal/centered/waveform/particles/terminal/gradient-mesh) are the book's. [E10] is the canonical repo with the corrected attribution; [E6] supplies the ~4×/~15× multipliers and "value high enough to pay for the increased performance" / "fewer truly parallelizable tasks than research" cautions; [E7] supplies the orchestrator-workers name. The community-vs-official-feature framing corrects the book (see Drift). |
| §6 — Figure 7.C (the fan-out: one spec → wave of subagents → variations → human picks) | n/a — pedagogical diagram | [E6], [E7] | n/a | Original SVG. |
| §6 — analogy: six architects, one brief | n/a — pedagogical | n/a | n/a | Original. |
§7 — the infinite prompt as a high-order/meta prompt; "Think deeply"; $ARGUMENTS LLM-parsed; four phases; the Agent tool (formerly Task); assignment packet; divergent-generation-not-tournament; orchestrator-workers | Book pp. 49–56 (the infinite.md walkthrough, the four phases, "task tool," the assignment protocol, "kudos to IndieDev.com") | [E7], [E10] | High | The four phases, $ARGUMENTS-parsed-by-the-LLM, and the assignment packet are the book's. The "Agent tool (formerly Task)" rename is completed from current Claude Code (see Drift). The "divergent generation, not an automatic tournament" clarification and the orchestrator-workers mapping ([E7]) are the lesson's precision over the book's looser framing. |
| §7 — analogy: the manager who writes the tickets, not the code | n/a — pedagogical | n/a | n/a | Original. |
| Whole-chapter analogy: delegate, isolate, then multiply (consulting partner) | n/a — pedagogical synthesis | n/a | n/a | Original. |
| Activity: Design a subagent on paper | n/a — pedagogical | [E1] | n/a | Original. Grounded in §1/§3/§5. |
| Practical exercise: Build, shape, and parallelize a subagent (stdlib Python sandbox) | Book pp. 8–35 recombined into a framework-free lab | [E1] | High — original sequencing | Every step grounded in the book's /agents + two-levers + parallelism material. Sandbox ~/cct-ch7-lab/ is outside the training repo and uses no npm/Node. |
Unsupported / Pedagogical-Only Claims
Statements in the learner-facing lesson that are not from the book and not directly from the labelled enrichment, listed for isolated audit.
| Item | Justification |
|---|---|
| Specialist-with-a-sealed-brief analogy (§1) | Pedagogical analogy. No external claim. |
| Job-requisition analogy (§2) | Pedagogical analogy. Restates the /agents creation flow. |
| Cautious-dispatcher analogy (§3) | Pedagogical analogy. Restates sequential-by-default. |
| One-page-memo analogy (§4) | Pedagogical analogy. Restates context isolation. |
| Recipe-card / cook's-training analogy (§5) | Pedagogical analogy. Restates the two levers + the untrusted-source caution. |
| Six-architects-one-brief analogy (§6) | Pedagogical analogy. Restates the fan-out-and-select cost trade-off. |
| Manager-who-writes-the-tickets analogy (§7) | Pedagogical analogy. Restates the meta-prompt idea. |
| Whole-chapter consulting-partner analogy | Pedagogical synthesis. No new claims. |
| Figures 7.A–7.C (SVGs) | Original SVGs. Visually restate context flow, the two levers, and the Infinite Agentic Loop fan-out. |
| Higher-order-functions framing of "meta"/high-order prompts (preface, §7) | Pedagogical framing; the book itself draws the same functional-programming analogy ("high-order functions… functions receive functions"). Restated for newcomers. |
The clean code-reviewer frontmatter example (§1) | Authored for the lesson as a tidy, current illustration in place of the book's sprawling project-specific reviewer (extract pp. 3–5). Field semantics match the book + [E1]. |
| "Divergent generation, not an automatic tournament" (§7) | Lesson clarification: the book never claims an automatic scoring/selection step; the lesson makes explicit that selection is human. Grounded in the book's own "render them, compare, choose the best one" flow. |
| Conceptual activity (Design a subagent on paper) | Original exercise; grounded in §1/§3/§5 and [E1]. |
| Practical exercise (stdlib Python sandbox), all parts | Original sequencing; every step grounded in the book or [E1]. The three sandbox files with planted defects are authored for this training; sandbox at ~/cct-ch7-lab/ is outside the training repo. |
Quiz Item → Source Mapping
| Quiz ID | Answer | Item | Source location | Enrichment | Confidence |
|---|---|---|---|---|---|
| q1 | a | What a subagent is and what makes it different from the main agent (own system prompt, own isolated context window, selective tool access; starts fresh from Claude's delegation message — no prior history/skills/files; returns one condensed summary). | Book pp. 2–3, 16–18 | [E1] | High — the three defining properties and the isolation/summary behaviour are the book's; the "starts fresh from a delegation message" wording is tightened to [E1] (replacing "only the prompt it's given"). |
| q2 | c | How a subagent is defined (Markdown + YAML frontmatter; body = system prompt; only name/description required) and what tools (allowlist: omit → inherit all; list → restricted, unlike a Skill's allowed-tools) and file location (project .claude/agents/ vs user ~/.claude/agents/) control. | Book pp. 5–7, 11–12 | [E1] | High — the allowlist semantics are the book's; the Skills allowed-tools contrast and model defaulting to inherit from [E1]. |
| q3 | b | How Claude decides whether subagent instances run concurrently (it does not assume independence → sequential when unsure) and how phrasing ("review these files in parallel" / "a separate review agent for each file") influences it. | Book pp. 14–15 — quoted | [E1] | High — entirely the book's; ties back to Chapter 6's independent-vs-dependent judgment. |
| q4 | d | The two levers — description (Claude reads it to decide when to delegate and to write the task prompt) and the system-prompt body (internal logic / output format) — plus the untrusted-definition security risk (a definition controls tools, permission mode, hooks, MCP, memory, and routing/prompting). | Book pp. 24–27, 30–32 | [E1] | High — the two-levers framing and the security concern are the book's (demonstrated on the Mermaid agent); the option/explanation reframe the book's "description appended to the main system prompt → hijack" to [E1]'s documented behavior (see Drift). The tool-pollution discipline is noted in the explanation. |
| q5 | c | How the Infinite Agentic Loop works (/infinite <spec_file> <output_dir> <count> → orchestrator → parallel subagents via the Agent tool → variations → human selection) and what the "infinite prompt" is (a high-order/meta prompt running spec analysis, directory reconnaissance, iteration strategy, parallel coordination). | Book pp. 39–44, 49–56 | [E7], [E10] | High — the command, the phases, and the meta-prompt framing are the book's; the explanation carries the corrected IndyDevDan/disler attribution and the community-not-official-feature framing (see Drift). |
| q6 | b | Synthesis: placing subagents in the multi-agent landscape (in-session delegation = orchestrator-workers; distinct from terminal instances, background agents / Agent view, agent teams [experimental, off by default], dynamic workflows, /batch) and judging the cost (~4× a chat per agent, ~15× multi-agent; fewer truly parallelizable parts than research). | Book pp. 35–36 (cost) + Chapter 6 bridge | [E2], [E3], [E6], [E7] | High — the one enrichment-grounded synthesis question. The token multipliers and the "value high enough" / "fewer parallelizable tasks than research" cautions are from [E6]; the orchestrator-workers name from [E7]; the surrounding landscape (Agent view, agent teams gating, /batch) from [E2]/[E3]. |
Drift / Corrections Applied
The book is largely current on this chapter's surface (verified against [E1]–[E10]). Most items below are places the lesson completes, renames, or softens the book. None reach the Chapter-5 magnitude.
2026-06-14 accuracy re-audit. An independent audit flagged five over-/under-statements about subagent context composition, invocation methods, the Ctrl+R/Cmd+R keyboard claim, the "description is appended to the main system prompt" implementation claim, and the source-boundary framing of the Infinite Agentic Loop / orchestrator-workers / token-cost numbers. All were verified against the current canonical docs ([E1] sub-agents, [E2] agents, agent-view, interactive-mode, cli-reference) and corrected across the lesson, quiz, this ledger, and the training-output mirror. The new rows below (marked 2026-06-14) record each. The book's original wording is preserved verbatim in extracted-chapters/ and is not edited.
| Item | Book position | Current / correct position | Lesson treatment |
|---|---|---|---|
| Infinite Agentic Loop attribution (CORRECTION) | Book names the creator "IndieDevDan" and signs off "Kudos to IndieDev.com" (extract pp. 36, 56). | The correct handle is IndyDevDan (GitHub disler), site agenticengineer.com, channel youtube.com/@indydevdan; the repo is github.com/disler/infinite-agentic-loop (MIT). It is a community pattern, not an official Anthropic feature — the book frames it as just "the implementation." | §6 uses the correct name/handle, explicitly flags the book's "IndieDevDan / IndieDev.com" misspelling, and labels the pattern as community / not-official with a "verify the exact command against current docs" caveat. q5's explanation carries the corrected attribution. |
The "Task tool" renamed to Agent (COMPLETION) | The book and the infinite.md command say the main agent spawns subagents using the "task tool" (extract pp. 52, 55). | Current Claude Code renamed it the Agent tool; Task remains an alias. | §7 says the subagents are spawned "via the Agent tool (the tool formerly called Task)." No book error — a rename completion. |
| Scope hierarchy is broader than two (COMPLETION) | Book teaches exactly two scopes — project .claude/agents/ and user ~/.claude/agents/ (extract pp. 5, 8). | Per [E1] the precedence is broader (managed settings > --agents flag > project > user > plugin); project wins over user on name collisions. | §1 teaches the two file directories the learner creates, and adds a one-line aside that organization-managed settings and plugins can also supply subagents, with project winning over user. |
| Frontmatter schema has grown (COMPLETION) | Book lists tools, skills, mcp, model, hooks, memory "and others," noting only name/description are required (extract p. 6) — fairly current. | Canonical [E1] also documents disallowedTools, permissionMode, maxTurns, mcpServers (canonical name vs the book's mcp), background, effort, isolation: worktree, color, initialPrompt — and the set grows between releases. | §1 names several of the additional fields and the further reading explicitly lists more, then links code.claude.com/docs/en/sub-agents for "the current, full schema; the set grows between releases" (soft wording per the project rule). |
tools is a genuine allowlist for subagents (CLARIFICATION) | Book is correct: "If this section is left empty, the subagent is granted access to all available tools" (extract p. 6) — and listing tools restricts to those. | Per [E1]: omit → inherits all; list → restricted to exactly those (plus a disallowedTools denylist). This is the opposite of a Skill's allowed-tools, which only pre-approves listed tools (a grant) without blocking the rest. | §1 keeps the book's correct allowlist statement and adds the explicit contrast with a Skill's allowed-tools (ties to the locked-in CLAUDE.md drift note about allowed-tools). |
model: inherit is the default (COMPLETION) | Book's first example uses model: inherit; the generated code-comedy-carl uses model: sonnet (extract pp. 3, 12) — both fine, but the book doesn't state the default. | Per [E1]: valid values are sonnet/opus/haiku/fable/a full model ID/inherit; omitting model defaults to inherit. | §1 states the valid values and that omitting model defaults to inherit. |
| Built-in subagents beyond general-purpose (COMPLETION) | Book mentions only the "general-purpose built-in agent" visible via /agents (extract p. 8). | Current Claude Code also ships read-only helpers Explore and Plan (plus other helpers). | §2 says /agents shows "the built-in agents Claude Code ships with (a general-purpose agent, plus read-only helpers like Explore and Plan)." |
| Invocation methods (SOFTENING / COMPLETION — expanded 2026-06-14) | Book demonstrates the natural-language path and says the agent "can also be invoked through a slash command" (extract p. 9). | Per [E1], invocation is a scale, not a fixed list: automatic delegation (description-driven); naming it in natural language; @-mention (requests a specific subagent for one task); and session-wide — claude --agent <name> or the agent setting make the whole main thread adopt that subagent, with --agents JSON for throwaway session-only definitions. /agents manages agents (it isn't how you fire a specific one at a task). | §3 presents the methods as a scale from "Claude decides" to "pin it for the session" (no fixed "three"), adds the session-wide --agent/agent/--agents methods, drops the "guarantees one run" wording, and softens the book's slash-command claim; the further reading notes /agents (manage) vs claude agents (the CLI background-session monitor) are different things. |
| Subagent context composition (CORRECTION — 2026-06-14) | Book/extract states the delegation prompt is "the only context the subagent receives" (extract pp. 17, 24: "the only context injected into the subagent"). | Per [E1] "what loads at startup": a subagent starts fresh (no prior conversation history, invoked skills, or files already read) and works from a delegation message Claude writes — but its initial context also includes its own system prompt + environment details, every level of the CLAUDE.md/memory hierarchy, a git-status snapshot, and any preloaded skills. The built-in Explore and Plan agents skip CLAUDE.md and git status. A forked subagent is the exception that inherits the parent conversation. | The frontmatter objective 4, §1's context bullet, §4's opening ("fresh ≠ empty" paragraph), Figure 7.A's labels/aria-label, and q1 (option + explanation) were reworded to replace "only the prompt / its only context" with the fresh-start-plus-what-loads framing, including the Explore/Plan and fork exceptions. |
| "Description appended to the main system prompt" (CORRECTION — 2026-06-14) | Book asserts an internal-implementation detail: "a description is appended to Claude Code's main agent system prompt" (extract p. 24) and bases its security warning on it — "Because the description is appended to the system prompt of Claude Code's main agent, a … definition from an untrusted source could include malicious instructions" (extract p. 27). | Current docs ([E1]) do not describe the description as appended to the main system prompt. They state Claude uses the description (with the user request and current context) to decide when to delegate, and composes the delegation message it hands the subagent. The full user message still goes to Claude; Claude writes the subagent's task prompt. | §5 Lever 1, Figure 7.B (visible text + aria-label), the §5 "untrusted definitions" paragraph, the common-pitfalls bullet, q4 (option + explanation), and the Figure-7.B ledger entry were reworded to "Claude reads the description to decide when to delegate and to write the task prompt." The security warning is kept but reframed: an untrusted subagent definition can influence routing, prompting, permissions, tools, hooks, MCP, memory, or instructions (a definition controls all of these) — not a proven "main-system-prompt hijack." |
| Ctrl+R/Cmd+R keyboard claim (CORRECTION — 2026-06-14) | An earlier draft of this chapter (not the book) claimed pressing Ctrl+R / Cmd+R "expands the agent view so you can watch a subagent's internal activity." | Per the interactive-mode and agent-view docs: in an interactive session, Ctrl+R is reverse command-history search; Ctrl+O toggles the transcript viewer (detailed tool usage/execution). To track in-session subagents, the /agents command has a Running tab (lists live/recently-finished subagents; open or stop them), and a subagent panel appears below the prompt. claude agents opens Agent View for background sessions — a separate surface — where Ctrl+R renames the selected background session. | §3's housekeeping note and the practical-exercise Part 2 step were rewritten to use Ctrl+O (transcript viewer) + the /agents Running tab, and to distinguish /agents from claude agents (where Ctrl+R renames). All "Ctrl+R/Cmd+R expand" wording removed from the lesson, exercise, this ledger, and the training-output mirror. |
| Source boundary: Infinite Loop / orchestrator-workers / token numbers (FRAMING — clarified 2026-06-14) | n/a — these are not Claude Code product docs. | The Infinite Agentic Loop is a community pattern ([E10], IndyDevDan/disler), the orchestrator-workers taxonomy is from Anthropic's engineering blog ([E7]), and the ~4×/~15× token-cost and ~90% eval figures are from Anthropic's engineering post ([E6]) reporting one internal evaluation. None are official Claude Code docs behavior. | These are cited only as clearly-labeled engineering/cookbook/community enrichment ([E6], [E7], [E9], [E10]) in §6–§7, the Further Reading, and the q5/q6 mappings — never under "[E1] docs" or as docs-verified Claude Code behavior. The training-output verification checklist was split so "verified against canonical docs" lists only Claude Code behaviors, with these enrichment items called out separately. Eval numbers carry soft "as reported / internal evaluation" wording. |
| Context window size (SOFTENING) | Book uses a "200K tokens max" worked example (extract pp. 18–19), while also noting models may have 1M/2M/10M-token windows. | Limits move with model generations. | The preface and §4 soften to "commonly around 200,000 tokens today, larger on some models" per the soft-wording rule, while preserving the book's worked growth illustration. |
| Canonical docs host (NOTE) | Book cites https://docs.claude.com/docs/en/sub-agents (extract p. 2) and https://code.claude.com/docs/en/sub-agents (extract p. 6). | The canonical host is code.claude.com; the docs.claude.com / docs.anthropic.com paths mirror/redirect. | The lesson and further reading cite code.claude.com throughout. |
| ReAct / "deep agents" aside & a non-canonical model id (NOTE, not a correction) | Book has a "Relationship to React Agents" section with a LangGraph create_react_agent snippet using the model id anthropic:claude-4-7-sonnet-latest (extract p. 7) — a non-canonical/likely-fictional id. | n/a — the snippet is illustrative; the model id is not a real canonical Claude id. | The lesson keeps only a light conceptual mention of the agents/deep-agents relationship in the preface and does not reproduce the broken model id or the snippet. Recorded here so a reviewer isn't misled by the extract. |
| Enrichment numbers are eval-specific (soft-wording) | n/a — these figures are not in the book. | The lesson cites Anthropic's internal evaluation: a multi-agent system outperformed single-agent by ~90% on their research eval; agents use ~4× a chat's tokens and multi-agent systems ~15×; subagents return ~1,000–2,000-token condensed summaries; the "attention budget" / context-rot framing. All drift with model generations. | Attributed to "Anthropic's internal evaluation, as reported" / "Anthropic's context-engineering write-up" per the soft-wording rule. Sources [E6]/[E7]/[E8]. |
Extraction caveat (image-only PDF)
source-pdfs/07-chapter-07.pdf is an image-only PDF — every page is a set of rendered images with no text layer (confirmed: pdftotext -layout and pypdf both returned 0 characters; the image-only check python -c "import pypdf; print(sum(len(p.extract_text() or '') for p in pypdf.PdfReader('source-pdfs/07-chapter-07.pdf').pages))" printed 0). Standard extraction was therefore impossible. The source-of-truth extracted-chapters/07-chapter-07.md was produced by rendering each of the 57 pages to PNG at 150 DPI (PyMuPDF / fitz) into work/07-chapter-07-pages/ and transcribing the images visually. Consequences a reviewer should know:
- Page markers are reliable (the renderer gave clean per-page boundaries), but printed book page numbers are unknown —
<!-- page N -->is the PDF page index, not the book's printed page. There is no.txtmirror for this chapter. - The book's figures are screenshots (terminal / editor / browser captures embedded as images, plus the two architecture diagrams in Figs 7.8 and 7.10). They are not transcribed pixel-for-pixel and not reproduced in the lesson (we have no rights, and they're bitmaps). Figure captions and the gist of each figure are preserved in the extract, marked "[Figure: …]". The page-44 six-variation list carries an explicit transcription-uncertainty note in the extract (small source text); the lesson's six variation names match it.
- The book's stale terms and the creator's misspelling are intentionally preserved verbatim in the extract — the extract retains "task tool," "IndieDevDan," and "Kudos to IndieDev.com" exactly as in the source. Do not edit
extracted-chapters/07-chapter-07.mdto match the lesson's corrections; it is the verbatim book source-of-truth and is supposed to retain the book's wording. The corrections live only in the lesson, the quiz, this ledger, and the training-output mirror. - Re-transcription, not OCR. No OCR engine (
tesseract) or PDF rasterizer (pdftoppm/ghostscript) was available locally; PyMuPDF was installed specifically to render the pages. If exact wording matters for a citation, cross-check against the printed book.
Source PDF: source-pdfs/07-chapter-07.pdf
Extracted source: extracted-chapters/07-chapter-07.md