AI Coding Subagents: A Practical Guide to Scoped Execution

    This guide explains how subagent mechanisms make AI coding assistants controllable and predictable. It covers what a subagent is, how it differs from a general conversational mode, how to tier models by task difficulty to control cost, how to orchestrate parallel fan-out, pipeline, and voting patterns, and how to organize agent definitions in a repository. It also lists common anti-patterns and a step-by-step adoption path.

    AI Coding Subagents: A Practical Guide to Scoped Execution

    The Starting Problem: You Asked for a Health Check and Got a Surgical Plan

    Most teams hit the same scenario early on with AI coding tools. You only want the repository scanned for potential security risks. What comes back is packed with refactoring suggestions, performance tuning ideas, pairs of test cases, and even a proposal to reorganize the directory structure. The output looks rich, but the usable signal is diluted, and reviewers have to spend extra time picking conclusions out of the noise.

    This is not a model intelligence problem. It is an inevitable result of the interaction paradigm itself. A general-purpose conversational assistant, faced with a vague request, tends to hand over everything that might be relevant in one shot to maximize the chance of appearing helpful. Appending more “don’t do anything else” prompts is not a reliable fix. The more engineering approach is to separate responsibilities, permissions, and context at the architecture level. That is exactly the problem the subagent mechanism solves.

    What a Subagent Really Is: One Conversation Split into Constrained Executable Units

    A subagent can be understood as a dedicated executor built around the main agent. It is not a smarter model. It is a strictly constrained runtime context, usually with four characteristics:

    • An independent context window: it loads only information relevant to its own task, preventing the main session history from growing without bound.
    • An independent task description: a structured role prompt defines the goal, boundaries, and output format.
    • An independent tool allowlist: it can call only explicitly authorized capabilities; unauthorized ones are invisible at runtime.
    • A declarable model tier: a model of a different size and cost can be selected based on task complexity.

    In most implementations, these definitions live as plain text files in a conventional directory inside the project (for example .claude/agents/ at the project root), with one file per subagent. This makes them easy to version, review, and reuse alongside the code. A file usually has two parts: YAML metadata at the top (name, description, tool list, model tier) and detailed Markdown instructions at the bottom.

    1. ---
    2. name: security-reviewer
    3. description: Read-only security and standards review; outputs an issue list and modifies no files
    4. tools: [Read, Grep, Glob]
    5. model: fast
    6. ---
    7. You are a code review expert. Your only job is to identify the following issues and provide locations and remediation directions:
    8. - Injection risks (SQL concatenation, command concatenation, template injection)
    9. - Cross-site scripting and missing output encoding
    10. - Authentication and broken access control flaws
    11. - Hardcoded secrets and sensitive data leaked in logs
    12. Constraints:
    13. 1. Read-only. Do not propose or directly generate large-scale refactoring.
    14. 2. Every issue must include file:line, risk level, and verifiable reproduction conditions.
    15. 3. Output a table sorted by risk level in descending order.

    The key point is that constraints are written into the structure, not into a one-off conversational request. A review subagent has no ability to write files, so it physically cannot refactor your code along the way. A test-generation subagent cares only about case coverage and will not turn around and question your architecture choices.

    Four Differences from the Traditional Conversational Mode

    Dimension General conversational mode Subagent mode
    Focus Divergent, covers every possibly relevant direction Convergent, handles only the assigned target
    Permission surface Usually inherits all capabilities of the main session Explicit allowlist, least privilege
    Context Continuously accumulating, prone to overflow and contamination Independent and short-lived, discarded after use
    Reusability Depends on individual prompt habits Configuration committed to the repo, one shared team standard

    The direct benefit of these four differences is predictable output. When review, testing, documentation, and dependency governance are each handled by a fixed subagent, the output format stays stable and can be consumed reliably by downstream processes such as static checks, pipeline gates, and review templates, instead of requiring manual rework every time.

    Cost Structure: Not Every Task Deserves the Most Expensive Model

    An often overlooked fact is that task difficulty is distributed very unevenly. Looking up symbol definitions, batch format conversion, log categorization, and simple pattern matching can all be done by a small, fast model, whose call cost is typically around one third of a high-capability model (the exact ratio varies by vendor and tier, so refer to the actual pricing documentation). Handing this work to a high-capability model is like using flagship compute to do string matching.

    Model tiering is best divided by “judgment density”:

    • Light tier: retrieval, formatting, renaming, list organization, structured extraction.
    • Standard tier: routine coding, unit test generation, defect localization, code explanation.
    • High-capability tier: cross-module architecture tradeoffs, difficult concurrency or memory issues, complex migration design.

    Combined with a model tier declared on each subagent, teams can significantly reduce monthly spend without sacrificing quality on the critical path. Because each subagent’s input is also trimmed, token consumption drops as well. That is a double saving.

    Parallel Orchestration: Turning Serial Waiting into Fan-Out and Aggregation

    One of the most valuable capabilities of subagents is parallelism. There are three typical patterns:

    1. Fan-out: slice the same task by directory, module, or file list, dispatch multiple homogeneous subagents at once, and have each return a local conclusion.
    2. Pipeline: review → fix → test generation → documentation update, where the previous stage’s output becomes the next stage’s input and responsibilities do not overlap.
    3. Voting: give the same problem to two or three subagents with different prompts or different model tiers, take the intersection as the high-confidence conclusion and the difference as items pending human confirmation.

    Parallelism must be paired with two engineering constraints. First, write isolation: parallel subagents must either all be read-only or each operate on a separate branch or separate workspace to avoid overwriting one another. Second, result convergence: the main agent deduplicates, sorts, and produces a single report, so multiple contradictory conclusions are never dumped on a human directly.

    Adoption Steps and Directory Layout

    1. project/
    2. ├── .claude/
    3. │ └── agents/
    4. │ ├── security-reviewer.md
    5. │ ├── test-author.md
    6. │ ├── perf-profiler.md
    7. │ └── doc-sync.md
    8. ├── src/
    9. └── tests/

    Recommended implementation order:

    1. Define the output contract first: specify what fields each subagent returns (location, level, evidence, recommendation). Parallelism without a contract only creates chaos.
    2. Then tighten permissions: default to read-only, and open write and execution capabilities item by item only when truly needed.
    3. Then tier the models: start from the cheapest tier and move up only if quality is insufficient.
    4. Finally, wire into the pipeline: connect subagent output to common capabilities such as static checks, test coverage, and monitoring alerts to form gates.

    Common Anti-Patterns

    • Overlapping responsibilities: two subagents can both modify the same set of files, causing conflicts and rollbacks.
    • Context leakage: stuffing the full session history into every subagent is both expensive and lowers the signal-to-noise ratio.
    • Prompt bloat: turning a role file into a thousand-line set of universal rules, which defeats the purpose of constraints.
    • No verification loop: generating without validating, missing the three confirmations of compile, test, and static analysis.
    • Permissions fully opened at once: giving every subagent complete access for convenience, leaving nothing to audit.

    Conclusion

    The point of subagents is not to make the tool “more automatic” but to make automation controllable, reproducible, and auditable: clear task boundaries, least privilege, cost allocated by difficulty, stable output formats, and significantly reduced waiting time through parallelism. In engineering practice on platforms such as Baidu AI Cloud, this same approach of “responsibility separation + least privilege + tiered compute + result convergence” applies to building reliable AI development pipelines. Design the constraints first, then talk about the ceiling of intelligence.