AI Catchup

Claude Code Subagent Patterns: 10 Reusable Agent Definitions

By 16 min read

A Claude Code subagent is a delegated worker with its own context window, defined as a markdown file with YAML frontmatter in .claude/agents/. Subagents can edit files when you grant Edit or Write, nest three layers deep by default, and run 20 at a time. These 10 definitions cover the highest-value delegations.

The single most under-used pattern in Claude Code is delegation. Most readers know subagents exist; few keep a set of them defined and ready. This guide is the practical playbook -- 10 subagent patterns, each written as a reusable agent definition file rather than a one-off chat prompt, with the workflow it solves and the failure mode to watch. Every mechanical claim below is sourced to Anthropic's Claude Code documentation, listed at the end; the patterns are editorial judgement built on top of that documented behaviour, not a measured study of our own usage.

For the underlying mechanics -- when to spawn vs when to stay, how compaction interacts, what exactly the parent gets back -- the Claude Code context management guide is the prerequisite.

What Changed Since This Guide Was First Published

This page was first published on April 17, 2026 and re-verified against Anthropic's docs on August 15, 2026. Four things it originally said no longer hold:

What this guide originally saidWhat Anthropic's docs say now
"Subagents pass back text, not direct edits, so anything that needs to mutate files is usually better done in the parent"Subagents can edit files when you include Edit or Write in their tools. Read-only is a choice you make by omitting them, not a property of subagents.
Spawning is a plain-language request, plus "explicit slash commands when the spawn pattern is part of a saved workflow"Subagents are definition files in .claude/agents/ or ~/.claude/agents/ with YAML frontmatter, invoked by auto-delegation, @-mention, or claude --agent. The /agents wizard was removed in v2.1.198.
"Going more than two levels deep usually produces diminishing returns"Nesting is three layers deep by default, configurable through CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH, with a default cap of 20 concurrent subagents.
"/ultrareview, a Claude Code slash command" for the formal pre-PR passThe command is /code-review ultra; /ultrareview is an alias when the feature is available to your account. It is a research preview that runs in a cloud sandbox and bills usage credits: three one-time free runs on Pro and Max, none on Team and Enterprise, then roughly $5 to $25 per review.

The last one is the correction most worth reading twice. The original text recommended running it routinely as if it were a free local command. It is a paid, remote, pre-merge tool.

Key Takeaways

  • A subagent is a file, not a phrasing. .claude/agents/<name>.md with name and description in frontmatter is the whole requirement; everything else is optional.
  • The tools line is the design decision. It sets whether a pattern is a read-only investigator or a worker that changes your tree.
  • Three of these patterns now ship built in. Explore, Plan, and /code-review cover the Codebase Scout, the Migration Planner, and the PR Reviewer out of the box.
  • Patterns 1-10: verifier, codebase scout, spec-to-tests translator, refactor proposer, PR reviewer, migration planner, bug hunter, docs generator, convention detective, library briefer.
  • Isolation is available when you need edits without collisions: isolation: worktree gives a subagent its own git checkout.

How to Define a Subagent

A subagent file is YAML frontmatter plus a markdown body that becomes its system prompt:

---
name: code-reviewer
description: Reviews code for quality and best practices
tools: Read, Glob, Grep
model: sonnet
---

You are a code reviewer. When invoked, analyze the code and provide
specific, actionable feedback on quality, security, and best practices.

Anthropic documents five locations, in priority order: organization-managed settings, the session-only --agents CLI flag, .claude/agents/ (project scope, check it into version control), ~/.claude/agents/ (all your projects), and a plugin's agents/ directory.

Only two frontmatter fields are required. The optional ones that change how a pattern behaves:

FieldWhat it does
toolsAllowlist. Omit it and the subagent inherits the conversation's tools.
disallowedToolsDenylist against the inherited pool -- the easy way to say "everything except Write and Edit".
modelsonnet, opus, haiku, fable, a full model ID, or inherit (the default).
permissionModedefault, acceptEdits, auto, dontAsk, bypassPermissions, or plan.
maxTurnsHard stop on agentic turns. The cheapest guard against a runaway survey.
memoryuser, project, or local -- persistent notes across invocations.
effortlow, medium, high, xhigh, max.
isolationworktree runs the subagent in its own git checkout.
skills, mcpServers, hooksPreloaded skills, scoped MCP servers, and lifecycle hooks for that subagent only.
backgroundtrue keeps it in the background even when Claude asks for the foreground.

