Architecture·11 min read·25 July 2026

Claude Code Subagents Workflow: A Production Guide

Master the claude code subagents workflow: when to spawn vs stay single-threaded, how to structure CLAUDE.md guardrails, and verification loops that hold in production.

By Solomon Udoh · AI Architect & Certification Lead

Claude Code Subagents Workflow: A Production Guide

The claude code subagents workflow is the pattern that separates toy demos from production-grade engineering automation. A subagent is a Claude instance spawned by a coordinator to handle a bounded slice of a larger task, isolated from the parent's context, and returning a structured result. Get the decomposition right and you compress multi-hour engineering tasks into minutes. Get it wrong and you accumulate context bloat, branch collisions, and silent attribution loss. This guide covers the mechanics, the decision rules, and the guardrails that actually hold under load.


What is a subagent in Claude Code, and when should you spawn one?

A subagent is a fresh Claude Code session launched by a coordinator agent to execute a narrowly scoped task. It starts with an empty context window, receives only what the coordinator explicitly passes, and returns a structured result. The coordinator never shares its full conversation history with the subagent; that isolation is the point.

The spawn decision comes down to three criteria:

  1. Independence -- the subtask does not depend on in-flight results from a sibling subtask.
  2. Scope clarity -- the subtask has a clear input contract and a verifiable output.
  3. Context cost -- keeping the work in the parent thread would dilute attention across unrelated tokens.

When all three hold, spawn. When the subtask is tightly coupled to the parent's evolving state, stay single-threaded. The Agentic Architecture & Orchestration domain of the CCAR-F exam (weighted at 27%) tests exactly this judgment call, making it the highest-stakes domain on the paper.

Each subagent should receive the minimal context required to complete its task and nothing more. Passing the full parent conversation is the most common source of context bloat in multi-agent systems.

Anthropic , Claude Documentation (Building effective agents)

How does the coordinator decide which subagents to spawn?

The coordinator's job is decomposition, dispatch, and synthesis. It does not execute tasks itself; it routes them. A well-designed coordinator follows a hub-and-spoke architecture: one central orchestrator, N specialist subagents, no peer-to-peer chatter between subagents.

The decision logic looks like this:

Loading diagram...

Coordinator dynamic subagent selection is a model-driven decision: the coordinator inspects the task, classifies it, and selects the appropriate specialist. This is distinct from pre-configured routing, where the pipeline is fixed at design time. For most production engineering workflows, a hybrid works best: fixed routing for well-understood task types, dynamic selection for novel or ambiguous requests.

Parallel vs sequential spawning

PatternWhen to useRisk
Parallel subagent spawningIndependent subtasks with no shared write targetsBranch collisions if file scopes overlap
Sequential chainEach step depends on the prior resultLatency compounds; single failure blocks the chain
Fork for explorationDivergent hypotheses to evaluateContext duplication cost; merge complexity
Single-threadedTight coupling, small scope, low context costNone, but misapplied it becomes a bottleneck

For parallel spawning across engineers on the same repository, the safest guard is to assign each subagent a disjoint file set before spawning. Overlapping write targets are the primary cause of branch collisions in team settings.


How should you structure CLAUDE.md to keep subagents on-task?

CLAUDE.md is the primary mechanism for encoding repo-specific rules that every Claude Code session inherits. Without it, subagents default to general coding conventions that may conflict with your codebase's standards.

A production-grade CLAUDE.md for a subagents workflow has three layers:

  1. Scope constraints -- explicit file and directory boundaries the agent is permitted to modify.
  2. Style and convention rules -- formatting, naming, import order, test requirements.
  3. Verification requirements -- what the agent must confirm before returning a result (tests pass, linter clean, diff is minimal).
markdown
# CLAUDE.md
## Scope
- Modify only files under `src/` and `tests/`.
- Do not reformat files outside the direct change scope.
- Do not alter `package-lock.json` or `yarn.lock` unless explicitly instructed.
## Conventions
- TypeScript strict mode; no `any` types.
- All new functions require a JSDoc comment.
- Test files mirror source paths under `tests/`.
## Verification
- Run `npm test` before returning. If tests fail, diagnose and fix before reporting.
- Report the diff size (lines added / removed) in your structured output.
- If a change would affect more than 50 lines outside the target file, pause and ask.

