Subagents and Automation in Claude Code
AI generated
Claude
>_
Claude Code · Subagents · Automation · Multi-Agent Workflow
Subagents and Automation in Claude Code
Isolated agent contexts for complex multi-step work

Subagents delegate focused subtasks to a separate Claude Code context with its own context window and its own system prompt. This helps with parallel codebase research and isolated review passes, but it adds coordination overhead that is not worth it for simple tasks, where a single agent often remains the better choice.

17 min. read Subagents · Parallelization · Code Review · Orchestration Claude Code · Claude Sonnet 5 · Anthropic

1. What a subagent technically is

A subagent in Claude Code is a standalone agent instance with its own context window, its own system prompt, and a restricted set of tools. The main agent delegates a clearly scoped subtask to the subagent, waits for its result, and then continues working with a compact summary rather than the full history of the subtask. This is what fundamentally distinguishes a subagent from a plain function: a subagent makes its own decisions, invokes tools independently, and can iterate before returning a result.

Technically, a subagent runs in the same Claude Code process but keeps a separate conversation history. That means files the subagent reads, search results it sifts through, and intermediate steps it tries do not consume the main agent's context window. Only what the subagent explicitly reports back as a result flows into the main context. This separation is the central technical mechanism that all the practical benefits of subagents build on.

2. Why isolated context windows solve the real problem

A language model's context window is a limited resource, and it fills up faster than expected during complex multi-step work. Reading ten files, running three test passes, and holding a long discussion about architecture decisions all inside a single agent context drains capacity that the actual task needs. Models also tend to become less precise in very long, cluttered contexts, because relevant information gets buried among irrelevant intermediate steps.

A subagent deliberately cuts this chain short. A research task like "find every place a specific legacy interface is used" can read dozens of files and still return just three sentences of result to the main agent. That keeps the main agent focused on the actual decision: what to do with that result. This isolation is especially valuable for exploratory tasks whose outcome is not known upfront and that potentially generate a lot of "noise" before arriving at a clear result.


# Example: main agent delegates an exploratory codebase question
# to a subagent instead of reading dozens of files itself

# Only this request stays visible in the main context:
"Find all controller classes that still use the old
ObjectManager::create() pattern instead of constructor
injection, and list the file paths."

# The subagent searches independently:
#   - app/code/**/*.php
#   - reads candidate files in full
#   - filters false positives (comments, tests)
#
# Result in the main context: only the final file list,
# not the dozens of files read along the way

3. Parallel research across a large codebase

The classic use case for subagents is parallel research across multiple independent areas of a codebase. For a Magento module with frontend templates, backend models, and a JavaScript component, three subagents can run at once: one analyzes the phtml templates for accessibility issues, one checks the PHP classes for PHPStan violations, and a third scans the Alpine.js components for inconsistent event naming. Because the three areas have no dependencies on each other, parallelization saves real wall-clock time, not just organizational overhead.

What matters is that the subtasks are truly independent. As soon as one subagent needs another's result before it can do meaningful work, the parallelization benefit evaporates and coordination overhead climbs without a payoff. In practice, the rule of thumb that works well is to split research tasks along file or module boundaries rather than along topics that overlap. Good task decomposition means each subagent can deliver its result independently without waiting on another.


{
  "task_group": "module_audit",
  "subagents": [
    {
      "name": "template-review",
      "scope": "app/design/frontend/**/*.phtml",
      "goal": "Check accessibility and CSP-compliant inline scripts",
      "tools": ["Read", "Grep"]
    },
    {
      "name": "phpstan-scan",
      "scope": "app/code/Mironsoft/**/*.php",
      "goal": "Identify and categorize PHPStan level 5 violations",
      "tools": ["Read", "Bash"]
    },
    {
      "name": "alpine-consistency",
      "scope": "app/design/frontend/**/web/js/**/*.js",
      "goal": "Check event naming conventions across Alpine components",
      "tools": ["Read", "Grep"]
    }
  ],
  "note": "All three subagents are independent and can run in parallel"
}

4. Isolated code review passes as a subagent pattern

A second well-established use case is the isolated review pass. When the same agent that wrote code also reviews it, it tends to repeat its own assumptions and blind spots, because its context is already saturated with implementation logic. A subagent that starts without that prior knowledge and sees only the finished diff evaluates the code closer to the perspective of a genuine reviewer who does not know its history.

In practice this means: the main agent implements a change, does not commit it right away, and instead starts a subagent with the sole task of critically reviewing the diff, watching for edge cases, security issues, and deviations from project conventions. That subagent gets no access to the prior conversation, only the diff and relevant project rules such as CLAUDE.md. That forces a genuine second perspective instead of a mere rubber stamp on the agent's own work.


