Module 6: Subagents: delegating work to specialized agents

Custom Subagents: building specialized agents to fit your project

Custom Subagents: building specialized agents to fit your project

Overview

Claude Code's built-in subagents cover generic patterns: explore, plan, execute, run commands. But every project has specific tasks that repeat and would benefit from a dedicated agent. Need an agent that reviews code against your team's standards? One that generates documentation in your format? One that writes tests following your exact conventions?

That's what custom subagents are for: agents you define with specific instructions, allowed tools, and clear restrictions. Custom subagents live in .claude/agents/ as markdown files, and Claude Code uses them when they're relevant to the task. They're the natural evolution of skills — the same specialization philosophy, but with the full capability of an independent agent.

This capsule teaches you to build custom subagents from scratch: file structure, tool configuration, defining restrictions, and patterns for team subagents. By the end, you'll know when to use a skill and when to use a custom subagent — and how to build them so they stay maintainable and useful.


What custom subagents are

A custom subagent is a markdown file with YAML frontmatter in .claude/agents/ (or another scope) that defines a specialized agent. When Claude Code detects that a custom subagent is relevant to the task, or when you invoke it directly, it creates an agent instance with the instructions and restrictions you defined.

The /agents command — the recommended way to create them

Instead of writing the file by hand, Claude Code offers /agents: an interactive interface for managing subagents.

> /agents

This opens an interface with tabs:

  • Running: subagents active in the current session
  • Library: every available subagent (built-in, user, project, plugin)

From Library you can:

  • Create new agent (guided or generated by Claude)
  • Edit existing subagents
  • See which subagent wins when there are duplicates
  • Delete custom subagents

Recommendation: Use /agents to create your first subagents. By the time you want to edit the file by hand, you'll know what's in it.

CLI command to list subagents

From the terminal, without launching Claude Code interactively:

claude agents

It shows every subagent grouped by source (built-in, user, project, plugin) and flags which ones are overridden by higher-priority definitions.

Subagent scopes (where they live)

LocationScopePriority
Managed settingsThe whole organization1 (highest)
--agents CLI flagCurrent session2
.claude/agents/Current project3
~/.claude/agents/All your projects4
Plugin agents/Wherever the plugin is active5 (lowest)

Resolution rules:

  • Same name in multiple scopes → the highest priority wins
  • .claude/agents/ is discovered by walking up from your current directory (works in monorepos)
  • --add-dir does NOT add subagents (it only grants file access)

Inline subagents via CLI (the --agents flag)

For quick testing or automation, you can define subagents inline as JSON when you launch Claude Code:

claude --agents '{
  "code-reviewer": {
    "description": "Expert code reviewer. Use proactively after code changes.",
    "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
    "tools": ["Read", "Grep", "Glob", "Bash"],
    "model": "sonnet"
  },
  "debugger": {
    "description": "Debugging specialist for errors and test failures.",
    "prompt": "You are an expert debugger. Analyze errors, identify root causes, and provide fixes."
  }
}'

Useful for CI/CD scripts where you don't want to commit a subagent but you do want to use a specific one.


YAML Frontmatter: the current subagent format

Custom subagents use the same format as Skills: YAML frontmatter + markdown content.

---
name: code-reviewer
description: Expert code reviewer. Use proactively after code changes to catch issues.
tools:
  - Read
  - Grep
  - Glob
  - Bash
model: sonnet
color: purple
memory: project
---

You are a senior code reviewer specialized in this codebase.

Your role: review changes and provide actionable feedback.

## Rules
- Focus on: correctness, performance, maintainability, security
- Don't make changes — only report findings
- Classify each finding: critical, warning, suggestion
- Reference exact file:line

## Project conventions
- TypeScript strict (no `any`)
- Pure functions when possible
- Explicit error handling

## Output format
For each finding:
- **[TYPE]** file:line — Problem description
- Suggestion

The main frontmatter fields