The three-level configuration hierarchy means that a root-level CLAUDE.md sets defaults, directory-level files narrow scope, and user-level settings handle personal preferences. Subagents inherit the hierarchy from the directory they are launched in, so placing task-specific CLAUDE.md files in subdirectories is a clean way to scope subagent behaviour without polluting the root config.

Per the version control implications of this hierarchy, the root and directory-level files should be committed to the repository. User-level files should not. This distinction matters for teams: committed files enforce shared standards; uncommitted files allow individual customisation without drift.


What verification loop should you trust for agentic coding outputs?

The weakest verification loop is "the model says it's done." The strongest is a deterministic external signal: tests pass, the linter exits zero, the diff is within scope. The CCAR-F exam consistently rewards deterministic solutions over probabilistic ones when stakes are high -- a principle that applies directly to verification design.

A practical three-stage loop:

text
Stage 1: Structural check
- Does the output match the expected schema or interface?
- Is the diff scoped to the declared target files?
Stage 2: Functional check
- Do unit tests pass?
- Do integration tests pass for affected paths?
Stage 3: Semantic check (human or LLM-as-judge)
- Does the change accomplish the stated goal?
- Are there unintended side effects?

Stage 3 is the only probabilistic stage. For high-stakes changes (security patches, data migrations, public API modifications), route Stage 3 to a human via a structured handoff. For routine changes, an independent review subagent can handle it -- but note the self-review limitation: a subagent reviewing its own output is not independent. Spawn a separate instance with only the diff and the acceptance criteria.

The key question is whether legitimate principals that have the ability to authorise the actions being requested have either explicitly done so or if it's sufficiently clear from context that they would permit Claude to take the relevant action in the current situation.

Anthropic , Claude Documentation (Being helpful, honest, and avoiding harms)

How do you orchestrate Claude Code with MCP servers without bloating context?

MCP servers extend what subagents can do: read from databases, call external APIs, write to filesystems, trigger CI pipelines. The risk is tool overload -- a subagent with 40 tools available spends attention on tool selection rather than task execution.

The solution is scoped tool distribution: each subagent receives only the tools relevant to its declared scope. A subagent tasked with reading test results needs the CI log tool, not the database write tool.

Practical MCP scoping for a subagents workflow:

Subagent roleTools to includeTools to exclude
Code reader / explorerread_file, grep, glob, list_dirAll write tools
Code writerread_file, edit_file, write_fileDatabase tools, CI triggers
Test runnerbash (scoped to test commands), read_fileFile write tools
Synthesiser / coordinatorread_file, structured output toolsAll execution tools

Environment variable expansion in MCP config lets you parameterise tool access at launch time, which is the cleanest way to scope credentials per subagent without hardcoding secrets into CLAUDE.md.

For context management, the rule is: pass summaries, not transcripts. When a subagent completes and the coordinator needs its output, extract the structured result and discard the subagent's conversation history. Summary injection for fresh sessions is the pattern: compress prior work into a dense fact block, inject it into the next session's system prompt, and start with a clean context window.


What production workflows actually benefit from subagents?

Not every engineering task warrants a subagents workflow. The overhead of decomposition, dispatch, and synthesis is real. Here are the task types where the pattern pays off, and where it does not.

Task typeSubagents benefit?Rationale
Large refactor across many filesYesFiles are independent; parallel execution compresses time
Security audit of a codebaseYesEach module can be reviewed in isolation
TDD loop (write test, implement, verify)ConditionalSequential dependency; benefit only if test and impl are in different modules
Single-function bug fixNoOverhead exceeds benefit; single-threaded is faster
Multi-service integration testYesServices are independent; parallel verification is safe
Documentation generationYesPer-file docs are independent; parallelism is clean
Database migrationNoSequential dependency and high stakes; single-threaded with human review

For the refactor and audit cases, the per-file and cross-file pass pattern is the standard approach: a first pass handles per-file changes in parallel, a second cross-file pass handles consistency (import paths, shared types, naming). The two passes must be sequential with respect to each other, but within each pass the subagents run in parallel.

Plan-then-build as the default entry point

