Back to Blog

Claude Code Sub-Agents: Delegate, Specialize, and Scale Your Coding Workflows

Learn Claude Code's sub-agent system: built-in agents like Explore and Plan, custom specialists, routing tasks to cheaper models, and scaling complex projects.

Theo Marsh10 min read

#Why Sub-Agents Matter

When you ask Claude Code to build a feature, it often needs to do several things: explore the codebase, understand patterns, write code, and verify it works. All of that happens in one context window, which means exploration noise mixes with implementation work. As your conversation grows, context fills up and quality drops.

Sub-agents solve this by splitting work into separate context windows. Each sub-agent gets its own conversation, its own system prompt, and its own tool access. When it finishes, it returns results to the main session — keeping your primary context clean.

Think of it like delegation in a real team. You don't want your lead engineer also doing every grep search and log scan. You hand those tasks to specialists.


#Built-In Sub-Agents

Claude Code ships with several built-in sub-agents that fire automatically when appropriate. You don't need to configure anything — Claude decides when to delegate.

#Explore

Model: Haiku (fast, cheap) Tools: Read-only Purpose: Searching and analyzing codebases

When Claude needs to find a file, understand a pattern, or scan a directory structure, it delegates to Explore. This keeps search noise out of your main conversation.

Explore has three thoroughness levels:

  • Quick — targeted lookups ("find the auth middleware file")
  • Medium — balanced exploration ("how is error handling done across the API layer")
  • Very thorough — comprehensive analysis ("map all the data flow from input to database")

#Plan

Model: Inherits from main session Tools: Read-only Purpose: Research before presenting a plan

When you're in plan mode and ask Claude to make changes, it sends Plan out to gather context before presenting its approach. This prevents the main session from filling up with research artifacts.

#General-Purpose

Model: Inherits from main session Tools: All tools Purpose: Complex multi-step tasks

For work that needs both exploration and action — research a problem, then implement a fix — Claude delegates to General-Purpose. It has full tool access and can make changes.

#Other Built-Ins

AgentModelPurpose
BashInheritsTerminal commands in separate context
Claude Code GuideHaikuAnswering questions about Claude Code itself
statusline-setupSonnetConfiguring your terminal status line

Want step-by-step guides for this and more?

ClawDocx Pro includes 500+ curated prompts, setup guides, SKILL.md files, and templates — everything to make your AI agent unstoppable.

See plans & pricing

#Creating Custom Sub-Agents

The real power is building your own. Custom sub-agents let you:

  • Lock down tools — a reviewer that can only read, never write
  • Route to cheaper models — send simple tasks to Haiku instead of Opus
  • Enforce patterns — a sub-agent that always follows your team's code style
  • Specialize prompts — domain-specific instructions for testing, security, docs

#Quickstart: The /agents Command

The fastest way to create a sub-agent:

bash
# In a Claude Code session
/agents

Select "Create new agent" and follow the prompts. Claude Code generates the Markdown definition file for you.

#Manual Creation

Sub-agents are Markdown files with YAML frontmatter. Place them in:

  • User-level: ~/.claude/agents/my-agent.md (available in all projects)
  • Project-level: .claude/agents/my-agent.md (available in this repo only)

Here's a complete example — a security reviewer:

markdown
---
name: security-reviewer
description: Reviews code changes for security vulnerabilities, auth issues, and data exposure risks
model: sonnet
tools:
- Read
- Bash
deny_tools:
- Write
- Edit
---
You are a security-focused code reviewer. When given code to review, check for:
1. **Injection vulnerabilities** — SQL injection, XSS, command injection
2. **Authentication/authorization gaps** — missing auth checks, privilege escalation
3. **Data exposure** — secrets in code, PII logging, missing encryption
4. **Input validation** — unsanitized user input, missing bounds checks
5. **Dependency risks** — known CVEs in imports
Format your review as:
- 🔴 **Critical** — must fix before merge
- 🟡 **Warning** — should fix, potential risk
- 🟢 **Note** — suggestion for improvement
Be specific. Reference file paths and line numbers.

#Key Frontmatter Fields