FieldDescription
descriptionWhen to use this subagent. Claude uses this to delegate automatically.
prompt / markdown bodyThe subagent's system prompt
toolsArray of available tools. If you omit it, it inherits all of them
disallowedToolsTools explicitly blocked
modelSpecific model (haiku, sonnet, opus, or inherit from the parent)
permissionModePermission mode (default, acceptEdits, bypassPermissions)
mcpServersMCP servers specific to the subagent
hooksHooks scoped to this subagent
maxTurnsMaximum turns before it stops
skillsSkills preloaded when the subagent starts
initialPromptThe subagent's first message
memoryEnable persistent memory (none, project, user)
effortEffort level (low, medium, high, etc.)
backgroundRun in the background
isolationworktree = create a temporary worktree
colorColor in the UI (for visual identification)

Persistent subagent memory

An important feature: subagents can have persistent memory across sessions.

With memory: project, the subagent accumulates insights in .claude/agent-memory/<name>/ — every time the subagent runs, it adds to that directory.

With memory: user, the memory lives in ~/.claude/agent-memory/ — it persists across all your projects.

Typical use case: A code-reviewer that learns the team's recurring problem patterns and remembers them in future reviews. A debugger that accumulates the project's common errors.

---
name: code-reviewer
description: Code reviewer with memory of recurring patterns
memory: project
---

After several reviews, the .claude/agent-memory/code-reviewer/ directory holds files with accumulated insights that the subagent reads on startup.

initialPrompt — auto-submitting the first turn (March 2026)

A recent feature: in the subagent's frontmatter you can declare an initialPrompt that gets auto-submitted as the first message the moment the subagent starts. Useful when the subagent always needs to do the same thing at the outset.

Example: a security-scanner subagent that always starts by scanning:

---
name: security-scanner
description: Scans code for security vulnerabilities
tools: [Read, Grep, Glob]
model: sonnet
initialPrompt: |
  Scan the codebase for:
  1. Hardcoded secrets (API keys, tokens, passwords)
  2. SQL injection vulnerabilities
  3. XSS vectors in templates
  4. Dependencies with known CVEs

  For each finding: file, line, severity (critical/high/medium/low), and a suggested fix.
---

You are a security scanner specialized in web applications.
Your role: find security problems, not create them.

Rules:
- Never modify code, only report
- Classify each finding by severity
- Include CVE IDs where they apply
- Prioritize by real impact, not just theoretical impact

When you invoke this subagent with /agents or via delegation, Claude Code automatically runs the initialPrompt as the first instruction — the subagent starts already working, without you having to give it the first order.

Useful when:

  • The subagent always does the same thing on startup
  • You want to reduce delegation friction
  • The "initial prompt" is part of the subagent's contract

Where they live

your-project/
├── .claude/
│   ├── agents/
│   │   ├── code-reviewer.md
│   │   ├── test-writer.md
│   │   ├── doc-generator.md
│   │   └── migration-agent.md
│   ├── skills/
│   │   ├── create-component.md
│   │   └── write-test.md
│   ├── settings.json
│   └── settings.local.json
├── CLAUDE.md
├── src/
└── ...

The structure is similar to skills: markdown files in a specific directory. The key difference is the directory (.claude/agents/ vs .claude/skills/) and the nature of the content.

How they're invoked

Custom subagents can be invoked in several ways:

  1. Directly: Claude Code detects them as available agents
  2. By name: You can refer to them in your prompt
  3. Automatically: If Claude Code detects that the task matches the subagent's purpose
You: Use the code-reviewer agent to review the changes
     I just made.
You: I need to document the payments module. Use the
     doc-generator.

The structure of a custom subagent

A custom subagent is a markdown file with sections that define its behavior. The structure is flexible, but these are the key elements:

Basic structure

# Code Reviewer

You are an agent specialized in code review for
this project.

## Your role
You review code against the project's standards and
provide actionable feedback.