To invoke one deliberately rather than relying on description matching, @-mention it as @"code-reviewer (agent)", which Anthropic documents as guaranteeing execution. To make an entire session run as that subagent, use claude --agent code-reviewer.

Three of These Patterns Now Ship Built In

Before writing a definition, check whether Anthropic already ships it:

  • Explore is a built-in one-shot agent for reading code, which covers most of Pattern 2.
  • Plan is a built-in one-shot agent for designing an approach, which covers much of Pattern 6.
  • /code-review runs a local review of your working diff, a PR, a branch, or a path, with depth scaling to the effort argument. That is Pattern 5 without a definition file.

Built-in Explore and Plan cannot be resumed, and both can be disabled through permissions.deny or the CLAUDE_CODE_DISABLE_EXPLORE_PLAN_AGENTS environment variable. Write your own version of these three when you want a house-specific system prompt, a pinned tool set, or a resumable agent -- not by default.

Pattern 1: The Verifier

Use when: Claude has just finished a non-trivial chunk of work and you want a second opinion before declaring it done.

Why delegate: the parent agent that wrote the code has a confirmation bias toward its own work. A fresh subagent reads the same code with no prior commitment.

Definition: tools: Read, Grep, Glob, Bash -- it needs to run the test command but must not fix what it finds.

Prompt template:

Verify the work I just completed. Here is the spec I started from (paste it), the final code (point to the files), and the test command. Review whether the implementation actually meets the spec, run the tests, and return a list of any gaps, regressions, or questionable choices. Do not make the changes -- just return the findings.

Failure mode to watch: the subagent returns a vague "looks fine" without actually checking. If you do not see specific file references and concrete observations in the report, re-prompt with explicit verification criteria.

This is the highest-ROI pattern in the list. Use it after every significant agent-driven change before you ship.

Pattern 2: The Codebase Scout

Use when: you need to understand how something works in a codebase you do not actively maintain (a vendored library, an internal tool, a reference implementation). Try the built-in Explore agent first.

Why delegate: reading 30 files into the parent context to understand one auth flow burns context on noise. A subagent reads them all, compresses the answer, and returns it.

Definition: tools: Read, Grep, Glob -- strictly read-only.

Prompt template:

Read through {repo path or URL} and return a summary of how {specific subsystem} works. Follow the actual code, not just the README; trace the entry points; identify any non-obvious decisions. Return a 1-2 page summary I can use as context to implement something similar in our codebase.

Failure mode: generic descriptions instead of specifics. Add explicit requirements: "include 3-5 short code excerpts that illustrate the key pattern", "name the files where each concept lives", "call out the design decisions a careful reader would not catch on first read".

Pattern 3: The Spec-to-Tests Translator

Use when: you have a written spec or PRD and want to start with the test suite before writing implementation.

Why delegate: turning prose into test cases is a focused task with a clear deliverable, done in a context where nothing tempts it to start implementing.

Definition: tools: Read, Grep, Glob for the list-only version. Add Write if you want the test files created rather than proposed -- that choice is now yours to make, and it is the single field that decides it.

Prompt template:

Read the spec at {path} and translate it into a list of test cases. For each: the exact test name in our project's naming convention, the inputs, the expected output, and a one-line description of the behavior it covers. Group the tests by which acceptance criterion in the spec they cover.

Failure mode: the subagent invents requirements not in the spec. Anchor it: "do not infer requirements not stated in the spec; if the spec is ambiguous, list the ambiguity rather than picking an answer".

Pattern 4: The Refactor Proposer

Use when: you suspect a refactor would help but want to evaluate the proposal before committing to it.

Why delegate: asking the same session that is mid-feature-work to "also propose a refactor" produces either a half-hearted suggestion or an over-eager one. A fresh subagent has no investment in the current direction.

