Module 6: Subagents: delegating work to specialized agents
Built-in Subagents: Claude Code's specialized agents
Built-in Subagents: Claude Code's specialized agents
Overview
Claude Code isn't a single agent — it's a main agent that can spawn specialized child agents to delegate work. These built-in subagents ship with the tool and need no configuration: general-purpose (full execution of subtasks), Explore (read-only analysis), Plan (design without execution), statusline-setup (status line configuration), and claude-code-guide (Claude Code documentation).
Each subagent has a distinct profile: allowed tools, speed, analysis depth, and output type. Knowing when to use each one — and when to let Claude Code fire them automatically — is the difference between wasting your context window and using it surgically.
This capsule covers all 5 built-in subagents in depth: what they do, how they work internally, when they activate, and how to ask for them explicitly. With practical examples you can replicate in your own project.
What a subagent is
A subagent is a lightweight agent instance that Claude Code creates to handle a subtask. It isn't a separate process or an external server — it's an agent that operates inside the same Claude Code session but with its own context and restrictions.
Anatomy of a subagent
┌──────────────────────────────────────────────────────────┐
│ MAIN AGENT (Parent) │
│ │
│ Context window: [your conversation + project] │
│ Tools: Read, Write, Execute, Search, Glob, etc. │
│ │
│ ┌────────────────────────────────────────────────────┐ │
│ │ SUBAGENT (Child) │ │
│ │ │ │
│ │ Own context: [instruction + files it read] │ │
│ │ Tools: [subset of the parent's] │ │
│ │ Output: compact result → returned to the parent │ │
│ └────────────────────────────────────────────────────┘ │
│ │
└──────────────────────────────────────────────────────────┘
Traits every subagent shares
- Isolated context: Every subagent has its own context window. It doesn't share the parent's context directly — it receives an instruction and works from that.
- Restricted tools: Subagents get a subset of the parent's tools. An Explore subagent can't write files. A statusline-setup subagent can only read and edit.
- Compact output: The subagent returns a summarized result to the parent. The parent doesn't receive everything the subagent read — it receives the conclusion.
- Ephemeral lifecycle: Subagents are created for a task, they run it, they return the result, and they're destroyed. They don't persist between invocations.
- Shared project: Even though context is isolated, subagents operate on the same project. If a subagent writes a file, the parent will see it.
Subagent context
Every subagent gets its own context window. That means:
- Subagents do NOT share context with the main agent
- You have to include all the relevant information in the subagent's prompt
- The subagent's result is returned as a message to the main agent
- The main agent does NOT see the intermediate tools the subagent used
The 5 built-in subagents
1. Explore subagent
The Explore subagent is a read-only agent optimized for code analysis. Its purpose is to read, search, understand — without modifying anything.
Technical profile
| Property | Value |
|---|---|
| Mode | Read-only |
| Available tools | Glob, Grep, Read (NOT Edit, Write, or Agent) |
| Unavailable tools | Edit, Write, Bash, Agent |
| Speed | Fast (model optimized for reading) |
| When it fires | Codebase analysis, pattern search, understanding architecture |
What it can do
- Read project files
- Search for patterns in the code (grep, semantic search)
- Analyze the directory structure
- Identify dependencies between modules
- Map the project's architecture
What it can NOT do
- Write or modify files
- Run terminal commands
- Install dependencies
- Create new files
Basic example
You: Analyze every test file in the project. What framework
is used? What's the naming convention? Are unit and
integration tests kept separate?
Claude Code automatically creates an Explore subagent that:
- Searches for
*.test.*,*.spec.*,__tests__/files - Reads test samples to identify the framework
- Analyzes the test directory structure
- Returns a summary to the parent, something like:
Explore subagent summary:
- Framework: Vitest (found vitest.config.ts)
- Naming: [name].test.ts for unit, [name].integration.test.ts for integration
- Structure: unit tests colocated with modules, integration tests in __tests__/integration/
- Coverage: 47 test files, 12 modules with no tests
- Patterns: describe/it with factories in __tests__/factories/
The parent receives this compact summary — not the 47 full files. That's the efficiency of the model.
Intermediate example
You: Before refactoring the authentication module, I need to
understand every dependency. What other modules import
from auth/? What interfaces does it expose?
The Explore subagent analyzes:
- Every import that references
auth/ - The interfaces and types exported from
auth/ - The modules that depend on it transitively
- Returns a dependency graph in text
Dependencies of auth/:
├── auth/index.ts exports: AuthService, AuthMiddleware, UserSession (type)
├── Imported by:
│ ├── routes/api.ts → uses AuthMiddleware
│ ├── routes/admin.ts → uses AuthMiddleware, AuthService
│ ├── services/user.ts → uses AuthService, UserSession
│ ├── services/payment.ts → uses AuthService (verification only)
│ └── middleware/cors.ts → uses UserSession (type only)
└── Internal dependencies of auth/:
├── auth/jwt.ts → jsonwebtoken, config/secrets
├── auth/session.ts → redis, auth/jwt
└── auth/middleware.ts → auth/session, auth/jwt
With this map, you can refactor confidently, knowing exactly what gets affected.
2. Plan subagent
The Plan subagent designs solutions without executing them. It's the /plan mode you already know from Module 04, but here you get to understand it as a subagent.
Technical profile
| Property | Value |
|---|---|
| Mode | Read-only + reasoning |
| Available tools | Glob, Grep, Read (NOT Edit, Write, or Agent) |
| Unavailable tools | Edit, Write, Bash, Agent |
| Speed | Moderate (deep reasoning) |
| When it fires | Feature design, migration planning, architecture decisions |
What it can do
- Read existing code to inform the plan
- Analyze trade-offs between options
- Produce step-by-step implementation plans
- Identify risks and dependencies
- Propose architecture without implementing it
What it can NOT do
- Write files
- Run commands
- Implement the plan it designs
Basic example
You: /plan Design the migration from Express to Fastify.
Don't implement anything yet.
The Plan subagent produces:
Express → Fastify migration plan
Phase 1: Preparation (nothing breaks)
1. Install fastify and @fastify/cors, @fastify/jwt
2. Create fastify-app.ts alongside express-app.ts
3. Migrate config/server.ts to support both
Phase 2: Route migration (one at a time)
4. Build an Express → Fastify middleware adapter
5. Migrate routes in order: health → auth → users → products
6. For each route: migrate + test + verify
Phase 3: Middleware migration
7. Rewrite auth middleware as Fastify hooks
8. Rewrite the error handler as a Fastify error handler
9. Rewrite validation (Joi → Fastify schema validation)
Phase 4: Cleanup
10. Remove express-app.ts and the Express dependencies
11. Update the CI/CD config
12. Run the full test suite
Risks identified:
- Custom middleware that uses Express req/res directly
- Integration tests that import the Express app
- 3 dependencies that rely on Express types
Estimate: 4-6 Claude Code sessions
Intermediate example
You: /plan I need to add multi-language support to the app.
Analyze the options (i18next, react-intl, custom) and
recommend one with justification.
The Plan subagent reads the project structure, analyzes the existing dependencies, and produces a plan with a comparison of options, a reasoned recommendation, and implementation steps.
3. General-purpose subagent
The General-purpose subagent has full execution capability. Claude Code uses it when it needs to delegate a task that requires reading, reasoning, and potentially taking action.
Technical profile
| Property | Value |
|---|---|
| Mode | Full execution (within the parent's restrictions) |
| Available tools | ALL tools (Bash, Read, Write, Edit, Glob, Grep, Agent, etc.) |
| Speed | Variable (depends on task complexity) |
| When it fires | Complex delegated tasks, deep analysis with reasoning |
What it can do
- Everything Explore can do (read, search, analyze)
- Deep reasoning about complex problems
- Potentially write files (if the parent allows it)
- Execute sequences of actions to complete a task
Basic example
You: Find every TODO comment in the project, classify them
by priority (critical, important, nice-to-have), and
give me a summary.
Claude Code delegates to a General-purpose subagent that:
- Searches for every
TODO,FIXME,HACK,XXXin the project - Reads the context around each one to classify it
- Produces an organized report:
Project TODOs (43 found):
CRITICAL (5):
- src/auth/jwt.ts:45 TODO: tokens aren't invalidated on logout
- src/db/migration.ts:12 FIXME: race condition in concurrent migration
- src/api/payment.ts:89 HACK: hardcoded API key (should move to env)
- ...
IMPORTANT (15):
- src/services/user.ts:23 TODO: add email validation
- ...
NICE-TO-HAVE (23):
- src/utils/format.ts:7 TODO: support more date formats
- ...
Intermediate example
You: I need to understand how data flows from a user logging
in to the moment they get the dashboard.
Trace the full flow.
The General-purpose subagent follows the flow across multiple files:
Login → dashboard flow:
1. POST /api/auth/login (routes/auth.ts:34)
→ Receives { email, password }
→ Calls AuthService.login()
2. AuthService.login (services/auth.ts:67)
→ UserRepository.findByEmail()
→ bcrypt.compare(password, hash)
→ JWTService.createToken({ userId, role })
→ SessionStore.create(userId, token)
→ Return { token, refreshToken }
3. Redirect to /dashboard (client/router.tsx:23)
→ AuthGuard checks the token in localStorage
→ GET /api/dashboard (routes/dashboard.ts:12)
4. DashboardController.getData (controllers/dashboard.ts:8)
→ UserService.getProfile(userId from token)
→ StatsService.getUserStats(userId)
→ NotificationService.getUnread(userId)
→ Return { profile, stats, notifications }
5. Dashboard.tsx renders with the data
4. statusline-setup subagent
The statusline-setup subagent specializes in configuring Claude Code's status line settings. It's a very narrow subagent with limited access.
Technical profile
| Property | Value |
|---|---|
| Mode | Configuration |
| Available tools | Read, Edit |
| Unavailable tools | Bash, Write, Glob, Grep, Agent |
| Speed | Fast |
| When it fires | When the status line needs to be configured or adjusted |
Example
Claude Code fires this subagent internally when it needs to
adjust the status line configuration. It's an internal support
subagent — you rarely invoke it directly.
5. claude-code-guide subagent
The claude-code-guide subagent is a documentation agent that answers questions about Claude Code features: hooks, MCP, settings, IDE integrations, and more.
Technical profile
| Property | Value |
|---|---|
| Mode | Documentation lookup |
| Available tools | Glob, Grep, Read, WebFetch, WebSearch |
| Unavailable tools | Bash, Write, Edit, Agent |
| Speed | Fast |
| When it fires | Questions about how to use Claude Code, its features, its configuration |
Example
You: How do I configure hooks in Claude Code?
Claude Code can delegate to claude-code-guide, which searches the
official documentation and returns a precise answer about hook
configuration.
When Claude Code creates subagents automatically
Claude Code doesn't always wait for you to ask for a subagent. In several scenarios, it creates them on its own:
Scenario 1: Tasks that require broad exploration
When you ask for something that requires reading many files, Claude Code creates an Explore subagent instead of loading every file into the main context window:
You: How is the payments module organized?
Claude Code detects that it needs to explore the payments/ directory with its many files and creates an Explore subagent. The subagent reads the files and returns a summary, keeping the main context clean.
Scenario 2: Parallelizable tasks
When a task has independent components, Claude Code can create multiple subagents in parallel:
You: Analyze code quality in the auth, payments, and
notifications modules.
Claude Code creates 3 Explore subagents in parallel — one per module. Each analyzes its module and returns results. The parent integrates the 3 analyses into a coherent response.
Scenario 3: Separating analysis from implementation
When Claude Code needs to understand before implementing, it uses an Explore subagent first:
You: Add pagination to the products endpoint.
Internally:
- Explore subagent → analyzes how the current endpoints are implemented
- Parent → uses the analysis to implement pagination consistently
When they are NOT created automatically
- Trivial tasks ("rename this variable")
- When the context already has the information it needs
- Direct questions that don't require exploration
- When the context window has plenty of room left
How to ask for subagents explicitly
You don't always have to wait for Claude Code to decide. You can ask for them directly:
Ask for explicit exploration
You: Use an exploration subagent to analyze every config file
in the project. I want to know which environment variables
are used and where.
Ask for an explicit plan
You: /plan Before implementing, use plan mode to design the
complete solution.
Ask for explicit delegation
You: Delegate the following tasks to subagents in parallel:
1. Analyze the existing tests
2. Find every endpoint without validation
3. Verify that every route has auth middleware
Keywords that trigger subagents
Certain words in your prompts make it more likely that Claude Code will use subagents:
| Keyword/phrase | Likely subagent |
|---|---|
| "analyze", "explore", "investigate" | Explore |
| "design", "plan", "propose" | Plan |
| "find every", "classify", "trace" | General-purpose |
| "run", "execute", "verify" | General-purpose |
| "in parallel", "simultaneously" | Multiple subagents |
Comparisons and decisions
When to use each subagent
┌──────────────────────────────────────────────────────────────┐
│ DECISION TREE │
│ │
│ Do you need to modify files or run commands? │
│ ├── NO → Do you need deep reasoning? │
│ │ ├── NO → EXPLORE subagent │
│ │ └── YES → PLAN subagent │
│ └── YES → Is it a delegable subtask? │
│ ├── YES → GENERAL-PURPOSE subagent │
│ └── NO → Main agent (no subagent) │
│ │
└──────────────────────────────────────────────────────────────┘
Explore vs General-purpose for analysis
| Criterion | Explore | General-purpose |
|---|---|---|
| Speed | Faster | Slower |
| Depth | Search + read | Reasoning + analysis |
| Output | Data found | Data + interpretation |
| Context usage | Efficient | Heavier consumption |
| Example | "Which files import lodash?" | "Is it safe to drop lodash from the project?" |
Rule: If you need data → Explore. If you need analysis of the data → General-purpose.
Plan subagent vs giving instructions to the parent
| Criterion | Plan subagent | Direct instruction |
|---|---|---|
| Complexity | Complex features, migrations | Targeted changes |
| Risk | High (touches multiple files) | Low (1-2 files) |
| Decisions | Multiple options with trade-offs | Obvious solution |
| Example | "Design the cache system" | "Add cache to this endpoint" |
Rule: If there are design decisions to make → Plan. If the implementation is straightforward → instruct the parent.
Common patterns
Pattern 1: Explore → Plan → Code (with explicit subagents)
The Module 04 workflow, now with the awareness that these are subagents:
Step 1 (Explore subagent):
You: Explore the notifications module. What kinds of
notifications exist? How are they sent? Is there a
queue or is it synchronous?
Step 2 (Plan subagent):
You: /plan With that analysis, design support for push
notifications. Give me options and trade-offs.
Step 3 (Parent agent):
You: Implement option 2 from the plan. Start with the
push notifications service.
Pattern 2: Parallel analysis
When you need to analyze several independent areas:
You: Analyze in parallel:
1. The database structure (models, relationships)
2. Test coverage (which modules have tests, which don't)
3. External dependencies (which packages, which versions)
Give me a consolidated summary of all three analyses.
Claude Code creates 3 subagents, runs them concurrently, and integrates the results.
Pattern 3: Subtask delegation
When you're implementing something complex and you need a subagent to handle a piece of it:
You: Implement the product search endpoint.
But first, delegate to a subagent that analyzes how
the other endpoints are implemented, so we stay
consistent.
Pattern 4: Post-implementation verification
After implementing, use subagents to verify:
You: You just implemented the cache module. Now:
1. Use a subagent to verify you didn't break any tests
2. Use another to verify the implementation follows
the project's conventions
Advanced subagent capabilities
Isolation with worktrees
Subagents can run in an isolated worktree — a temporary copy of the repository:
- Use
isolation: "worktree"when launching the subagent - The subagent works in a separate copy of the repo
- If it makes no changes, the worktree is cleaned up automatically
- If it does make changes, you get back the worktree path and branch
- Useful for: destructive exploration, refactoring trials, experimental changes
Continuing an existing subagent
If you need to keep working with a subagent that already finished a task, you can use SendMessage with the agent's ID or name. The subagent resumes with all of its context preserved.
This is useful when the subagent's result needs refinement, or when you want to give it extra tasks without starting from scratch.
Background execution
Subagents can run in the background with run_in_background: true. When an agent runs in the background:
- You get an automatic notification when it completes
- You do NOT need to poll or sleep
- You can keep working on other things while the subagent works
- Ideal for: long research tasks, extensive searches, parallel builds
Pitfalls and edge cases
Pitfall 1: Over-delegation
Not everything needs a subagent. If the task is simple, a subagent adds overhead with no benefit:
❌ "Use a subagent to read the package.json file"
✅ "What version of React does the project use?" (Claude reads it directly)
Rule: If the task means reading 1-3 files and doesn't need deep reasoning, the parent can just do it.
Pitfall 2: A subagent without enough context
Subagents receive an instruction, but not your full history. If your instruction depends on prior context, the subagent won't have it:
❌ "Analyze the problem I mentioned earlier"
✅ "Analyze the bug in src/auth/login.ts where the token
isn't invalidated on logout"
Rule: Make your instructions to subagents self-contained.
Pitfall 3: Expecting subagents to share state
Subagents don't share context with each other. If you create 3 subagents in parallel, each one operates independently:
❌ Expecting subagent 2 to use information from subagent 1
✅ The parent integrates results from all 3 subagents
Pitfall 4: Subagents for tasks that need iteration
Subagents are best-effort in a single run. If the task requires iteration (try something, see if it works, adjust), the parent should handle it:
❌ "Delegate to a subagent to debug the production error"
✅ Debug directly with the parent, iterating
Edge case: Write conflicts
If two subagents try to write to the same file (something Claude Code normally prevents), there's a resolution mechanism: the parent serializes the writes.
Edge case: A subagent that fails
If a subagent can't complete the task (e.g. it can't find the files, the search returns nothing), it returns the partial result to the parent. The parent decides whether to retry with different instructions or handle the case manually.
Complete worked example
Scenario: Adding a new reports module
You have a Node.js project with Express and PostgreSQL. You need to add a reports module that generates sales reports.
Step 1: Exploration
You: Before implementing the reports module, I need to
understand the structure. Analyze:
1. How the existing modules are organized (structure)
2. What SQL queries are used to access sales
3. Whether any endpoint already generates similar data
Claude Code creates Explore subagents:
Analysis result:
Module structure:
src/
├── controllers/ → one controller per domain
├── services/ → business logic
├── repositories/ → data access (Knex)
├── routes/ → Express routers
└── types/ → TypeScript interfaces
Sales queries:
- repositories/sale.ts has findAll, findById, findByDateRange
- findByDateRange takes {from, to} and returns Sale[]
- No aggregations (SUM, COUNT, GROUP BY)
Similar endpoints:
- GET /api/sales/summary → returns count and total for the current month
- No reports by date range or by category
Step 2: Planning
You: /plan With that analysis, design the reports module.
I need sales reports by date range, by category, and
a dashboard with key metrics.
The Plan subagent produces a detailed 8-step plan.
Step 3: Implementation with verification
You: Implement steps 1-3 of the plan (repository, service,
types). After implementing, verify that it compiles and
that the existing tests still pass.
Claude Code implements and verifies:
tsc --noEmit && npm test
Result: compilation OK, 47/47 tests pass.
Step 4: Continue the implementation
You: Implement steps 4-6 (controller, routes, validation).
Include tests for the new endpoints.
The main agent implements, writes tests, and verifies: 52/52 tests.
Practice exercises
Exercise 1: Directed exploration
Open Claude Code in your project and run:
Analyze my project's structure using an exploration
subagent. I want to know:
1. How many files there are by type (ts, js, json, md)
2. Which directories are the largest
3. Whether there are files that don't fit any clear pattern
What to expect
Claude Code will create an Explore subagent that:
- Uses Glob to count files by extension
- Analyzes the directory structure
- Identifies "orphan" files that don't follow conventions
The result should be a structured summary with concrete numbers. If Claude doesn't explicitly create a subagent, it still uses the exploration tools internally — the result should be similar.
Exercise 2: A plan for a new feature
/plan Design how you'd add a caching system to my
project. Evaluate the options: in-memory (node-cache),
Redis, or file-based. Recommend one with justification
based on the project's current structure.
What to expect
The Plan subagent should:
- Read the project structure to understand the stack
- Evaluate the 3 options with pros/cons
- Recommend one based on the real context (e.g. if you already use Redis for sessions, recommend Redis; if it's a small project, recommend in-memory)
- Produce a 4-6 step implementation plan
If it doesn't explore your project before planning, ask it to: "First analyze my project and then plan."
Exercise 3: Parallel analysis
Analyze these three areas of my project in parallel:
1. Dependencies: which packages are used and whether any are outdated
2. Tests: which modules have tests and which don't
3. Security: are there hardcoded secrets, security TODOs,
or vulnerable dependencies?
Give me a consolidated report.
What to expect
Claude Code should create multiple subagents (or at least parallelize internally). The result should have three clear sections with findings specific to your project. If it doesn't parallelize, the results will be sequential but just as valid.
Bonus: if Claude Code runs npm audit as part of the security analysis, that tells you it used a general-purpose subagent with Bash access.
Exercise 4: The full Explore → Plan → Code workflow
Pick a small improvement for your project (e.g. add validation to an endpoint, improve error handling). Run the full cycle deliberately:
Step 1: Explore how [X] is currently handled in the project.
Step 2: /plan Design how to improve [X].
Step 3: Implement the plan.
Step 4: Verify that everything compiles and the tests pass.
What to expect
This exercise should take 10-15 minutes. At each step, notice:
- Did Claude Code create a subagent? Which type?
- Did the parent's context stay clean?
- Was the plan informed by the exploration?
The value of the exercise is experiencing the full cycle while being conscious of which subagent operates in each phase.
Exercise 5: Explicit delegation
I want you to delegate the following task to a subagent:
"Find every async function in the project that has no
error handling (try/catch or .catch()). List each one
with its file and line."
What to expect
Claude Code should create a subagent that:
- Searches for
asyncfunctions in the project - Analyzes which ones have try/catch and which don't
- Returns a list with locations
This is a simplified static-analysis exercise. Don't expect 100% precision — text-search-based analysis doesn't cover every edge case (e.g. error handling in a wrapper further up).
Summary
Built-in subagents are the main delegation mechanism in Claude Code. You don't need to configure anything to use them — they ship with the tool and Claude Code fires them based on the task.
What you learned in this capsule:
- There are 5 built-in subagents: general-purpose (full execution), Explore (read-only), Plan (design), statusline-setup (configuration), claude-code-guide (documentation)
- Each subagent has restricted tools and isolated context
- Claude Code creates subagents automatically when it detects parallelizable tasks or tasks that need broad exploration
- You can ask for subagents explicitly with direct instructions
- Subagents return compact results to the parent, keeping the context window clean
- The core pattern is Explore → Plan → Code, now understood as a sequence of subagents
- Don't over-delegate: if the task is simple, the parent can just do it
Next capsule: 03 - Custom subagents — how to build your own specialized agents with instructions, tools, and restrictions that you define.
Additional resources
Official documentation
- Sub-agents — Subagent types, configuration, and behavior
- Best Practices — Workflows and context management with subagents
- CLI Reference — Available commands and modes
Patterns and workflows
- Interactive Mode — Task management and delegation
- Plugins Reference — Skills, agents, hooks: how they interact