## Rules
- Focus on: correctness, performance, maintainability
- Do NOT change the code — only report findings
- Classify each finding: critical, warning, suggestion
- Reference the exact file and line

## Project conventions
- Strict TypeScript (never use any)
- Pure functions when possible
- Explicit error handling (don't swallow errors)
- Tests for all business logic

## Output format
For each finding, use:
- **[TYPE]** file:line — Description of the problem
- Suggested fix

Configuration elements

Name and purpose

The filename defines the subagent's identity. Claude Code uses it to decide when to activate it:

FilenamePurpose
code-reviewer.mdCode review
test-writer.mdTest generation
doc-generator.mdDocumentation
migration-agent.mdData/code migrations
security-auditor.mdSecurity auditing

Best practice: Use descriptive names that reflect the purpose. Claude Code uses the name to judge relevance.

Instructions (the core of the subagent)

The instructions define what the subagent does and how. Write them as if you were explaining to a new developer exactly how to do the task:

## Instructions

When asked to write tests:

1. Read the file that's going to be tested
2. Identify every exported function
3. For each function:
   a. Determine the valid and invalid inputs
   b. Identify edge cases (null, undefined, empty, overflow)
   c. Write tests covering the happy path and at least 2 edge cases
4. Use the describe/it pattern with descriptive names
5. Use factories for test data (see __tests__/factories/)
6. Never mock the database — use the test database

Restrictions (what it must NOT do)

Restrictions are as important as instructions. They define the subagent's limits:

## Restrictions

- Do NOT modify production files (test files only)
- Do NOT change the Vitest configuration
- Do NOT add new dependencies without listing them in the report
- Do NOT generate tests for private (non-exported) functions
- Do NOT use snapshots — we prefer explicit assertions

Project context

You can include relevant information the subagent needs:

## Project context

- Test framework: Vitest
- Test database: SQLite in-memory
- Factories: in __tests__/factories/ using the factory pattern
- Fixtures: in __tests__/fixtures/ for static data
- Minimum coverage: 80% branches
- CI runs: vitest run --coverage

Custom subagent examples

Example 1: Code Reviewer Agent

# Code Reviewer

You are a code reviewer specialized in this project.

## Your role

You review pull requests and code changes against the project's
standards. Your output is a review report, not changes to the
code.

## What to review

### Correctness
- Is the logic correct?
- Are all edge cases handled?
- Are there race conditions or concurrency problems?

### TypeScript
- Is `any` used? (banned in this project)
- Are the interfaces properly typed?
- Are type guards used where they apply?

### Error handling
- Are errors caught correctly?
- Are the project's custom error classes used?
- Are errors logged before re-throwing?

### Performance
- Are there N+1 queries?
- Is pagination used in queries that could return many results?
- Are there expensive computations that should be cached?

### Tests
- Do the changes have matching tests?
- Do the tests cover edge cases?

## Report format

Code Review Report

Critical (blocks merge)

  • [CRITICAL] file:line — description Suggestion: ...

Warnings (should be fixed)

  • [WARNING] file:line — description Suggestion: ...

Suggestions (nice to have)

  • [SUGGESTION] file:line — description Suggestion: ...

Verdict

APPROVED / CHANGES_REQUESTED / NEEDS_DISCUSSION


## Restrictions

- Do NOT modify any file
- Do NOT run commands
- Only read and analyze
- If you don't understand something, say so instead of assuming

Example 2: Test Writer Agent

# Test Writer

You are an agent specialized in writing tests for this project.

## Your role

You generate unit and integration tests following the project's
exact conventions. You don't implement features —
you only write tests.

## Testing conventions

### File structure
- Unit tests: colocated with the module in `__tests__/[name].test.ts`
- Integration tests: in `__tests__/integration/[name].integration.test.ts`
- Factories: in `__tests__/factories/[entity].factory.ts`

### Naming
- `describe('ClassName')` or `describe('functionName')`
- `it('should [expected behavior] when [condition]')`
- Example: `it('should return null when user is not found')`

### Patterns
- Use Vitest: describe, it, expect, vi (for mocks)
- Arrange-Act-Assert in every test
- Factories to create test data (never hardcode data)
- Independent tests: every test must be able to run on its own
- Don't share mutable state between tests

### Database
- Unit tests: mock the repository layer
- Integration tests: use SQLite in-memory
- Always clean the DB between tests (beforeEach → truncate)

## Process

1. Read the file to be tested
2. Identify every public function/method
3. For each one, generate:
   - A happy path test
   - At least 2 edge cases
   - Error cases (what happens when it fails)
4. If a factory already exists for the entity, use it
5. If there's no factory, create it in __tests__/factories/
6. Run the tests to verify they pass

## Restrictions

- Do NOT modify production files
- Do NOT change existing tests (only add new ones)
- Do NOT use snapshot testing
- Do NOT import from absolute paths (use the project's @ aliases)
- If a test fails, report the error — don't silently fix it

Example 3: Documentation Agent

# Documentation Generator

You are an agent specialized in generating technical documentation
for this project.

## Your role

You generate and update technical documentation: module READMEs,
JSDoc/TSDoc, and usage guides. The documentation has to be useful
for developers joining the team.

## Documentation types

### Module README
For each main directory in src/, generate a README.md with:
- The module's purpose (1-2 paragraphs)
- File structure
- Main interfaces (with usage examples)
- Dependencies on other modules

### TSDoc for exported functions
```typescript
/**
 * Brief description of what the function does.
 *
 * @param paramName - Description of the parameter
 * @returns Description of return value
 * @throws {ErrorType} When this error can occur
 *
 * @example
 * ```typescript
 * const result = functionName(input);
 * ```
 */

Usage guides

For complex features, generate a guide with:

  • What problem it solves
  • How to use it (code examples)
  • Required configuration
  • Common troubleshooting

Conventions

  • Spanish for READMEs and guides
  • English for TSDoc (industry standard)
  • Code examples must always be runnable (no pseudocode)
  • Maximum 200 lines per document
  • No emojis in technical documentation

Restrictions

  • Do NOT modify production code
  • Do NOT generate documentation for test files
  • Do NOT document internal (non-exported) functions
  • Verify that the code examples compile

### Example 4: Migration Agent

An agent for database migrations with Knex. It includes: the migration process (analyze → generate the file with `up`/`down` → verify rollback → run against the test DB → confirm tests), naming conventions (`YYYYMMDD_HHMMSS_description.ts`), and restrictions (no production, no DROP without confirmation, don't modify migrations that already ran). Same pattern as the others: role + process + conventions + restrictions.

---

## Skill vs Subagent: when to use each

This is the most important decision in this module. Skills and subagents complement each other, but they aren't interchangeable.

### Head-to-head comparison

| Criterion | Skill | Custom Subagent |
|---|---|---|
| **What it is** | Markdown instructions | A full agent with its own context |
| **Location** | `.claude/skills/` | `.claude/agents/` |
| **How it's invoked** | `/name` (slash command) | By name or automatically |
| **Context** | Shares the parent's context | Its own isolated context |
| **Reasoning** | Follows instructions step by step | Reasons, decides, executes |
| **Ideal complexity** | Tasks of 5-15 steps | Tasks that require analysis + decisions |
| **Example** | "Create a component with these 7 steps" | "Review the code and give me a report" |

### Decision tree

Does the task have fixed, predictable steps? ├── YES → Does it need reasoning to decide what to do? │ ├── NO → SKILL (direct instructions) │ └── YES → CUSTOM SUBAGENT (an agent that reasons) └── NO → CUSTOM SUBAGENT (it needs flexibility)

Examples:

  • "Create a React component with CSS Modules" → SKILL (fixed steps: create file, create styles, create test, barrel export)

  • "Review this PR against our standards" → SUBAGENT (needs to analyze, reason, classify findings)

  • "Generate documentation for this module" → SUBAGENT (needs to understand the code to document it)

  • "Add a new CLI command with boilerplate" → SKILL (fixed steps: create file, register command, create test)


### When to migrate a skill to a subagent

Signs that a skill needs to become a subagent:

1. **The skill requires decisions:** "If the file already exists, update it. If not, create it." — that requires reasoning, not just steps.
2. **The output is variable:** A skill that always produces the same thing can stay a skill. If the output depends on analysis, it needs a subagent.
3. **It needs to read a lot of context:** If the skill has to analyze 10+ files before acting, a subagent with isolated context is more efficient.
4. **It has complex conditional logic:** "If it's a Sequelize model, do X. If it's TypeORM, do Y. If it's Prisma, do Z." — a subagent handles that complexity better.

### When NOT to create a subagent

- The task is solved by a hook (simple automation)
- The task is a linear instruction with no decisions
- It won't be reused (it's a one-off task)
- A built-in subagent already does the same thing

---

## Best practices for custom subagents

### 1. Single responsibility

Every subagent should have one clear, bounded purpose. Don't build a subagent that "reviews code, generates documentation, and writes tests" — build three separate subagents.

❌ all-in-one-agent.md (does everything) ✅ code-reviewer.md (only reviews code) ✅ test-writer.md (only writes tests) ✅ doc-generator.md (only generates documentation)


### 2. Explicit restrictions

Always define what the subagent must NOT do. Restrictions matter more than instructions because they prevent damage:

```markdown
## Restrictions
- Do NOT modify production files
- Do NOT run destructive commands (rm, DROP)
- Do NOT install dependencies without listing them first
- Do NOT silently ignore errors

3. Project context included

Don't assume the subagent knows how your project works. Include the necessary information directly in the file:

## Project context
- Framework: Next.js 14 with App Router
- ORM: Prisma with PostgreSQL
- Tests: Vitest + Testing Library
- Styling: Tailwind CSS
- Linting: ESLint + Prettier

4. A defined output format

Define exactly how you want the subagent's output. This makes the results consistent and predictable:

## Output format

### For each issue found:
**[SEVERITY]** `file:line`
> Description of the issue
>
> Suggestion: [how to fix it]

### At the end of the report:
- Total issues: N
- Critical: N | Warning: N | Suggestion: N
- Verdict: PASS / FAIL

5. Test with simple tasks first

Before trusting a custom subagent with critical tasks, try it on something simple:

You: Use the code-reviewer agent to review the file
     src/utils/format.ts. It's a small file — I want
     to see if the agent follows the conventions I defined.

If the output doesn't match what you expected, adjust the subagent's instructions.


Common patterns

Pattern 1: Review before merge

Create a code-reviewer.md and use it before every PR:

You: Review the files I modified in this session
     using the code-reviewer agent. Give me the report
     before I commit.

Pattern 2: Documentation after implementation

After implementing a feature, generate documentation automatically:

You: I just implemented the notifications module.
     Use the doc-generator agent to document the
     public interfaces and create the module's README.

Pattern 3: Tests in parallel with implementation

While you implement, a subagent can write tests:

You: Implement the payments service. In parallel, have
     the test-writer agent generate the tests based on
     the interface I'm defining.

Pattern 4: Chaining subagents

One subagent's output feeds the next:

Step 1:
You: Use the code-reviewer agent to analyze the
     authentication module.

[Claude Code produces the report]

Step 2:
You: Based on the critical issues in the report,
     fix the problems it found.

Step 3:
You: Now use the test-writer agent to add tests
     covering the edge cases the reviewer identified.

This chain — review → fix → test — is a complete quality pipeline run by subagents.

Pattern 5: An onboarding subagent

For team projects, create a subagent that helps new members understand the codebase. An onboarding-guide.md covering: overall architecture, how to add features, how to run tests, conventions, and main dependencies. Concise answers with references to concrete files.


Pitfalls and edge cases

Pitfall 1: A subagent that's too generic

A subagent that says "helps with everything" is no more useful than the main agent. Specificity is what makes subagents valuable:

❌ general-helper.md → "Helps with any task in the project"
✅ code-reviewer.md → "Reviews code against specific standards"

Pitfall 2: Instructions that contradict CLAUDE.md

If your CLAUDE.md says "use CSS Modules" but your subagent says "use styled-components", you have a conflict. Keep it consistent:

❌ CLAUDE.md: "CSS Modules" + subagent: "styled-components"
✅ CLAUDE.md: "CSS Modules" + subagent: "When creating styles,
   follow the project's CSS Modules convention"

Rule: Subagents should reference and respect CLAUDE.md, not contradict it.

Pitfall 3: Subagents with no restrictions

A subagent with no restrictions can do unexpected things. Always define what it must NOT do:

❌ Only instructions about what to do
✅ Instructions + clear restrictions

Pitfall 4: Too many subagents

More subagents isn't better. If you have 15 subagents, Claude Code won't know when to use each one:

❌ 15 hyper-specific subagents
✅ 3-5 well-defined, clearly distinct subagents

Rule: Start with 2-3 subagents that cover your most repetitive tasks. Add more only when you have a clear need.

Pitfall 5: Not testing the subagent

Creating a subagent and assuming it works is a common mistake. Try it on a simple case where you know the expected result, an edge case to verify the restrictions, and a real case to validate that it's useful.

Edge case: A subagent that contradicts the user

If the user asks for something that violates the subagent's restrictions, the subagent should report the conflict — not silently violate its restrictions.

Edge case: Multiple applicable subagents

If you have code-reviewer.md and security-auditor.md, and the task is "review the code's security", Claude Code may pick one or use both. Make the names and purposes clearly distinct to avoid ambiguity.


Complete worked example

Scenario: Setting up a quality pipeline with custom subagents

You're going to build 3 custom subagents for a Node.js/TypeScript project that, used in sequence, form a quality pipeline.

Step 1: Create the 3 subagents

Create the following files in .claude/agents/:

code-reviewer.md — Reviews TypeScript code against the project's standards (strict TypeScript, functions < 30 lines, files < 300 lines, explicit error handling). Output with findings classified as CRITICAL/WARNING/OK. Read-only.

test-writer.md — Writes tests with Vitest. Conventions: colocated files, describe/it/Arrange-Act-Assert pattern, factories in __tests__/factories/. For each function: happy path + 2 edge cases + 1 error case. Doesn't modify production, doesn't use snapshots.

doc-generator.md — Generates technical documentation in Spanish. Module README (max 150 lines with a diagram and a real example), TSDoc in English for exported functions. Doesn't document internal functions or tests.

Step 4: Use the pipeline

Session 1 — You implement a new feature:
You: Implement the product search endpoint.

Session 2 — Review:
You: Use the code-reviewer agent to review the files
     I created for product search.
[Report: 2 warnings, 1 suggestion]

You: Fix the warnings in the report.

Session 3 — Tests:
You: Use the test-writer agent to generate tests for
     the product search module.
[Tests generated: 12 tests, 100% passing]

Session 4 — Documentation:
You: Use the doc-generator agent to document the
     product search module.
[README generated + TSDoc added]

The full pipeline: implement → review → test → document. Each step with a specialized agent.


Practice exercises

Exercise 1: Build your first custom subagent

Create a subagent in .claude/agents/code-reviewer.md adapted to your project. Include:

  1. Name and role
  2. At least 5 standards specific to your project
  3. A defined output format
  4. At least 3 restrictions

Try it on an existing file in your project.

Guide solution

The file should follow the structure shown in this capsule. The standards must be specific to YOUR project, not generic. Example of verification:

You: Use the code-reviewer agent to review src/services/user.ts

Expected result: a report with findings classified
by severity, following the format you defined.

If the report doesn't follow your format, check your subagent's "Output format" section. If the findings don't reflect your standards, check the standards section.

Exercise 2: Skill vs Subagent — decide correctly

For each task, decide whether you need a skill or a custom subagent, and justify it:

  1. Create a new REST endpoint with the standard boilerplate
  2. Review a PR against the team's conventions
  3. Generate a React component with tests and styles
  4. Analyze the technical debt in a module
  5. Add logging to every function in a service
  6. Generate the changelog for a release
Solution
  1. Skill — fixed steps: create route file, controller, service, test. Always the same steps.
  2. Subagent — it has to reason about the code; there are no fixed steps. Every PR is different.
  3. Skill — fixed steps: create .tsx, .module.css, .test.tsx, index.ts. Same structure every time.
  4. Subagent — it has to analyze, classify, and reason about what "technical debt" means in your context.
  5. Skill or subagent — depends. If the logging pattern is always the same → skill. If it has to decide what to log → subagent.
  6. Subagent — it has to read commits, understand changes, classify by type (feature, fix, breaking).

Exercise 3: Build a test-writer subagent

Create .claude/agents/test-writer.md for your project. Make sure to include:

  1. Your testing framework (Vitest, Jest, Mocha, etc.)
  2. Your naming conventions
  3. Where the tests live in your project
  4. How you handle test data (factories, fixtures, etc.)

Try it: ask it to generate tests for an existing file.

Verification

The subagent should:

  • Generate tests in the right location
  • Use the right framework (not Jest if you use Vitest)
  • Follow your naming convention
  • Create factories/fixtures if your project uses them

If it fails on any of these, adjust the subagent's instructions.

Exercise 4: A 3-subagent pipeline

If you completed exercises 1 and 3, you already have a code-reviewer and a test-writer. Create a doc-generator and run the full pipeline on a feature in your project:

  1. Implement a small change
  2. Use code-reviewer → analyze the result
  3. Use test-writer → verify the tests
  4. Use doc-generator → verify the documentation
What to evaluate

Evaluate:

  • Did each subagent follow its instructions?
  • Did the reports use the format you defined?
  • Were the restrictions respected? (e.g. did the reviewer refrain from modifying files?)
  • Does the pipeline flow naturally? (e.g. do the reviewer's issues give you useful information about what to test?)

If the pipeline feels disconnected, adjust the output formats so information flows from one subagent to the next.

Exercise 5: A team subagent

Think about your team (real or hypothetical). What repetitive task would benefit from a shared subagent? Build it and document:

  1. What problem it solves
  2. Why a subagent and not a skill
  3. How a teammate who has never seen it would use it
Evaluation criteria

A good team subagent:

  • Solves a problem the team has regularly (not once a year)
  • Is self-explanatory (a teammate can use it without extra documentation)
  • Has restrictions that make it safe (it can't break anything)
  • Produces consistent output (anyone gets the same kind of result)

Real examples from teams:

  • pr-description-generator.md — generates consistent PR descriptions
  • migration-validator.md — verifies that migrations have a rollback
  • api-contract-checker.md — verifies that endpoints follow the OpenAPI contract

Summary

Custom subagents are your tool for building specialized agents that understand your project and your conventions. Unlike skills (step-by-step instructions), subagents reason, analyze, and make decisions.

What you learned in this capsule:

  • Custom subagents live in .claude/agents/ as markdown files
  • Every subagent has: a name, instructions, context, an output format, and restrictions
  • Skill = fixed, predictable steps. Subagent = reasoning and analysis
  • Subagents should be: focused (single responsibility), restricted (what NOT to do), tested (verify the output)
  • Subagents can be chained to create quality pipelines
  • Start with 2-3 subagents and add more only when there's a clear need
  • Restrictions are as important as instructions

Next capsule: 04 - Plugin marketplace — how to install prebuilt capabilities (skills, hooks, subagents, MCP) from Anthropic's official marketplace with the /plugin command.


Additional resources

Official documentation

Skills vs Subagents

Agent patterns