For any task above a certain complexity threshold, the coordinator should enter plan mode before spawning subagents. Plan mode produces a structured decomposition that the coordinator can inspect, the user can approve, and the subagents can execute against. Skipping plan mode is the most common cause of narrow decomposition failure: the coordinator spawns subagents for a subtask that was never the right unit of work.


How do you keep parallel Claude Code sessions from colliding?

Branch collisions happen when two subagents write to the same file concurrently. The fix is not coordination between subagents (that reintroduces coupling) but pre-assignment of disjoint write scopes by the coordinator before any subagent is spawned.

A coordinator prompt that enforces this:

text
You are coordinating a refactor of the authentication module.
Before spawning any subagents, produce a JSON manifest that assigns each
subagent a disjoint set of files. No file may appear in more than one
subagent's assignment. Format:
{
"subagents": [
{ "id": "sa-1", "files": ["src/auth/login.ts", "tests/auth/login.test.ts"] },
{ "id": "sa-2", "files": ["src/auth/session.ts", "tests/auth/session.test.ts"] }
]
}
Do not spawn any subagent until the manifest is complete and verified.

This is a prerequisite gate design: the manifest is a gate that must pass before execution begins. If the manifest reveals that two required changes share a file, the coordinator collapses them into a single sequential subagent rather than risking a collision.

For teams running multiple engineers with Claude Code sessions simultaneously, the same principle applies at the branch level: each engineer's Claude Code session should operate on a dedicated branch. Merging is a human-gated step, not an automated one.


What does a minimal end-to-end subagents workflow look like in code?

Below is a simplified coordinator prompt that implements the full pattern: decompose, gate, spawn, verify, synthesise.

python
COORDINATOR_SYSTEM = """
You are a coordinator agent for engineering tasks.
Workflow:
1. Receive the task description.
2. Produce a JSON decomposition: list of subtasks, each with id, scope (files),
goal (one sentence), and acceptance_criteria (list of strings).
3. Confirm the decomposition has no overlapping file scopes.
4. For each subtask, produce a subagent prompt that includes:
- The subtask goal
- The exact files in scope
- The acceptance criteria
- The verification command to run
5. After all subagents complete, collect their structured results.
6. Verify each result against its acceptance criteria.
7. If any result fails, re-route that subtask (do not silently suppress failures).
8. Produce a final synthesis report.
Never execute file changes yourself. Delegate all execution to subagents.
"""
python
SUBAGENT_SYSTEM = """
You are an execution agent. You receive a single bounded task.
Rules:
- Modify only the files listed in your scope.
- Run the verification command before reporting completion.
- Return a JSON result: { "subtask_id": str, "status": "pass"|"fail",
"diff_lines_added": int, "diff_lines_removed": int,
"verification_output": str, "notes": str }
- If verification fails, diagnose and retry once. If it fails again, set
status to "fail" and explain in notes. Do not fabricate a passing result.
"""

The structured result format is critical. A coordinator that receives free-text from subagents cannot reliably synthesise or verify. JSON with explicit status fields is the minimum viable contract.


How does the CCAR-F exam test subagents workflow knowledge?

Domain 1 (Agentic Architecture & Orchestration) carries 27% of the CCAR-F exam weight, making it the single largest domain. The exam draws 4 scenarios at random from a bank of 6 per sitting, so every candidate will face at least one multi-agent scenario.

The exam consistently tests three judgment calls in the subagents context:

  1. When to spawn vs stay single-threaded -- scenarios present a task and ask which architecture is appropriate. The answer turns on independence, scope clarity, and context cost.
  2. How to handle subagent failure -- scenarios present a failed subagent result and ask how the coordinator should respond. The correct answer is almost always root-cause diagnosis and targeted re-routing, not silent suppression or full restart.
  3. How to enforce constraints -- scenarios ask whether a guardrail should be implemented via prompt instruction or programmatic hook. The rule: when the constraint is high-stakes and must not be bypassed, use a programmatic hook. When it is advisory, a prompt instruction is proportionate.

Our concept library at /concepts covers 174 atomic concepts mapped to all five CCAR-F domains and 30 task statements. The agentic architecture concepts are the densest cluster, reflecting the domain's exam weight.

Frequently asked questions

