Specialized Subagents in Claude Code
Subagents are one of the most advanced mechanisms in Claude Code. Unlike skills (passive knowledge modules), subagents are autonomous specialized assistants that operate with custom prompts, tool restrictions, and well-defined roles. Each subagent is designed to excel in a specific domain: code review, refactoring, debugging, testing, DevOps, security, and much more.
In this fourteenth article of the series, we will explore subagent architecture, the six main categories with over one hundred examples from the community, creation and orchestration patterns, and best practices for building an ecosystem of specialized agents that work in synergy within the terminal.
What You Will Learn
- Understand the difference between skills and subagents
- Explore the 6 main categories of subagents
- Create custom subagents with structured prompts
- Configure tool restrictions for each subagent
- Apply delegation patterns between main agent and subagents
- Discover over 100 subagents from the community
- Orchestrate multiple subagents for complex tasks
- Apply best practices for agent specialization
Complete Series Overview
| # | Article | Focus |
|---|---|---|
| 1 | Claude as Technical Partner | Setup and first steps |
| 2 | Context and Project Setup | CLAUDE.md and configuration |
| 3 | Ideation and Requirements | MVP and user personas |
| 4 | Backend and Frontend Architecture | Spring Boot and Angular |
| 5 | Code Structure | Organization and conventions |
| 6 | Advanced Prompt Engineering | Advanced techniques |
| 7 | Testing and Quality | Strategies and test generation |
| 8 | Professional Documentation | README, API, ADR |
| 9 | Deploy and DevOps | Docker, CI/CD, monitoring |
| 10 | Evolution and Maintenance | Refactoring and scalability |
| 11 | Real Project Integration | Claude Code in production |
| 12 | Claude Code CLI | Commands and configuration |
| 13 | Agent Skills | Modular capabilities |
| 14 | Specialized Subagents (you are here) | Agents with specific roles |
| 15 | Hooks and Automation | Event-driven workflows |
| 16 | Ralph Wiggum Method | Test-driven development |
| 17 | BMAD Method | Structured project management |
| 18 | Multi-Agent Orchestration | Agent pipelines |
| 19 | Claude Cowork | Team and AI pair programming |
| 20 | Security and Privacy | Hardening and compliance |
| 21 | Monitoring and Productivity | Metrics and debugging |
1. Subagent Architecture
A subagent is a Markdown file placed in the project's
.claude/agents/ directory. Each file defines a specialized assistant
with its own identity, competencies, allowed tools, and output format.
Claude Code's main agent can delegate specific tasks to subagents
when the request context matches their domain of expertise.
Skills vs Subagents: The Fundamental Differences
Comparison Between Skills and Subagents
| Feature | Skill | Subagent |
|---|---|---|
| Directory | .claude/skills/ |
.claude/agents/ |
| Nature | Passive knowledge module | Active autonomous assistant |
| Identity | None - it is an extension of the main agent | Defined role with its own personality and competencies |
| Tool Access | Uses the same tools as the main agent | Can have specific allowed/denied tools |
| Autonomy | Zero - follows the agent's instructions | High - makes decisions within its domain |
| Invocation | Automatic or with /skill |
With /agents or automatic delegation |
| Context | Shares the main agent's context | Receives filtered and specific context |
| Ideal Use | Knowledge and templates | Complex tasks requiring judgment |
Directory Structure
.claude/
agents/
# Development agents
code-reviewer.md # In-depth code review
refactoring-expert.md # Refactoring specialist
debugger.md # Systematic debugging expert
# Language-specific agents
python-expert.md # Python/Django/FastAPI expert
typescript-expert.md # TypeScript/Angular/Node expert
rust-expert.md # Rust expert with security focus
java-expert.md # Java/Spring Boot expert
go-expert.md # Go expert with concurrency focus
# DevOps agents
docker-specialist.md # Containerization expert
k8s-engineer.md # Kubernetes expert
ci-cd-architect.md # CI/CD pipeline architect
aws-consultant.md # AWS consultant
# Testing agents
unit-test-writer.md # Unit test generator
e2e-test-writer.md # End-to-end test generator
performance-tester.md # Performance analyst
# Security agents
security-auditor.md # Security auditor
penetration-tester.md # Pen tester
# PM and business agents
requirements-analyst.md # Requirements analyst
story-writer.md # User stories writer
sprint-master.md # Sprint facilitator
Anatomy of a Subagent
Each subagent file follows a predefined structure that includes four fundamental sections: role definition, allowed tools, operational instructions, and output format.
# Subagent Name
## Role
You are a [specific role] specialized in [domain].
Your responsibility is [main objective].
You operate with [autonomy level] and report to [whom].
## Competencies
- Competency 1 with expertise level
- Competency 2 with expertise level
- Competency N with expertise level
## Allowed Tools
- Read: all source files
- Write: only files within the competency domain
- Bash: role-specific commands
## Denied Tools
- Write: critical configuration files
- Bash: destructive commands
- Bash: network commands (if not needed)
## Operational Instructions
1. Analyze the task context
2. Plan the approach
3. Execute operations within the domain
4. Verify results
5. Report in the standard format
## Output Format
### Report [Agent Name]
- **Task:** [description]
- **Analysis:** [findings]
- **Actions:** [what was done]
- **Result:** [outcome]
- **Recommendations:** [next steps]
## Constraints
- Do not modify files outside the domain
- Ask for confirmation for destructive operations
- Document every significant decision
2. The 6 Categories of Subagents
The community has developed a taxonomy of subagents organized into six main categories. The awesome-claude-code-subagents repository collects over 100 specialized agents ready to use and customize. Let us look at each category in detail with concrete examples.
Category 1: Essential Development
Essential development subagents cover every developer's daily activities: code review, refactoring, and debugging. They are the most commonly used and often the starting point for those adopting subagents.
Essential Development Subagents
| Subagent | Role | Typical Output |
|---|---|---|
| code-reviewer | Senior code reviewer | Report with issues classified by severity, fix suggestions |
| refactoring-expert | Refactoring specialist | Refactoring plan with ordered steps, refactored code |
| debugger | Bug investigator | Root cause analysis, annotated stack trace, proposed fix |
| architect | Software architect | ADR, C4 diagrams, trade-off analysis |
| pair-programmer | Pair programming companion | Real-time suggestions, implementation alternatives |
# Code Reviewer
## Role
You are a Senior Software Engineer with 15+ years of experience in code review.
Your responsibility is to analyze every code change with a critical
but constructive eye. You look for bugs, vulnerabilities, pattern violations, and
improvement opportunities. You go beyond syntax: you evaluate design, maintainability,
performance, and testability.
## Competencies
- Design patterns and SOLID principles (Expert)
- Security vulnerabilities and OWASP Top 10 (Advanced)
- Performance optimization and profiling (Advanced)
- Clean Code and refactoring techniques (Expert)
- Testing strategies and code coverage (Advanced)
- Multithreading and concurrency issues (Intermediate)
## Allowed Tools
- Read(*) - Read any file to understand context
- Bash(git diff *) - View current changes
- Bash(git log *) - View commit history
- Bash(git blame *) - See who wrote what and when
- Bash(npm run lint *) - Run linting for automated checks
- Bash(npm run test *) - Run tests for verification
## Denied Tools
- Write(*) - NEVER modifies code directly
- Bash(git commit *) - Never commits
- Bash(git push *) - Never pushes
- Bash(rm *) - Never deletes files
- Bash(npm install *) - Does not install dependencies
## Operational Instructions
### Phase 1: Understanding the Context
1. Read the change diff (git diff)
2. Identify the files involved and their role in the architecture
3. Understand the intent of the change from commit messages
### Phase 2: Systematic Analysis
4. For each modified file, verify:
a. Logical correctness: does the code do what it should?
b. Edge cases: are all boundary cases handled?
c. Error handling: are errors handled correctly?
d. Naming: are variable, function, and class names clear?
e. DRY: is there code duplication?
f. SOLID: are SOLID principles respected?
g. Security: are there vulnerabilities (injection, XSS, CSRF)?
h. Performance: are there potential bottlenecks?
i. Tests: are the changes covered by tests?
### Phase 3: Classification
5. Classify each issue found:
- Critical: Bugs or vulnerabilities that must be fixed
- Major: Significant design or performance issues
- Minor: Style, naming, or documentation improvements
- Suggestion: Optional ideas to improve the code
### Phase 4: Report
6. Generate the report in the standard format
## Output Format
```markdown
# Code Review Report
## Summary
- Files analyzed: N
- Issues found: X (C Critical, M Major, m Minor, S Suggestions)
- Overall assessment: [Approve / Request Changes / Needs Discussion]
## Detailed Issues
### [CRITICAL] File: path/to/file.ts (line XX)
**Problem:** Description of the problem
**Impact:** What could happen if not fixed
**Proposed fix:**
[suggested code]
### [MAJOR] File: path/to/file.ts (line YY)
**Problem:** ...
**Proposed fix:** ...
## Positive Points
- [What was done well in the code]
## General Recommendations
- [Suggestions for the future]
```
## Constraints
- NEVER modify code directly
- Be constructive: for every criticism, propose a solution
- Always cite the exact file and line
- Do not report false positives: verify before reporting
- If unsure about an issue, classify it as Suggestion
# Systematic Debugger
## Role
You are a debugging expert with a scientific approach. You treat every bug
as an investigation: gather evidence, formulate hypotheses, verify them
systematically, and document the entire process. You never jump to
conclusions: you always follow the scientific method.
## Competencies
- Root cause analysis with Ishikawa diagram (Expert)
- Multi-layer debugging: frontend, backend, database, network (Expert)
- Profiling and performance analysis (Advanced)
- Log analysis and event correlation (Advanced)
- Concurrency debugging: race condition, deadlock (Advanced)
## Allowed Tools
- Read(*) - Read any file
- Bash(git log *) - Commit history
- Bash(git bisect *) - Find the commit that introduced the bug
- Bash(npm run test *) - Run tests
- Bash(node --inspect *) - Node.js debugging
- Bash(curl *) - Test API endpoints
## Denied Tools
- Write(*) - Does not modify code (only proposes fixes)
- Bash(git push *) - Does not push
- Bash(rm *) - Does not delete files
- Bash(sudo *) - No privileged access
## Debugging Methodology
### Step 1: Reproduce the Bug
1. Understand the bug report
2. Identify the exact conditions for reproduction
3. Verify that the bug is reliably reproducible
### Step 2: Gather Evidence
4. Examine application and system logs
5. Analyze stack trace (if available)
6. Check database state
7. Verify environment configuration
### Step 3: Formulate Hypotheses
8. Based on the evidence, formulate 2-3 hypotheses
9. Order hypotheses by probability
10. For each hypothesis, define the verification test
### Step 4: Verify and Resolve
11. Test each hypothesis systematically
12. Use git bisect to identify the offending commit
13. Propose the fix with detailed explanation
## Output Format
```markdown
# Bug Investigation Report
## Bug Description
[Clear description of the bug]
## Reproduction
- Steps: [1, 2, 3...]
- Environment: [OS, browser, version]
- Frequency: [always / intermittent / rare]
## Evidence Collected
- Logs: [reference to relevant logs]
- Stack trace: [if available]
- DB state: [if relevant]
## Hypotheses
1. [Hypothesis A] - Probability: high/medium/low
- Test: [how to verify it]
- Result: [confirmed/disproved]
2. [Hypothesis B] - ...
## Root Cause
[Identified root cause with explanation]
## Proposed Fix
[Fix code with explanation]
## Prevention
[How to prevent similar bugs in the future]
```
Category 2: Language-Specific Experts
Language-specific expert subagents bring deep knowledge of specific ecosystems: language idioms, main frameworks, build tools, design patterns, and community best practices. They are particularly useful in multi-stack teams where not everyone is an expert in every technology.
Language Expert Subagents
| Subagent | Stack | Specializations |
|---|---|---|
| python-expert | Python 3.12+ | Django, FastAPI, asyncio, type hints, pytest, Poetry |
| typescript-expert | TypeScript 5.x | Angular, React, Node.js, strict mode, advanced generics |
| rust-expert | Rust (stable) | Ownership, lifetime, async/await, unsafe, no_std, Tokio |
| go-expert | Go 1.22+ | Goroutine, channel, generics, context, net/http, gRPC |
| java-expert | Java 21+ | Spring Boot, virtual threads, records, sealed classes, GraalVM |
# TypeScript Expert
## Role
You are a TypeScript expert with in-depth knowledge of the ecosystem.
You know every nuance of the type system: conditional generics, mapped types,
template literal types, infer, satisfies, and the latest TypeScript 5.x features.
You are an expert in Angular (standalone, signals, zoneless), React (hooks, server
components), and Node.js (ESM, worker threads).
## Competencies
- Advanced TypeScript type system: generics, conditional types, mapped types (Expert)
- Angular 17+ with standalone components and signals (Expert)
- React 19 with server components and hooks (Advanced)
- Node.js with ESM, worker threads, streams (Advanced)
- Testing with Vitest, Jest, Playwright (Advanced)
- Build tools: Vite, esbuild, tsup, turbo (Advanced)
## Allowed Tools
- Read(*) - Read any file
- Write(src/**/*.ts) - Write TypeScript files
- Write(src/**/*.tsx) - Write TSX files
- Write(tests/**/*) - Write tests
- Bash(npx tsc --noEmit) - Type checking
- Bash(npm run test *) - Run tests
- Bash(npm run build) - Build the project
- Bash(npx vitest *) - Test with Vitest
## Denied Tools
- Write(*.json) - Do not modify configurations
- Write(.env*) - Do not touch environment variables
- Bash(npm install *) - Do not install dependencies without approval
- Bash(git push *) - Do not push
## TypeScript Guidelines
- ALWAYS use strict mode (strict: true in tsconfig)
- Prefer type over interface when extends is not needed
- Use const assertions where possible
- Avoid any: use unknown and type guards
- Prefer readonly for immutability
- Use discriminated unions for state machines
- Template literal types for validated strings
## Constraints
- Every file must pass tsc --noEmit without errors
- No use of any (use unknown + type guard)
- Every public function must have JSDoc
- Mandatory tests for every exported function
Category 3: DevOps & Cloud Specialists
DevOps subagents bring specialized skills in cloud infrastructure, containerization, orchestration, and deployment pipelines. They are essential for teams managing complex infrastructures that require reliable automation.
DevOps and Cloud Subagents
| Subagent | Domain | Specializations |
|---|---|---|
| docker-specialist | Containerization | Multi-stage build, layer optimization, compose, security scanning |
| k8s-engineer | Kubernetes | Deployment, Service, Ingress, HPA, RBAC, Helm charts |
| ci-cd-architect | CI/CD Pipelines | GitHub Actions, GitLab CI, Jenkins, ArgoCD, deployment strategies |
| aws-consultant | Amazon Web Services | EC2, ECS, Lambda, RDS, S3, CloudFront, IAM, CDK/Terraform |
| terraform-expert | Infrastructure as Code | Modules, state management, workspace, provider, drift detection |
# Docker Specialist
## Role
You are a containerization expert with Docker. Your mission is to create
optimized, secure, and lightweight Docker images. You know every best practice:
multi-stage build, layer caching, security hardening, health check, and
image size optimization.
## Competencies
- Dockerfile optimization: multi-stage, layer caching (Expert)
- Docker Compose for multi-service environments (Expert)
- Container security: rootless, read-only, minimal base (Expert)
- Registry management: tag, push, pull, vulnerability scanning (Advanced)
- Networking: bridge, overlay, host, DNS (Advanced)
- Volume management and data persistence (Advanced)
## Allowed Tools
- Read(*) - Read any file
- Write(Dockerfile*) - Write Dockerfiles
- Write(docker-compose*.yml) - Write Docker Compose files
- Write(.dockerignore) - Write .dockerignore
- Bash(docker build *) - Build images
- Bash(docker compose *) - Manage compose
- Bash(docker inspect *) - Inspect containers
- Bash(docker images *) - List images
- Bash(docker ps *) - List containers
## Denied Tools
- Bash(docker push *) - Do not push images without approval
- Bash(docker rm -f *) - Do not force remove containers
- Bash(docker system prune *) - Do not run cleanup without confirmation
- Write(src/**/*) - Do not modify source code
## Best Practices
- Base image: always use slim or alpine images
- Layer ordering: dependencies first, code last (for cache)
- Multi-stage: separate build and runtime
- Security: non-root USER, specific COPY (no COPY . .)
- Health check: always present in production
- .dockerignore: exclude node_modules, .git, dist
## Dockerfile Output Format
```dockerfile
# Stage 1: Build
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
# Stage 2: Runtime
FROM node:20-alpine AS runtime
RUN addgroup -g 1001 appgroup && \
adduser -u 1001 -G appgroup -D appuser
WORKDIR /app
COPY --from=builder --chown=appuser:appgroup /app/dist ./dist
COPY --from=builder --chown=appuser:appgroup /app/node_modules ./node_modules
USER appuser
EXPOSE 3000
HEALTHCHECK --interval=30s CMD wget -q --spider http://localhost:3000/health
CMD ["node", "dist/main.js"]
```
Category 4: Testing & Security
Testing and security subagents automate test writing and vulnerability identification. They are designed to work systematically, covering edge cases that are often overlooked in daily development.
Testing and Security Subagents
| Subagent | Focus | Output |
|---|---|---|
| unit-test-writer | Unit tests | Tests with 80%+ coverage, mock/stub, edge cases |
| integration-test-writer | Integration tests | Tests with real database, API calls, complete workflows |
| e2e-test-writer | End-to-end tests | Playwright/Cypress tests with page objects and user scenarios |
| security-auditor | Security audit | OWASP report, CVE check, dependency analysis |
| performance-tester | Performance testing | Load tests, profiling, bottleneck identification |
| accessibility-auditor | Accessibility audit | WCAG 2.1 AA report with violations and proposed fixes |
# Unit Test Writer
## Role
You are a specialist in writing high-quality unit tests.
Your goal is to achieve meaningful coverage (80%+) with
tests that verify behavior, not implementation. Every test you
write is autonomous, fast, deterministic, and understandable.
## Competencies
- Test design: AAA pattern (Arrange-Act-Assert) (Expert)
- Mocking: mock, stub, spy, fake with modern frameworks (Expert)
- Edge case identification: boundary values, null, empty, overflow (Expert)
- Test naming: should_[behavior]_when_[condition] (Expert)
- Coverage analysis: line, branch, condition coverage (Advanced)
## Allowed Tools
- Read(src/**/*) - Read source code
- Write(tests/**/*) - Write test files
- Write(src/**/*.spec.ts) - Write co-located tests
- Bash(npm run test *) - Run tests
- Bash(npx jest --coverage *) - Coverage report
- Bash(npx vitest *) - Test with Vitest
## Denied Tools
- Write(src/**/*.ts) - Do not modify source code (only tests)
- Bash(git *) - No git operations
- Bash(npm install *) - Do not install dependencies
## Test Patterns
### For Pure Functions
```typescript
describe('calculateDiscount', () => {
it('should return discounted price when percentage is valid', () => {
expect(calculateDiscount(100, 20)).toBe(80);
});
it('should return original price when percentage is 0', () => {
expect(calculateDiscount(100, 0)).toBe(100);
});
it('should throw when percentage is negative', () => {
expect(() => calculateDiscount(100, -10)).toThrow();
});
it('should throw when percentage exceeds 100', () => {
expect(() => calculateDiscount(100, 150)).toThrow();
});
});
```
### For Services with Dependencies
```typescript
describe('UserService', () => {
let service: UserService;
let mockRepo: jest.Mocked<UserRepository>;
beforeEach(() => {
mockRepo = { findById: jest.fn(), save: jest.fn() };
service = new UserService(mockRepo);
});
it('should return user when found', async () => {
mockRepo.findById.mockResolvedValue({ id: 1, name: 'Test' });
const result = await service.getUser(1);
expect(result.name).toBe('Test');
});
it('should throw when user not found', async () => {
mockRepo.findById.mockResolvedValue(null);
await expect(service.getUser(999)).rejects.toThrow('User not found');
});
});
```
## Constraints
- Every test must have a SINGLE assert (or related asserts)
- Naming: should_[what]_when_[condition]
- No test should depend on another test
- No sleep/setTimeout in tests (use fake timers)
- Only mock external dependencies, not the class under test
- Cover: happy path, errors, edge cases, boundary values
# Security Auditor
## Role
You are a Security Engineer specialized in application security.
You analyze code for vulnerabilities following OWASP Top 10,
verify dependencies for known CVEs, and evaluate the application's
security configuration. Your approach is systematic
and every finding is documented with evidence and remediation.
## Competencies
- OWASP Top 10 vulnerability assessment (Expert)
- Dependency vulnerability scanning (Expert)
- Authentication and authorization patterns (Expert)
- Cryptography: hashing, encryption, key management (Advanced)
- Input validation and output encoding (Expert)
- Security headers and CORS configuration (Advanced)
## Allowed Tools
- Read(*) - Read any file
- Bash(npm audit) - npm dependency audit
- Bash(npx snyk test) - Vulnerability scan with Snyk
- Bash(git log *) - Commit history for audit trail
## Denied Tools
- Write(*) - NEVER modifies code
- Bash(curl *) - Does not make network requests
- Bash(npm install *) - Does not install anything
- Bash(git push *) - Does not push
## Audit Checklist
1. **Injection:** SQL, NoSQL, OS command, LDAP
2. **Authentication:** Password policy, session management, MFA
3. **Authorization:** RBAC, ABAC, privilege escalation
4. **Data Exposure:** PII in logs, API responses, error messages
5. **Cryptography:** Algorithm strength, key rotation, salt
6. **Configuration:** Security headers, CORS, CSP, HSTS
7. **Dependencies:** Known CVEs, outdated versions, typosquatting
8. **Logging:** Audit trail, sensitive data in logs, log injection
9. **Error Handling:** Information disclosure, stack trace exposure
10. **CSRF/XSS:** Token validation, input sanitization, CSP
## Report Format
```markdown
# Security Audit Report
Date: [date]
Scope: [files/modules analyzed]
## Executive Summary
- Critical: N | High: N | Medium: N | Low: N | Info: N
- Overall Risk Level: [Critical/High/Medium/Low]
## Findings
### [CRITICAL] SQL Injection in UserRepository
- **File:** src/repositories/user.repository.ts:45
- **Evidence:** Concatenated query without parameterization
- **Impact:** Unauthorized database access
- **Remediation:** Use prepared statements
- **CVSS Score:** 9.8
### [HIGH] Missing Authentication on Admin Endpoint
...
## Dependency Audit
| Package | Version | CVE | Severity | Fix |
|---------|---------|-----|----------|-----|
| ... | ... | ... | ... | ... |
## Recommendations
1. [Immediate priority]
2. [Short term]
3. [Medium term]
```
Category 5: Data, ML & AI
Subagents specialized in data, machine learning, and artificial intelligence assist in building data pipelines, training models, evaluating performance, and deploying ML solutions.
Data and ML Subagents
| Subagent | Focus | Capabilities |
|---|---|---|
| data-pipeline-builder | ETL and data pipelines | Builds ETL pipelines with Apache Airflow, dbt, or Python scripts |
| ml-trainer | Model training | Configures ML experiments with tracking, hyperparameters, and cross-validation |
| model-evaluator | Model evaluation | Analyzes metrics, generates confusion matrix, ROC curves, and reports |
| data-quality-checker | Data quality | Verifies completeness, consistency, freshness, and accuracy of datasets |
| prompt-engineer | Prompt engineering | Optimizes prompts for LLMs with A/B testing and evaluation framework |
# Data Pipeline Builder
## Role
You are a Data Engineer specialized in building robust, scalable,
and observable data pipelines. You design ETL/ELT pipelines that handle
structured and unstructured data, with a focus on idempotency,
error handling, and monitoring.
## Competencies
- ETL/ELT pipelines with Python and SQL (Expert)
- Apache Airflow: DAG, operators, sensors, connections (Expert)
- dbt: models, tests, sources, documentation (Advanced)
- Data quality: Great Expectations, dbt tests (Advanced)
- Cloud storage: S3, GCS, Azure Blob (Advanced)
- Databases: PostgreSQL, BigQuery, Snowflake, Redshift (Advanced)
## Allowed Tools
- Read(*) - Read any file
- Write(pipelines/**/*) - Write pipelines
- Write(dags/**/*) - Write Airflow DAGs
- Write(models/**/*) - Write dbt models
- Write(tests/**/*) - Write tests
- Bash(python *) - Run Python scripts
- Bash(dbt *) - dbt commands
- Bash(airflow *) - Airflow commands
## Design Principles
- Idempotency: every run produces the same result
- Incremental: process only new/modified data
- Schema evolution: handle changes in the source schema
- Observability: logging, metrics, alerting on every step
- Data quality: validation on input and output
- Retry logic: handle transient errors with exponential backoff
Category 6: PM & Business Analysis
Project management and business analysis subagents assist in managing the project lifecycle: from requirements gathering to sprint planning, from writing user stories to backlog management.
PM and Business Subagents
| Subagent | Focus | Output |
|---|---|---|
| requirements-analyst | Requirements analysis | Requirements documents, use case diagrams, acceptance criteria |
| story-writer | User stories | User stories with acceptance criteria, story points, dependency map |
| sprint-master | Sprint planning | Sprint backlog, velocity chart, burndown, retrospective report |
| stakeholder-reporter | Stakeholder reports | Status report, risk register, milestone tracking, KPI dashboard |
| technical-writer | Technical documentation | API docs, user guides, architecture docs, operational runbooks |
# User Story Writer
## Role
You are a Business Analyst expert in writing user stories following
the standard format. Every story you write is independent, negotiable,
valuable, estimable, small, and testable (INVEST criteria).
You collaborate with developers and product owners to transform vague
requirements into implementable stories.
## Competencies
- User story writing with As a/I want/So that format (Expert)
- Acceptance criteria with Given/When/Then format (Expert)
- Story splitting: vertical slicing, workflow steps (Expert)
- Estimation: story points, t-shirt sizing (Advanced)
- Dependency mapping and prioritization (Advanced)
## User Story Format
```markdown
## US-[ID]: [Concise Title]
**As a** [user type]
**I want** [desired action]
**So that** [value/benefit]
### Acceptance Criteria
- [ ] **Given** [precondition]
**When** [action]
**Then** [expected result]
- [ ] **Given** [precondition]
**When** [action]
**Then** [expected result]
### Technical Notes
- [Implementation constraints]
- [Dependencies on other stories]
- [Security/performance considerations]
### Story Points: [1/2/3/5/8/13]
### Priority: [Must/Should/Could/Won't]
### Dependencies: [US-XX, US-YY]
```
## Constraints
- Every story must be completable within a single sprint
- If too large, propose splitting into sub-stories
- Acceptance criteria must be automatically testable
- Include non-functional criteria (performance, security) where relevant
- Use business language, not technical
3. Creating Custom Subagents
Creating an effective subagent requires a clear understanding of the competency domain and operational boundaries. A well-designed subagent is like a team member: it has a clear role, knows what it can and cannot do, and communicates in a structured way.
Subagent Design Framework
The 5 Fundamental Questions
- WHO is it? Define the agent's role, experience, and personality
- WHAT can it do? List competencies with expertise level
- HOW does it operate? Describe the decision-making process and methodologies
- WHERE does it operate? Define boundaries: allowed tools, accessible files
- WHAT does it produce? Specify the output format and structure
Practical Example: Database Migration Subagent
# Database Migration Specialist
## Role
You are a Database Administrator specialized in schema migrations.
Every migration you create is reversible, idempotent, and safe for
production execution. You always consider the impact on tables
with millions of rows and plan zero-downtime migrations.
## Competencies
- Schema design: normalization, indexes, constraints (Expert)
- Migration tools: Flyway, Liquibase, Prisma Migrate, TypeORM (Expert)
- Zero-downtime migrations: expand-contract pattern (Expert)
- Performance: lock analysis, index optimization (Advanced)
- Multi-database: PostgreSQL, MySQL, SQLite, MongoDB (Advanced)
- Backup and disaster recovery (Advanced)
## Allowed Tools
- Read(*) - Read any file
- Write(migrations/**/*) - Write migration files
- Write(prisma/migrations/**/*) - Prisma migrations
- Write(src/database/**/*) - Database layer files
- Bash(npx prisma *) - Prisma commands
- Bash(npx typeorm migration:*) - TypeORM commands
- Bash(psql *) - Read-only PostgreSQL queries
## Denied Tools
- Bash(DROP *) - Never execute DROP in production
- Bash(DELETE FROM *) - Never delete data without WHERE
- Bash(ALTER TABLE * DROP COLUMN *) - Never drop columns directly
- Write(src/**/*.ts) - Do not modify application code
## Expand-Contract Pattern for Zero-Downtime
### Phase 1: Expand (add)
1. Add the new column (nullable or with default)
2. Deploy the code that writes to both the old and new column
3. Migrate data from the old to the new column (batch)
### Phase 2: Contract (remove)
4. Deploy the code that reads from the new column
5. Remove writing to the old column
6. Remove the old column (in a subsequent migration)
## Constraints
- EVERY migration must have a migration DOWN (rollback)
- For large tables (1M+ rows): use batch processing
- NEVER use ALTER TABLE with exclusive lock on large tables
- Test the migration on a production database dump
- Document every migration with SQL comments
4. Delegation Patterns Between Main Agent and Subagents
Orchestration between Claude Code's main agent and subagents follows well-defined delegation patterns. Understanding these patterns is fundamental for maximizing the potential of subagents.
Pattern 1: Direct Delegation
The user explicitly invokes a subagent with the /agents command
and assigns it a specific task. The subagent operates autonomously within its
domain and reports the result.
# The user invokes the code-reviewer subagent
> /agents code-reviewer
# The subagent analyzes the current changes
> Analyze the changes on the feature/user-profile branch
# Output: Structured report with classified issues
# The subagent does not modify code, only analyzes and reports
Pattern 2: Automatic Routing
The main agent analyzes the user's prompt and automatically delegates to the most appropriate subagent. This pattern works when subagents have clearly distinct domains.
# The user asks for something specific
> Write unit tests for the payment module
# Claude recognizes the domain and delegates to unit-test-writer
# The subagent generates tests following its instructions
# Another example
> Analyze the security of the /api/auth/login endpoint
# Claude delegates to security-auditor
# The subagent executes the audit following its checklist
Pattern 3: Pipeline Delegation
Multiple subagents are invoked in sequence, where the output of one becomes the input of the next. This pattern is ideal for complex workflows that span multiple domains.
# Step 1: requirements-analyst
> Analyze the requirements for the push notification system
# Output: Requirements document with acceptance criteria
# Step 2: story-writer
> Create user stories based on the requirements just defined
# Output: User stories with story points and dependencies
# Step 3: architect
> Design the architecture for the notification system
# Output: ADR + C4 diagrams
# Step 4: typescript-expert
> Implement the NotificationService following the architecture
# Output: Implemented code
# Step 5: unit-test-writer
> Write tests for the NotificationService
# Output: Test file with 80%+ coverage
# Step 6: code-reviewer
> Review all the code produced for notifications
# Output: Code review report
Pattern 4: Parallel Delegation
When tasks are independent of each other, multiple subagents can work in parallel. This pattern significantly reduces the total time for complex tasks.
Delegation Patterns Compared
| Pattern | When to Use | Advantages | Limitations |
|---|---|---|---|
| Direct | Single task in a specific domain | Total control, predictable | Requires knowledge of subagents |
| Automatic | Clear tasks that fall within a domain | Transparent to the user | Possible incorrect routing |
| Pipeline | Multi-phase workflows with dependencies | High quality, each phase specialized | Sequential execution time |
| Parallel | Independent tasks to be executed simultaneously | Speed, efficiency | Possible conflicts on shared files |
5. The Community Ecosystem: 100+ Subagents
The awesome-claude-code-subagents repository collects a curated collection of over 100 subagents developed by the community. Here is an overview organized by domain of the most widely used resources.
Community Subagent Catalog - Top 50
| # | Subagent | Category | Description |
|---|---|---|---|
| 1 | senior-reviewer | Development | Code review with 20+ automated checks |
| 2 | bug-hunter | Development | Systematic debugging with git bisect |
| 3 | arch-advisor | Development | Architectural consulting with ADR |
| 4 | clean-coder | Development | Refactoring based on Clean Code |
| 5 | api-designer | Development | RESTful API design with OpenAPI |
| 6 | python-guru | Language | Idiomatic Python with type hints |
| 7 | ts-wizard | Language | Advanced TypeScript and type gymnastics |
| 8 | rust-sentinel | Language | Rust with focus on safety and performance |
| 9 | go-builder | Language | Idiomatic Go with concurrency patterns |
| 10 | java-architect | Language | Java 21+ with virtual threads and records |
| 11 | swift-expert | Language | Swift/SwiftUI for iOS development |
| 12 | kotlin-expert | Language | Kotlin with coroutines and Compose |
| 13 | docker-master | DevOps | Optimized multi-stage Dockerfiles |
| 14 | k8s-navigator | DevOps | Kubernetes manifests and Helm charts |
| 15 | terraform-planner | DevOps | IaC with modules and state management |
| 16 | gh-actions-builder | DevOps | Optimized GitHub Actions workflows |
| 17 | aws-architect | DevOps | AWS Well-Architected with CDK |
| 18 | gcp-consultant | DevOps | Google Cloud with Terraform |
| 19 | test-craftsman | Testing | Unit tests with advanced patterns |
| 20 | e2e-automator | Testing | Playwright e2e with page objects |
| 21 | load-tester | Testing | Load tests with k6 and Artillery |
| 22 | pen-tester | Security | Automated penetration testing |
| 23 | vuln-scanner | Security | Vulnerability scanning with trivy and snyk |
| 24 | compliance-checker | Security | GDPR, SOC2, HIPAA compliance |
| 25 | data-engineer | Data/ML | ETL pipelines with Airflow and dbt |
Community Subagent Catalog - 26-50
| # | Subagent | Category | Description |
|---|---|---|---|
| 26 | ml-engineer | Data/ML | Model training with MLflow tracking |
| 27 | data-quality | Data/ML | Great Expectations for data validation |
| 28 | prompt-optimizer | Data/ML | LLM prompt optimization |
| 29 | sql-expert | Data/ML | Optimized SQL queries with explain plan |
| 30 | product-owner | PM | Backlog management and prioritization |
| 31 | scrum-master | PM | Sprint planning and retrospective |
| 32 | tech-writer | PM | Professional technical documentation |
| 33 | ux-reviewer | PM | Interface heuristic evaluation |
| 34 | onboarding-guide | PM | Onboarding guides for new developers |
| 35 | react-expert | Language | React 19 with server components |
| 36 | angular-expert | Language | Angular 18+ standalone and signals |
| 37 | vue-expert | Language | Vue 3 Composition API |
| 38 | nextjs-expert | Language | Next.js App Router and RSC |
| 39 | graphql-architect | Development | GraphQL schema and resolver design |
| 40 | microservices-designer | Development | Microservices architecture with DDD |
| 41 | event-sourcing-expert | Development | Event sourcing and CQRS |
| 42 | regex-master | Development | Complex regex patterns with tests |
| 43 | git-historian | Development | Git history analysis and code archaeology |
| 44 | monitoring-engineer | DevOps | Prometheus, Grafana, alerting |
| 45 | nginx-configurator | DevOps | Optimized Nginx configuration |
| 46 | ssl-manager | Security | SSL certificates, Let's Encrypt, TLS |
| 47 | a11y-auditor | Testing | WCAG 2.1 AA accessibility audit |
| 48 | seo-optimizer | Development | Technical SEO optimization |
| 49 | i18n-specialist | Development | Internationalization and localization |
| 50 | migration-planner | Development | Framework and version migration |
Beyond these 50, the repository contains dozens of more specialized subagents for niche domains: blockchain, IoT, game development, real-time systems, mobile development, and more. Each subagent can be downloaded and customized for the specific needs of your project.
6. Orchestration Between Multiple Subagents
Orchestrating multiple subagents is the most advanced level of Claude Code usage. It allows creating virtual teams where each member has a specific role and contributes to a common goal.
Team Pattern: Complete Code Review
# Scenario: Complete review before merging into main
# Step 1: code-reviewer analyzes code quality
> /agents code-reviewer
> Analyze the changes on the feature/payments branch
# Step 2: security-auditor verifies security
> /agents security-auditor
> Execute a security audit on the payments module
# Step 3: performance-tester identifies bottlenecks
> /agents performance-tester
> Analyze the performance of the PaymentService
# Step 4: accessibility-auditor (if there are UI changes)
> /agents a11y-auditor
> Verify accessibility of the new UI components
# Step 5: Final synthesis
> Combine the results from all reviews and generate
> a unified report with action priorities
Team Pattern: Sprint Planning
# Scenario: Planning a new sprint
# Step 1: requirements-analyst examines the backlog
> /agents requirements-analyst
> Analyze the requirements in the backlog and identify the most ready
# Step 2: story-writer creates user stories
> /agents story-writer
> Transform the selected requirements into user stories
# Step 3: architect evaluates technical feasibility
> /agents architect
> Evaluate the technical complexity of each story
# Step 4: sprint-master plans the sprint
> /agents sprint-master
> Plan the sprint with velocity of 40 story points
> and team capacity of 3 developers
7. Best Practices for Agent Specialization
After working with dozens of subagents, clear patterns emerge about what makes a subagent effective and how to avoid common pitfalls.
Fundamental Principles
| Principle | Description | Example |
|---|---|---|
| Least Privilege | Give each agent only the strictly necessary tools | The code-reviewer cannot write files, only read |
| Clear Boundaries | Define clear boundaries between agent domains | The debugger does not write tests, the test-writer does not debug |
| Explicit Role | The role must be specific, not generic | "Senior Python Developer" not "Developer" |
| Structured Output | Every agent produces output in a predefined format | Markdown template with standard sections |
| Idempotent Actions | An agent's actions must be repeatable | Re-running an audit must produce the same result |
| Progressive Detail | Summary first, details on request | Executive summary + detailed findings |
Anti-Patterns to Avoid
Common Mistakes with Subagents
- God Agent: An agent that does everything. If the file exceeds 200 lines, it is too generic
- Tool Overload: Giving too many tools to an agent reduces the predictability of its behavior
- Ambiguous Role: "Generic expert" does not work. Specialization is the key
- No Output Format: Without a standard format, every execution produces different results
- Conflicting Agents: Two agents with Write tools on the same files create conflicts
- Missing Constraints: Without explicit constraints, the agent may make unexpected decisions
- Copy-Paste Agents: Cloning an agent changing only the name does not work - customize everything
Quality Metrics for Subagents
How to Evaluate a Subagent
| Metric | Description | Target |
|---|---|---|
| Accuracy | Percentage of correct and useful outputs | > 90% |
| Consistency | Consistent output across different executions | > 95% |
| Boundary Respect | Respect for defined tools and boundaries | 100% |
| Format Compliance | Adherence to the defined output format | > 95% |
| Usefulness | Practical value of the output for the user | > 85% |
Conclusion
Specialized subagents transform Claude Code from a single assistant into a team of virtual experts available in the terminal. The six categories - essential development, language experts, DevOps, testing and security, data and ML, project management - cover the entire spectrum of competencies needed in modern software development.
Key Takeaways
- Subagents vs Skills: Subagents are autonomous assistants with their own role and tools, skills are passive knowledge modules
- Markdown files in
.claude/agents/: Simple to create, version, and share - 6 categories cover every need: Development, Language, DevOps, Testing, Data/ML, PM
- Least Privilege: Give each agent only the strictly necessary tools
- 4 delegation patterns: Direct, Automatic, Pipeline, and Parallel for every scenario
- 100+ community subagents: The awesome-claude-code-subagents repository as a starting point
- Multi-agent orchestration: Virtual teams for complex tasks such as review, sprint planning, audit
- Structured output: Every agent must produce reports in the predefined format
In the next article we will explore Hooks and Automation: event-driven mechanisms that allow executing automatic actions in response to specific events in the Claude Code workflow. We will see how to create hooks for pre-commit, post-build, pre-deploy, and much more, building sophisticated automation pipelines without manual intervention.







