Subagents in AI Coding Tools: A Practical Guide to Context Isolation
AI coding subagents are usually framed as a concurrency feature, but their real value is context engineering: a subagent runs in its own context window, does the messy exploration there, and returns only a distilled conclusion. This guide explains how that boundary works, the three signals that tell you when dispatching pays off versus staying in the main conversation, the built-in agent archetypes (explorer, reviewer, executor), how to codify reusable roles as metadata-driven Markdown config files, how foreground and background execution plus fan-out change the way you harvest results, and how multi-agent teams are organized to avoid concurrent-write conflicts. It closes with the two levers that control cost and risk — model tiering and least privilege — and a short checklist for putting subagents into practice on large codebases and long-running tasks.
1. Where the Problem Starts: Context Is a Consumable Resource
Many people treat an AI coding assistant as “a pair programmer with broader knowledge.” But on a real project, the moment you ask it to do anything sizable, you hit a contradiction: for it to do the job well, it first has to see the scene clearly — flip through a dozen files, read a batch of logs, run a few rounds of search. And those intermediate artifacts fill up the context themselves.
By the time you actually need it to write code, the context already holds screen after screen of search results nobody will look at again, whole files verbatim, and logs of failed retries. The result is counterintuitive: the longer you talk, the more confused it gets. The reasons are not hard to understand:
- Effective attention gets diluted. Large amounts of irrelevant tokens compete for the same attention budget as the target instruction, and the key constraints drown.
- Stale information gets locked in. Old file content read in round 3 is still sitting in the context, so later judgments tend to rest on outdated facts.
- Noise is irreversible. Context only grows, never shrinks, and summary compaction is lossy — once pollution happens, only restarting the conversation clears it.
So a subagent is first and foremost a context engineering technique, not a “concurrency feature.”
2. What a Subagent Really Is: Redrawing the Context Boundary
A subagent is, simply put, an independent instance dedicated to one class of work. What makes it different from the main conversation is that it is separate on four dimensions:
| Dimension | Main agent | Subagent |
|---|---|---|
| Context window | Accumulates the whole conversation | Independent; holds only what this task needs |
| System prompt | Generic workflow | Can be tailored to a domain |
| Tool permissions | Fairly broad | Can be minimized (e.g., read-only) |
| Model tier | Usually the stronger one | Can be downgraded to match task complexity |
The runtime mechanism is a “one in, one out” process:
Main agent (context: task goal + known constraints)││ Dispatch: explicit task boundary + expected output format▼Subagent (own context: does its own search, its own trial and error,reads dozens of files)││ Return: one distilled conclusion (findings, evidence, file paths, risks)▼Main agent (context grows by a few lines; moves on to the next step)
In one sentence: the exploration stays on the subagent’s side, and only the conclusion comes back to yours. The full text of those dozens of files never gets a chance to enter the main conversation.
If you were to express this delegation with an idealized interface, it would look roughly like this:
{"task": "Locate the order state machine's transition implementation and explain the entry conditions for each state","context_hint": "Scope to the src/order directory only; do not modify any files","output_contract": {"conclusion": "string, 3-5 lines","evidence": "list of file:line references","open_questions": "array of strings"}}
Declaring an output contract explicitly is the part most easily overlooked in practice and the part with the biggest payoff: it determines how clean the subagent’s returned content is.
3. When to Dispatch a Subagent: Three Signals
You don’t need subagents for everything — dispatching has fixed overhead too (a cold start, plus writing the handoff description). These three signals are enough to decide:
- The intermediate artifacts are bulky. You expect to read a dozen or more files, or to produce hundreds or thousands of lines of search or scan results.
- The intermediate artifacts are disposable. Their value is only for the moment; the conclusion is what you actually need.
- The task can be cleanly separated. The boundary is clear, coupling with the rest of the main conversation is low, and the pieces may even be independent enough to run in parallel.
Conversely, these situations are better kept in the main conversation:
- Interactive discussion that requires repeated clarification with the user;
- “Mainline decisions” whose outcome shapes every subsequent design step;
- Tasks that share a lot of intermediate state, where handoff cost exceeds the benefit;
- Small, latency-sensitive changes where you want an answer in a few seconds.
One further rule of thumb: when you notice yourself dispatching the same kind of work repeatedly and writing the same instructions each time, that is the signal to codify it rather than describing it by hand every round.
4. Built-In Subagents: Start With What’s Already in the Box
Mainstream AI coding tools usually ship with several subagents organized by responsibility. Three archetypes are common:
- Explorer — good at broad search and code location; reads a lot and says little, a natural fit for “where is this feature implemented?”
- Reviewer — read-only by design; used for code review, security scanning, dependency checks, without touching any files.
- Executor — takes on mechanical batch operations, such as bulk signature changes, unified formatting, or generating test skeletons.
Two pitfalls show up often when using built-in agents. One is a task description that’s too vague, which leads the agent to expand its search scope on its own and return longer content. The other is not constraining the working directory, so it wanders into unrelated modules and burns turns. Writing the boundaries clearly before dispatching is the simplest way to raise the hit rate.
5. Custom Subagents: Codify the Roles You Reuse
Built-in agents can’t cover your domain. When the same kind of work keeps coming back, it pays to write it into a config file. The common industry approach is Markdown files with metadata: the header declares identity and constraints, the body writes the behavioral rules.
---name: db-migration-reviewerdescription: Reviews database migration scripts. Use when the task involvesDDL changes, index adjustments, or rollback plans. Read-only;never modifies files.tools: [read_file, grep, list_dir] # tool allowlist, no write accessmodel: fast # structured review, a lighter model is enough---You are a migration script reviewer. Output your findings in this order:1. Compatibility risk: can it run online, does it lock tables2. Reversibility: is a rollback path provided3. Data risk: any data loss or truncation4. Index impact: execution cost of adding/removing indexesEvery finding must cite file:line evidence. Do not add anything beyondthe code-change recommendations.
The most critical field is description. The main agent reads it to decide “should this work go to this agent,” so a vague one leads to misrouting. A good description states both what it does and when to use it.
These files usually live at two levels:
- Project level (a directory inside the repo): travels with the code, goes into version control, and takes effect consistently for every team member — a good fit for project-specific conventions and standards.
- User level (an
agentssubdirectory under your global config directory): reused across projects, suited to personal habitual review roles and generic workflow roles.
The organizing principle to follow: any role that carries team standards (naming conventions, log formats, directory structure) belongs at project level; any role that encodes a generic workflow (reading logs, dependency analysis, writing unit test skeletons) belongs at user level.
6. Foreground and Background: Parallel Execution and Harvesting Results
Foreground (synchronous) execution means the main agent waits for the result, and the main conversation is blocked in the meantime — but you can watch the process. It suits key tasks that shape subsequent steps.
Background (asynchronous) execution means the main agent moves on to other work immediately and is notified when the subagent finishes. It suits long-running tasks that don’t block the mainline, such as a full test run, scanning a batch of historical logs, or applying the same analysis to multiple modules.
The payoff from parallelism is fan-out: split one analysis into N parts and dispatch them to N instances at the same time. Three things still need your control:
- A concurrency ceiling. Too much parallelism means competing for the same I/O, build services, and API quota, which makes everything slower.
- Result harvesting. Background tasks need a clear completion signal and a designated location (for example, result files written to an agreed directory), or the conclusions get lost.
- Failure handling. When some parts fail, the main agent needs to know “which succeeded, which failed, and why” — not an incomplete conclusion whose gaps you can’t see.
7. One Step Further: Multi-Agent Collaboration (Agent Teams)
A single subagent solves “pollution”; multi-agent collaboration solves “division of labor and parallelism.” The typical shape is one orchestrator + several workers + an independent reviewer:
Orchestrator (breaks down the task, assigns responsibilities, aggregates)├─ Worker A: backend API changes (owns backend/)├─ Worker B: frontend adaptation (owns frontend/)├─ Worker C: test coverage (read-only + write access to the test directory)└─ Reviewer: read-only across the whole repo, checks consistency and conventions
Two collaboration modes are common:
- Shared blackboard: every participant writes conclusions to agreed files and later participants read them. The information is persistent and easy to trace, but watch out for concurrent write conflicts.
- Message passing: the orchestrator distributes and collects one by one. The structure is clearer, but the pressure on the orchestrator’s own context is higher.
The most realistic risk in multi-agent setups isn’t “figuring it out wrong” — it’s concurrent write conflicts and semantic inconsistency. The mitigations are straightforward:
- Partition by directory or module, giving each worker an exclusive write scope and forbidding it from crossing the line.
- Keep the reviewer read-only, placed after the workers, responsible for the final consistency check.
- Let the orchestrator hold only conclusions. It doesn’t copy the workers’ intermediate artifacts, keeping its own context lean.
- Make every step reversible. Land changes in small, verifiable batches rather than one big bulk edit.
8. Cost and Risk: Two Levers That Are Easy to Pull
A subagent architecture gives you two natural control points.
Cost tiering. Use lighter models for exploration, retrieval, and format conversion; use stronger models for architecture decisions, complex debugging, and final review. In practice, downgrading the “read a lot, think a little” work significantly cuts total consumption with very little quality loss.
Least privilege. Reviewer agents get no write access; executor agents get no network access; data agents are confined to specified directories. Put permissions in configuration rather than relying on prompt wording, because configuration is a hard constraint and a prompt is a soft one.
Context budget. Give each subagent task an explicit completion criterion (for example, “no more than 20 lines of conclusions”) so it doesn’t expand its scope indefinitely; periodically compress long history in the main conversation, and hand details off to files instead of storing them in context.
9. Implementation Checklist
- Will the task’s intermediate artifacts exceed a dozen files? Yes → dispatch a subagent.
- Did you specify the task boundary, directory scope, and expected output format when dispatching?
- Is there a recurring task of the same type? Yes → codify it as a custom subagent.
- Does the subagent have a tool allowlist? For read-only roles, is write access fully removed?
- Are simple tasks downgraded to a lighter model?
- Do background parallel tasks have a clear completion signal and a result location on disk?
- In multi-agent parallelism, are write scopes non-overlapping, and is the review step read-only and placed last?
10. Summary
The value of subagents boils down to one sentence: trade an independent context window for a clean, controllable main conversation. It lets an AI coding assistant freely flip through dozens of files and run hundreds of log lines without your main conversation drowning in noise — and layering on tool allowlists and model tiering pushes risk and cost down at the same time.
From single-agent exploration, to codifying custom roles, to multi-agent division of labor, it is all the same thing being refined: managing “process” and “conclusion” separately. Once that habit is in place, the usable effective context you have when facing a large codebase and long-running tasks is far more generous than the window size suggests.