What is the difference between a subagent and a tool call in Claude Code?
A tool call executes a deterministic function and returns a result within the same session context. A subagent is a separate Claude Code session with its own isolated context window, capable of reasoning, planning, and using tools independently. Subagents are appropriate when the subtask requires multi-step reasoning; tool calls are appropriate for single deterministic operations.
How many subagents can a coordinator spawn in parallel?
There is no hard limit imposed by Claude Code itself. The practical limit is set by your API rate limits, the number of disjoint file scopes available in the task, and your ability to synthesise results without attribution loss. Most production workflows spawn between 2 and 8 parallel subagents per coordinator invocation. Beyond that, synthesis complexity tends to outweigh the parallelism benefit.
Should subagents have access to the coordinator's full conversation history?
No. Passing the full parent conversation to a subagent is the most common source of context bloat in multi-agent systems. Each subagent should receive only the structured context required for its specific subtask: the goal, the file scope, the acceptance criteria, and any relevant background facts as a compressed summary. The coordinator retains the full history; subagents do not.
How do you prevent a subagent from making overly broad diffs?
Encode scope constraints explicitly in CLAUDE.md and in the subagent's system prompt. Specify the exact files the subagent may modify. Add a verification step that checks diff size and fails if changes exceed a defined threshold (for example, more than 50 lines outside the target file). Returning diff metadata in the structured result lets the coordinator enforce the constraint programmatically.
What is the CCAR-F exam weight for agentic architecture topics?
Domain 1 (Agentic Architecture and Orchestration) carries 27% of the CCAR-F exam weight, making it the highest-weighted domain. The exam draws 4 scenarios at random from a bank of 6 per sitting, and multi-agent orchestration scenarios appear in every sitting. The passing score is 720 on a 100 to 1000 scale.
Can Claude Code subagents write to the same file simultaneously?
They can attempt to, but the result is a collision that corrupts or overwrites work. The correct design is for the coordinator to produce a file manifest with disjoint write scopes before spawning any subagents. No file should appear in more than one subagent's assignment. If two required changes share a file, collapse them into a single sequential subagent.

People also ask

How does Claude Code decide when to use subagents?
Claude Code spawns a subagent when a subtask is independent of sibling tasks, has a clear input and verifiable output, and would dilute the parent context if kept in-thread. When those three conditions do not hold, staying single-threaded is faster and safer. The coordinator makes this decision, not the subagent itself.
What is the best way to structure CLAUDE.md for a multi-agent workflow?
A production CLAUDE.md for multi-agent use has three layers: scope constraints listing the exact files or directories each agent may modify, style and convention rules the agent must follow, and verification requirements specifying what must pass before the agent reports completion. Directory-level CLAUDE.md files narrow scope for specific subagent roles without polluting the root config.
How do you pass context between Claude Code subagents without bloating the context window?
Pass structured summaries, not full transcripts. When a subagent completes, the coordinator extracts its JSON result and discards the conversation history. Relevant background facts are compressed into a dense block and injected into the next session's system prompt. This keeps each subagent's context window focused on its specific task rather than accumulated prior work.
What verification loop should you use for Claude Code agentic outputs?
A three-stage loop works best: structural check (output matches expected schema, diff is scoped correctly), functional check (tests and linter pass), and semantic check (change accomplishes the goal without unintended side effects). The first two stages are deterministic. The third is probabilistic and should route to a human reviewer for high-stakes changes.
How do you run parallel Claude Code sessions without branch collisions?
The coordinator produces a file manifest assigning each subagent a disjoint set of files before any subagent is spawned. No file appears in more than one assignment. For team-level parallelism, each engineer's Claude Code session operates on a dedicated branch, with merging handled as a human-gated step rather than an automated one.

About the author

Solomon Udoh

AI Architect & Certification Lead

Solomon Udoh is an AI Architect who designs and ships production agent systems on the Claude API and Claude Code. He built AI Skill Certs' adaptive engine and authored its 174-concept knowledge graph, mapping every Claude Certified Architect - Foundations objective to hands-on, exam-aligned practice.

  • Designs production multi-agent systems on the Claude API and Agent SDK
  • Author of the AI Skill Certs knowledge graph (174 mapped exam concepts)
  • Builds with MCP, Claude Code, structured outputs, and agentic loops daily
  • Reviews every concept page against the official Anthropic exam guide

You might also like

Ready to put it into practice?

Study every exam concept with an adaptive tutor.

Start studying