Definition: tools: Read, Grep, Glob plus maxTurns -- a refactor survey is the classic runaway.

Prompt template:

Examine these files: {list}. Propose a refactor that addresses {specific concern: duplicated logic / unclear responsibilities / fragile coupling}. Identify the specific problems, propose the smallest refactor that addresses them, list the files that would need to change, and call out any risks. Do not perform the refactor. Format as a markdown report I can review before deciding.

Failure mode: a proposal that touches half the codebase. Constrain it: "the proposal must touch fewer than 5 files", "if a clean refactor is not possible at this scope, return that finding".

Pattern 5: The PR Reviewer

Use when: you want a code review on a diff before opening the PR. Start with the built-in /code-review, which already takes a diff, a PR number, a branch, or a path.

Why delegate: the parent session that wrote the code remembers the design discussion and will rationalize the choices. A reviewer that reads only the diff is the closest you get to a fresh pair of eyes.

Definition: tools: Read, Grep, Glob, Bash -- Bash so it can run git diff itself.

Prompt template:

Review the changes in {git diff or PR URL}. Identify any bugs or edge cases the diff introduces, flag any places where the change is hard to understand, note naming or convention violations against {our CLAUDE.md or AGENTS.md}, and identify tests that should exist but do not. Return a structured review with severity (must-fix / should-fix / nit) for each finding.

Failure mode: the subagent praises everything. Add: "Be skeptical. Assume there is at least one issue worth raising. If after careful review there genuinely are none, say so explicitly."

On the paid tier. For a substantial pre-merge change there is also /code-review ultra, which Anthropic documents as a research preview that runs a fleet of reviewer agents in a cloud sandbox and independently reproduces each finding. It typically takes 5 to 10 minutes and bills usage credits: Pro and Max accounts get three one-time free runs that do not refresh, Team and Enterprise get none, and after that a review costs roughly $5 to $25 depending on the size of the change. /ultrareview is an alias for it when the feature is available to your account. It is not available on Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry, or to organizations with Zero Data Retention enabled -- in which case /code-review ultra runs a local review instead. Treat it as a deliberate spend before merging something large, not a habit.

Pattern 6: The Migration Planner

Use when: you need to migrate a codebase from one library or framework to another and want a real plan before touching anything. The built-in Plan agent is the zero-setup version.

Why delegate: migration planning is exploration-heavy. The subagent surveys the dependency surface, maps every call site, and returns a phased plan without the parent absorbing the file-by-file scanning.

Definition: tools: Read, Grep, Glob, and consider model: opus -- classification quality is the whole deliverable here.

Prompt template:

Plan our migration from {library X} to {library Y}. Catalog every file that uses {library X} with line numbers, classify each usage by complexity (trivial rename / non-trivial transform / requires manual decision), produce a phased plan with concrete first steps, and identify any usages that need human input before they can be migrated. Return as a markdown plan I can hand to the team.

Failure mode: the subagent gives up on the survey halfway through. Constrain: "the survey must be exhaustive across the whole repo; if the search is too large, say so and propose how to scope it".

When the plan is agreed and the edits are mechanical, /batch is the documented next step -- Anthropic describes it as a skill that splits one large change into 5 to 30 worktree-isolated subagents that each open a pull request.

Pattern 7: The Bug Hunter

Use when: there is a reproducible bug and you want to investigate without polluting your session with the trail of dead ends.

Why delegate: bug investigation is exploratory and most of the exploration is wrong. The parent sees the conclusion, not the 20 turns of hypothesis-testing that came before.

Definition: tools: Read, Grep, Glob, Bash -- it needs to reproduce. Keep Edit out so the analysis stays an analysis.

Prompt template:

Investigate this bug: {repro steps + observed behavior + expected behavior}. Form hypotheses, test each against the code, narrow to the most likely cause, and return: the file and line where the bug lives, why it produces this behavior, the smallest change that would fix it, and the test that should be added to prevent regression. Do not apply the fix.

Failure mode: the subagent commits to the first plausible hypothesis. Anchor it: "consider at least three hypotheses before settling; if the evidence is genuinely insufficient to choose, return the top hypotheses with their evidence rather than picking arbitrarily".