FieldWhat It DoesExample
nameIdentifier Claude uses to delegatesecurity-reviewer
descriptionHow Claude decides when to use this agentReviews code for security issues
modelWhich model to use (opus, sonnet, haiku)haiku
toolsAllowlist of tools (empty = all tools)[Read, Bash]
deny_toolsBlocklist of tools[Write, Edit]
permissionsPermission mode (default, auto-accept)auto-accept
backgroundRun in background (don't block main session)true
isolationGit isolation modeworktree

#Practical Sub-Agent Recipes

#Test Runner (Cheap & Fast)

markdown
---
name: test-runner
description: Runs tests and reports results. Use for checking test suites after changes.
model: haiku
tools:
- Read
- Bash
deny_tools:
- Write
- Edit
---
Run the test suite and report results concisely:
- Total tests, passed, failed, skipped
- For failures: file path, test name, error message, and likely cause
- Suggest fixes if the cause is obvious
Do not modify any files. Report only.

#Documentation Writer

markdown
---
name: doc-writer
description: Writes and updates documentation for code changes
model: sonnet
tools:
- Read
- Write
- Edit
deny_tools:
- Bash
---
You write clear, accurate documentation. When asked to document code:
1. Read the code thoroughly before writing
2. Write for developers who are new to the codebase
3. Include usage examples with realistic inputs
4. Document edge cases and error conditions
5. Follow JSDoc/TSDoc format for inline docs
6. Keep README updates concise and scannable

#Commit Message Generator

markdown
---
name: commit-gen
description: Generates conventional commit messages from staged changes
model: haiku
tools:
- Bash
- Read
deny_tools:
- Write
- Edit
---
Generate a commit message following Conventional Commits format:
1. Run `git diff --staged` to see changes
2. Categorize: feat, fix, docs, style, refactor, test, chore
3. Write a concise subject line (< 72 chars)
4. Add body with bullet points for significant changes
5. Reference issue numbers if mentioned in the code
Output ONLY the commit message, nothing else.

#Sub-Agent Patterns

#Cost Optimization: Route by Complexity

Use model in your agent definitions to send simple tasks to cheaper models:

  • Haiku ($) → file search, test running, log scanning, simple formatting
  • Sonnet ($$) → code review, documentation, refactoring
  • Opus ($$$) → architecture decisions, complex debugging, security audits

Claude decides which agent to delegate to based on the description field. Write descriptions that clearly match the task complexity.

#Background Agents

Add background: true to run agents without blocking your main session:

markdown
---
name: background-linter
description: Runs comprehensive lint checks in the background
background: true
model: haiku
---

Background agents run independently. Use Ctrl+F to list and kill them.

#Worktree Isolation

For agents that make changes, isolation: worktree creates a temporary git worktree so changes don't affect your working branch:

markdown
---
name: experimental-refactor
description: Tries experimental refactoring approaches in an isolated branch
isolation: worktree
---

The worktree is cleaned up when the sub-agent finishes. If you like the changes, they're on a branch you can merge.

#Persistent Memory

Sub-agents can maintain their own auto-memory across sessions:

markdown
---
name: project-expert
description: Deep knowledge of this project's architecture and conventions
auto_memory: true
---

Over time, this agent builds up project-specific knowledge that persists between sessions.


#Sub-Agents vs Agent Teams

This is a common point of confusion. Here's the distinction:

Sub-AgentsAgent Teams
CommunicationReport back to main session onlyTalk to each other directly
CoordinationMain session manages everythingShared task list, self-organizing
ScopeSingle sessionMultiple parallel sessions
Best forDelegating specific tasksParallel work on large features
OverheadLowHigh (more tokens, coordination cost)

Rule of thumb: If the tasks are independent (review this, run those tests, write that doc), use sub-agents. If the tasks need coordination (frontend + backend + tests for one feature), consider agent teams.


#Tips for OpenClaw Users

When running Claude Code through OpenClaw's ACP integration:

  • Sub-agents run inside the Claude Code session — they're invisible to OpenClaw's session management
  • If you need OpenClaw-visible delegation, use OpenClaw's own sub-agent system (sessions_spawn) instead
  • For complex workflows: use OpenClaw for orchestration (which repo, which branch, what to build) and Claude Code sub-agents for internal task splitting (explore, implement, test)

The two delegation systems are complementary, not competing.


#Getting Started

  1. Start with the built-in agents — they work out of the box
  2. Create one custom agent for your most repetitive task (testing, linting, docs)
  3. Route cheap tasks to Haiku to save costs
  4. Add background: true for non-blocking agents
  5. Use isolation: worktree for risky experiments

Sub-agents are how Claude Code scales from "helpful assistant" to "autonomous development team." Start small, see what sticks, and build up.


For advanced sub-agent configurations, multi-project setups, and team-wide agent libraries, check out the premium guides on ClawDocx.

Get the full experience with ClawDocx Pro

Access 500+ prompts, step-by-step guides, SKILL.md files, and more. Everything you need to master OpenClaw.

Start Free Trial

Related Posts