# Typical flow: implementation and review as separate subagent roles

# 1. Main agent implements the feature and produces a diff
git diff --staged > /tmp/pending-change.diff

# 2. A fresh subagent gets ONLY the diff and project rules,
#    no knowledge of the prior implementation conversation.
#    Task: "Review this diff for security issues,
#    missing PHPDoc blocks, and violations of CLAUDE.md."

# 3. Result: a list of concrete findings, not a blanket approval
#    - missing @throws annotation on line 42
#    - addFieldToFilter() with int instead of ['eq' => $value] array form

# 4. Main agent decides which findings to fix before committing

5. Configuring subagents: markdown definitions and tool scope

Subagents are defined in Claude Code as markdown files with YAML frontmatter, typically under .claude/agents/. Each definition sets the name, description, allowed tools, and a specialized system prompt. A subagent for security reviews typically needs only read access and Grep, while a subagent for refactoring tasks also needs write access and Bash. This restriction is not an accident but a deliberate security feature: a review subagent that could accidentally modify files would defeat the point of an independent check.

The description in the frontmatter largely determines when the main agent activates the subagent automatically. A precise phrasing like "Use this agent for isolated security review of PHP diffs before code is committed" leads to more reliable automatic delegation than a vague description like "helps with code". Teams using subagents should version these definitions and keep them in the repository, so all developers have access to the same specialized roles.


# .claude/agents/security-reviewer.md
---
name: security-reviewer
description: >
  Use this agent for isolated security review of PHP diffs
  before code is committed. Does not implement changes,
  only reports findings.
tools:
  - Read
  - Grep
  - Bash
model: sonnet
---

# The subagent's system prompt follows here as markdown text,
# e.g. review criteria, known vulnerability patterns,
# and the instruction to only report findings,
# never to make changes itself

6. Orchestration: how the main agent uses subagents

The main agent decides case by case whether a task gets delegated to a subagent. That decision rests on the task description in the prompt, the registered subagent definitions, and the estimated scope of the subtask. For several independent subtasks, the main agent can start multiple subagents in parallel within a single request, which in practice yields the biggest time savings because the subagents work simultaneously rather than one after another.

Once a subagent run finishes, the main agent receives only the final text response, not the subagent's full tool-use history. That imposes discipline on how subagent tasks get phrased: the task description has to be precise enough that the response is understandable and actionable without further context. A subagent that only reports "done" without naming concrete results makes the isolation worthless, because the main agent then has to ask again or verify the work itself.


# Simplified illustration of how a main agent might reason about
# whether to dispatch independent subtasks to subagents in parallel

def should_delegate(subtasks: list[str], shared_state: bool) -> bool:
    """
    Decide whether subtasks should run as parallel subagents.
    Returns False if subtasks depend on shared, mutable state.
    """
    if shared_state:
        # Tight coupling means constant back-and-forth, no isolation benefit
        return False
    return len(subtasks) > 1

subtasks = [
    "Audit phtml templates for accessibility issues",
    "Scan PHP classes for PHPStan level 5 violations",
    "Check Alpine.js components for event naming consistency",
]

if should_delegate(subtasks, shared_state=False):
    # Dispatch all three subagents in a single request, run concurrently
    results = dispatch_subagents(subtasks)
else:
    # Fall back to sequential work in the main agent context
    results = [run_inline(task) for task in subtasks]

7. When subagents create unnecessary complexity

Not every task benefits from a subagent, and the temptation to use subagents as a general organizing principle often creates more overhead rather than less. Changing a single file, implementing a simple bug fix, or answering a short question about the codebase does not need a separate agent context. The coordination cost of phrasing a task, waiting for the result, and interpreting it far outweighs the benefit of context isolation here.

A reliable signal for the decision: if the subtask likely needs less context than delegating it costs, a subagent is not worth it. Equally problematic are tasks with strong mutual dependencies where information would have to flow back and forth constantly between subagent and main agent. In those cases, isolation creates artificial friction, because every follow-up question triggers a new delegation cycle instead of the agent simply continuing in its running context.

8. Cost, latency, and context loss as a real downside

Subagents are not a free mechanism. Every subagent call starts its own model inference with its own token consumption, and running multiple subagents in parallel adds up those costs quickly. Starting ten subagents for a task a single agent could have solved in a few steps means paying a token price for parallelization that does not always justify the time saved. In latency-sensitive, interactive workflows, waiting on several subagent results can even take longer than a single sequential pass, if the coordination itself costs time.