Pattern 8: The Docs Generator

Use when: you have shipped a feature and need to write docs for it.

Why delegate: writing docs requires reading the changes carefully and synthesizing them. The subagent does that reading in its own context and returns the finished doc.

Definition: this is the clearest case for a writing subagent, tools: Read, Grep, Glob, Write. Point Write at your docs directory and let it produce the file rather than a wall of markdown in your terminal.

Prompt template:

Write user-facing docs for the changes in {PR / commit range / set of files}. Identify what user-visible behavior changed, write the doc as a single markdown page following the structure in {existing doc path as a template}, include a "what you can do with this" section with concrete use cases, and add example code or commands where useful.

Failure mode: the docs are written in a different voice than your existing docs. Always pass an existing doc as a style template; a subagent that has never seen your docs produces generic prose.

Pattern 9: The Convention Detective

Use when: you joined a new codebase, or your team is formalizing conventions and you want to extract the patterns that already exist.

Why delegate: extracting conventions requires reading a large amount of code looking for patterns. The parent never has to load the full survey.

Definition: tools: Read, Grep, Glob, and memory: project is worth considering -- conventions accumulate, and a subagent with project memory can build on what it found last time.

Prompt template:

Read through {directory or file pattern} and identify the conventions this codebase uses: naming conventions (functions, files, variables), error handling patterns, testing patterns, import organization, and any non-obvious idioms. For each, include 2-3 example file references. Return as a markdown list I can use as the basis for our CLAUDE.md or AGENTS.md.

Failure mode: the subagent reports the obvious and misses the subtle. Add: "include at least three non-obvious idioms that a new contributor would not catch by reading style guides".

This pattern is particularly valuable when consolidating multiple agent tools' configuration files; for the cross-tool comparison see Codex CLI vs Claude Code vs Cursor architecture.

Pattern 10: The Library Briefer

Use when: you need to use a library you have not used before and want a focused summary instead of the full docs.

Why delegate: the parent's training data has whatever the library looked like months ago. A subagent that fetches live docs returns something current.

Definition: tools: WebFetch, WebSearch, Read, Write -- the one pattern in the list whose tool set is mostly outside the repo.

Prompt template:

Read the docs at {URL} for {library name} and produce a focused brief covering {specific concern: how to do X, the most idiomatic patterns, common pitfalls}. Include code examples for the patterns I will most likely need. Cite the docs URL section for each claim. Return as markdown I can paste into a working note.

Failure mode: the brief is too generic. Anchor it tightly: "I am specifically trying to do {very specific thing}. Optimize the brief for that concrete use case, not for a general overview".

Combining the Patterns

The patterns work alone but compound when combined. Two combinations worth knowing:

  • Pattern 4 then Pattern 5. Refactor Proposer plans the change, you accept the plan, then PR Reviewer reviews the implemented diff. Two subagents, one human approval, no parent-context pollution.
  • Pattern 7 then Pattern 1. Bug Hunter finds the bug, you or the parent implement the fix, Verifier checks the fix addresses the cause. The Bug Hunter's analysis is part of the Verifier's input -- the subagents share artifacts even though their contexts are separate.

Three documented mechanics change what a combination can be:

  • Forks. /subtask starts a subagent that inherits your full conversation history, system prompt, tools, and model, and shares the prompt cache, which Anthropic notes is cheaper than a fresh subagent. A fork cannot spawn further forks. With agent view turned off the command is /fork instead.
  • Background execution. A background subagent runs concurrently while you keep working, and its permission prompts surface in the main session naming the subagent. /tasks lists everything running in the background of the session, including subagents that have finished.
  • Worktree isolation. isolation: worktree gives a subagent its own git checkout, which is what makes several editing subagents at once safe rather than a merge accident.

When the job outgrows a handful of subagents, Anthropic points to dynamic workflows -- a script that runs many subagents and cross-checks their results, for a codebase-wide audit or a several-hundred-file migration.

When Not to Use Subagents

Subagents are not free. They take time, they consume model budget, and Anthropic notes plainly that running several at once multiplies token usage. Skip them when:

  • The task is small enough to do inline (rename a function, fix a one-line bug).
  • The work depends heavily on context the subagent would not have. This is the real constraint: a non-fork subagent receives your CLAUDE.md, git status, and preloaded skills, but not the conversation history. An in-progress design discussion does not travel. A fork does carry it, which is what /subtask is for.
  • You are in a fast iteration loop where round-tripping breaks flow.

Note what is no longer on this list. "The deliverable is not a written report" used to be a reason to stay in the parent, on the theory that subagents only pass back text. They do not: a subagent with Edit or Write in its tools changes files directly. The question is not whether a subagent can do the work but whether you want it done in an isolated context, and whether it should have its own worktree while it does.

The honest rule: if the answer to "would I want this done by a separate teammate so I do not have to context-switch?" is yes, it is a subagent task. If you would rather just do it yourself in 30 seconds, stay in the parent.

A Realistic First Week With These Patterns

Pick three patterns and try them on real work this week:

  • Day 1-2: Write the Verifier (Pattern 1) as an actual file in .claude/agents/ and use it on every non-trivial chunk of agent work. Writing it once is the point -- a pattern you retype is a pattern you stop using.
  • Day 3-4: Run the built-in /code-review on at least two of your own diffs before opening the PR. Notice what it catches that you missed, and only then decide whether a custom reviewer definition earns its keep.
  • Day 5-7: Pick one of the Bug Hunter (7), Refactor Proposer (4), or Codebase Scout (2). Try the built-in Explore agent against your own Codebase Scout definition and keep whichever gives the better report.

By end of week one you will have a felt sense of which patterns fit your workflow. The point of subagents is not to use them on everything; it is to have them defined and ready for the moments when they are the right tool.

For the broader Claude Code workflow stack -- routines, auto mode, effort levels -- our Claude Opus 4.7 best practices guide is the companion piece.

Sources

All of the following were fetched and re-verified on August 15, 2026:

Frequently Asked Questions

What is a Claude Code subagent?

A subagent is a delegated worker spawned from your session that runs in its own context window and returns only its final report to the parent. Anthropic's docs state a subagent receives its custom system prompt, the task delegation message, your CLAUDE.md files, git status, preloaded skills, and a roster of sibling agents -- but not the parent's conversation history. The exploration and tool output stay walled off in the subagent's context.

Where do Claude Code subagents live?

Subagents are markdown files with YAML frontmatter. Anthropic documents five locations in priority order: organization-managed settings, the session-only --agents CLI flag, .claude/agents/ for the current project, ~/.claude/agents/ for all your projects, and a plugin's agents/ directory. Only name and description are required fields; tools, model, permissionMode, memory, effort, and isolation are optional.

Can a Claude Code subagent edit files?

Yes. Anthropic's subagent reference states subagents can edit files if you include Edit or Write in their tools list. A subagent with tools set to Read, Grep, Glob is read-only by construction; one with Read, Edit, Bash, Grep, Glob can change your working tree. You can also use disallowedTools to remove Write and Edit from an otherwise inherited tool pool.

Can subagents spawn more subagents?

Yes. Anthropic documents a default nesting depth of three layers below the main conversation, changed with the CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH environment variable and disabled entirely by setting it to 1. The default concurrency limit is 20 simultaneous subagents, changed with CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS. Forked subagents started with /subtask cannot spawn further forks.

How do I invoke a specific subagent?

Four documented ways. Claude delegates automatically by matching your task against a subagent's description field. Plain language ('use the code-reviewer to analyze these changes') lets Claude decide. An @-mention of the form @"code-reviewer (agent)" guarantees execution. Running claude --agent code-reviewer, or setting agent in .claude/settings.json, makes the whole session use that subagent's configuration.

Does the /agents command still open a panel?

No. As of Claude Code v2.1.198 the /agents wizard was removed; the command now prints a notice pointing to the subagent file locations. Create and edit subagents by asking Claude or by editing files in .claude/agents/ or ~/.claude/agents/ directly, which Claude Code auto-detects within seconds. Note that /agents is a different thing from the claude agents command, which opens agent view.

Get the weekly AI Catchup

Tools, practices, and what matters, in your inbox every week.