The second real downside is information loss. Because only a subagent's final text response flows back into the main context, intermediate steps, uncertainties, and alternative solution paths get lost that the main agent might have needed to make a well-founded decision. A subagent that makes an assumption without explicitly communicating it can steer the main agent in the wrong direction, without the main agent being able to check the basis of that assumption. This opacity is a deliberate tradeoff for context efficiency, not a free optimization.

9. Subagents compared directly to single-agent workflows

The choice between a single agent and subagent delegation depends on the structure of the task, not on its perceived complexity alone. The following overview summarizes when each approach is the better choice in practice.

Task type Single agent Subagent delegation Recommendation
Single bug fix Direct and fast Unnecessary coordination overhead Use a single agent
Research across 3 independent modules Sequential, context overloaded Parallel, context stays lean One subagent per module
Code review after implementation Repeats its own assumptions Independent perspective Fresh review subagent
Tightly coupled iteration Direct context access Constant back-and-forth delegation Use a single agent
Exploring a large legacy codebase Context window fills up fast Exploratory noise stays isolated Delegate research tasks

In practice a simple test works well before every decision: can the subtask be phrased in a single, clear sentence, and is its result usable independently of other running subtasks? If both hold, a subagent is usually the right choice. If the task requires constant follow-up questions or depends directly on the existing conversation history, a single agent remains the more robust and cheaper solution.

Mironsoft

Claude Code workflows, automation, and Magento development

Setting up subagent workflows for your team?

We analyze your existing Claude Code workflows, identify tasks that benefit from parallelization and isolated reviews, and set up matching subagent definitions for your Magento project.

Workflow audit

Reviewing existing prompts and workflows for delegation potential

Subagent setup

Building specialized agent definitions for review and research

Team onboarding

Establishing conventions for sensible delegation across the team

10. Summary

Subagents in Claude Code solve a concrete problem: complex multi-step tasks overload a single context window with intermediate steps that are irrelevant to the actual decision. A subagent encapsulates a focused subtask in its own context and returns only the actionable result. That pays off especially for parallel research across independent areas of a codebase and for isolated code review passes that need a genuine second perspective rather than a rubber stamp on the agent's own work.

At the same time, delegation is not an automatic path to better results. Every subagent call costs extra tokens and time, and isolation swallows intermediate information the main agent might sometimes have needed. For simple, tightly coupled, or sequentially dependent tasks, a single agent remains the more robust and cheaper choice. The skill lies in slicing tasks so that delegation delivers real value instead of creating complexity without a payoff.

Subagents and Automation in Claude Code - The Key Points at a Glance

What a subagent is

A standalone agent instance with its own context window, its own system prompt, and restricted tool access.

When delegation pays off

Independent research areas and isolated review passes without prior knowledge from the implementation.

Configuration

Markdown files with YAML frontmatter under .claude/agents/, a precise description drives automatic activation.

Real limits

Extra token cost, possible latency, and information loss for tightly coupled or simple tasks.

11. FAQ: Subagents and Automation in Claude Code

1What is a subagent in Claude Code?
A standalone agent instance with its own context window, its own system prompt, and restricted tool access, handling a focused subtask and reporting back only the result.
2How does a subagent differ from a simple function?
A subagent makes its own decisions and invokes tools independently. A function has a fixed flow with no decision logic of its own.
3Why does a subagent improve the outcome of code reviews?
A fresh subagent with no knowledge of the implementation evaluates code closer to the perspective of a genuine reviewer, instead of repeating its own assumptions.
4When does parallelizing with multiple subagents pay off?
When subtasks are genuinely independent. As soon as one subagent waits on another's result, the time savings evaporate.
5How are subagents configured in Claude Code?
As markdown files with YAML frontmatter under .claude/agents/. The frontmatter sets the name, description, tools, and model.
6When should I avoid using a subagent?
For simple tasks or tightly coupled iterations requiring constant context exchange. The coordination overhead here exceeds the benefit.
7Do subagents cost more than a single agent?
Yes, every call starts its own model inference with its own token consumption. For small tasks, that often does not justify the time saved.
8What information gets lost during subagent delegation?
Only the final text response flows back. Intermediate steps and uncertainties of the subagent stay hidden unless explicitly reported.
9Does the main agent activate subagents automatically?
Yes, based on the description in the definition. A precise description leads to more reliable automatic delegation.
10Should subagent definitions be shared across a team?
Yes. Versioned definitions in the repository ensure all developers use the same specialized roles and tool restrictions.