A visual, example-driven guide to Claude Code — from basic concepts to advanced agents, with copy-paste templates that bring immediate value.
docs: Update subagents lesson based on official documentation
Luong NGUYEN2177035e5155
diff --git a/04-subagents/README.md b/04-subagents/README.mdindex 6c1dd3a..4894d95 100644--- a/04-subagents/README.md+++ b/04-subagents/README.md@@ -2,21 +2,26 @@# Subagents - Complete Reference Guide-Subagents are specialized AI assistants with isolated context windows and customized system prompts. They enable delegated task execution while maintaining clean separation of concerns.+Subagents are specialized AI assistants that Claude Code can delegate tasks to. Each subagent has a specific purpose, uses its own context window separate from the main conversation, and can be configured with specific tools and a custom system prompt.## Table of Contents1. [Overview](#overview)-2. [Architecture](#architecture)-3. [Configuration](#configuration)-4. [Tool Access Hierarchy](#tool-access-hierarchy)-5. [Practical Examples](#practical-examples)-6. [Context Management](#context-management)-7. [When to Use Subagents](#when-to-use-subagents)-8. [Best Practices](#best-practices)-9. [Available Subagents in This Folder](#available-subagents-in-this-folder)-10. [Installation Instructions](#installation-instructions)-11. [Related Concepts](#related-concepts)+2. [Key Benefits](#key-benefits)+3. [File Locations](#file-locations)+4. [Configuration](#configuration)+5. [Built-in Subagents](#built-in-subagents)+6. [Managing Subagents](#managing-subagents)+7. [Using Subagents](#using-subagents)+8. [Resumable Agents](#resumable-agents)+9. [Chaining Subagents](#chaining-subagents)+10. [Architecture](#architecture)+11. [Context Management](#context-management)+12. [When to Use Subagents](#when-to-use-subagents)+13. [Best Practices](#best-practices)+14. [Example Subagents in This Folder](#example-subagents-in-this-folder)+15. [Installation Instructions](#installation-instructions)+16. [Related Concepts](#related-concepts)---@@ -32,95 +37,76 @@ Subagents enable delegated task execution in Claude Code by:Each subagent operates independently with a clean slate, receiving only the specific context necessary for their task, then returning results to the main agent for synthesis.-### Key Benefits--- **Separation of Concerns** - Each agent focuses on their specialty-- **Clean Context** - No interference from unrelated information-- **Scalability** - Multiple agents work on different aspects simultaneously-- **Quality** - Specialized prompts improve output for domain-specific tasks-- **Control** - Granular tool permissions prevent unintended modifications+**Quick Start**: Use the `/agents` command to create, view, edit, and manage your subagents interactively.----## Architecture+## Key Benefits-### High-Level Architecture+| Benefit | Description |+|---------|-------------|+| **Context preservation** | Operates in separate context, preventing pollution of main conversation |+| **Specialized expertise** | Fine-tuned for specific domains with higher success rates |+| **Reusability** | Use across different projects and share with teams |+| **Flexible permissions** | Different tool access levels for different subagent types |+| **Scalability** | Multiple agents work on different aspects simultaneously |-```mermaid-graph TB- User["👤 User"]- Main["🎯 Main Agent<br/>(Coordinator)"]- Reviewer["🔍 Code Reviewer<br/>Subagent"]- Tester["✅ Test Engineer<br/>Subagent"]- Docs["📝 Documentation<br/>Subagent"]+---- User -->|asks| Main- Main -->|delegates| Reviewer- Main -->|delegates| Tester- Main -->|delegates| Docs- Reviewer -->|returns result| Main- Tester -->|returns result| Main- Docs -->|returns result| Main- Main -->|synthesizes| User-```+## File Locations-### Subagent Lifecycle+Subagent files can be stored in multiple locations with different scopes:-```mermaid-sequenceDiagram- participant User- participant MainAgent as Main Agent- participant CodeReviewer as Code Reviewer<br/>Subagent- participant Context as Separate<br/>Context Window+| Type | Location | Scope | Priority |+|------|----------|-------|----------|+| **Project subagents** | `.claude/agents/` | Current project | Highest |+| **User subagents** | `~/.claude/agents/` | All projects | Lower |+| **Plugin agents** | `plugins/agents/` | Via plugins | Varies |+| **CLI-defined** | Via `--agents` flag | Session-specific | Medium |- User->>MainAgent: "Build new auth feature"- MainAgent->>MainAgent: Analyze task- MainAgent->>CodeReviewer: "Review this code"- CodeReviewer->>Context: Initialize clean context- Context->>CodeReviewer: Load reviewer instructions- CodeReviewer->>CodeReviewer: Perform review- CodeReviewer-->>MainAgent: Return findings- MainAgent->>MainAgent: Incorporate results- MainAgent-->>User: Provide synthesis-```+When duplicate names exist, project-level subagents take priority over user-level ones.---## Configuration-### Subagent Configuration Table--| Configuration | Type | Purpose | Example |-|---------------|------|---------|---------|-| `name` | String | Agent identifier | `code-reviewer` |-| `description` | String | Purpose & trigger terms | `Comprehensive code quality analysis` |-| `tools` | List/String | Allowed capabilities | `read, grep, diff, lint_runner` |-| `system_prompt` | Markdown | Behavioral instructions | Custom guidelines |+### File Format-### Configuration File Format--Subagents are defined in YAML front matter followed by the system prompt:+Subagents are defined in YAML frontmatter followed by the system prompt in markdown:```yaml----name: agent-name-description: Brief description of purpose-tools: read, grep, diff+name: your-sub-agent-name+description: Description of when this subagent should be invoked+tools: tool1, tool2, tool3 # Optional - inherits all tools if omitted+model: sonnet # Optional - specify model alias or 'inherit'+permissionMode: default # Optional - permission mode+skills: skill1, skill2 # Optional - skills to auto-load----# System Prompt (Markdown)--You are an expert in [domain]...+Your subagent's system prompt goes here. This can be multiple paragraphs+and should clearly define the subagent's role, capabilities, and approach+to solving problems.```+### Configuration Fields++| Field | Required | Description |+|-------|----------|-------------|+| `name` | Yes | Unique identifier (lowercase letters and hyphens) |+| `description` | Yes | Natural language description of purpose. Include "use PROACTIVELY" to encourage automatic invocation |+| `tools` | No | Comma-separated list of specific tools. Omit to inherit all tools |+| `model` | No | Model to use: `sonnet`, `opus`, `haiku`, or `inherit`. Defaults to configured subagent model |+| `permissionMode` | No | `default`, `acceptEdits`, `bypassPermissions`, `plan`, `ignore` |+| `skills` | No | Comma-separated list of skills to auto-load |+### Tool Configuration Options-**Option 1: Inherit All Tools from Main Thread**+**Option 1: Inherit All Tools (omit the field)**```yaml---name: full-access-agentdescription: Agent with all available tools-tools: *---```@@ -129,7 +115,7 @@ tools: *---name: limited-agentdescription: Agent with specific tools only-tools: read, grep, diff+tools: Read, Grep, Glob, Bash---```@@ -138,278 +124,209 @@ tools: read, grep, diff---name: conditional-agentdescription: Agent with filtered tool access-tools: read, bash(npm:*), bash(test:*)+tools: Read, Bash(npm:*), Bash(test:*)---```----+### CLI-Based Configuration-## Tool Access Hierarchy+Define subagents for a single session using the `--agents` flag:-```mermaid-graph TD- A["Subagent Configuration"] -->|Option 1| B["Inherit All Tools<br/>from Main Thread"]- A -->|Option 2| C["Specify Individual Tools"]- B -->|Includes| B1["File Operations"]- B -->|Includes| B2["Shell Commands"]- B -->|Includes| B3["MCP Tools"]- C -->|Explicit List| C1["read, grep, diff"]- C -->|Explicit List| C2["Bash(npm:*), Bash(test:*)"]+```bash+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"+ }+}'```-### Common Tool Combinations+----**Code Review Agent**-```yaml-tools: read, grep, diff, lint_runner-```+## Built-in Subagents-**Implementation Agent**-```yaml-tools: read, write, bash, grep, edit, glob-```+Claude Code includes three built-in subagents that are always available:-**Documentation Agent**-```yaml-tools: read, write, grep-```+### 1. General-Purpose Subagent-**Security Auditor**-```yaml-tools: read, grep-```-------## Practical Examples+| Property | Value |+|----------|-------|+| **Model** | Sonnet |+| **Tools** | All tools |+| **Purpose** | Complex research tasks, multi-step operations, code modifications |-### Example 1: Complete Subagent Setup+**When used**: Tasks requiring both exploration and modification with complex reasoning.-#### Code Reviewer Subagent+### 2. Plan Subagent-**File**: `.claude/agents/code-reviewer.md`+| Property | Value |+|----------|-------|+| **Model** | Sonnet |+| **Tools** | Read, Glob, Grep, Bash |+| **Purpose** | Used automatically in plan mode to research codebase |-```yaml-----name: code-reviewer-description: Comprehensive code quality and maintainability analysis-tools: read, grep, diff, lint_runner----+**When used**: When Claude needs to understand the codebase before presenting a plan.-# Code Reviewer Agent+### 3. Explore Subagent-You are an expert code reviewer specializing in:-- Performance optimization-- Security vulnerabilities-- Code maintainability-- Testing coverage-- Design patterns+| Property | Value |+|----------|-------|+| **Model** | Haiku (fast, low-latency) |+| **Mode** | Strictly read-only |+| **Tools** | Glob, Grep, Read, Bash (read-only commands only) |+| **Purpose** | Fast codebase searching and analysis |-## Review Priorities (in order)+**When used**: When searching/understanding code without making changes.-1. **Security Issues** - Authentication, authorization, data exposure-2. **Performance Problems** - O(n²) operations, memory leaks, inefficient queries-3. **Code Quality** - Readability, naming, documentation-4. **Test Coverage** - Missing tests, edge cases-5. **Design Patterns** - SOLID principles, architecture+**Thoroughness Levels**:+- **Quick** - Fast searches with minimal exploration+- **Medium** - Moderate exploration, balanced speed and thoroughness+- **Very thorough** - Comprehensive analysis across multiple locations and naming conventions-## Review Output Format+----For each issue:-- **Severity**: Critical / High / Medium / Low-- **Category**: Security / Performance / Quality / Testing / Design-- **Location**: File path and line number-- **Issue Description**: What's wrong and why-- **Suggested Fix**: Code example-- **Impact**: How this affects the system+## Managing Subagents-## Example Review+### Using the `/agents` Command (Recommended)-### Issue: N+1 Query Problem-- **Severity**: High-- **Category**: Performance-- **Location**: src/user-service.ts:45-- **Issue**: Loop executes database query in each iteration-- **Fix**: Use JOIN or batch query+```bash+/agents```-#### Test Engineer Subagent+This provides an interactive menu to:+- View all available subagents (built-in, user, and project)+- Create new subagents with guided setup+- Edit existing custom subagents and tool access+- Delete custom subagents+- See which subagents are active when duplicates exist-**File**: `.claude/agents/test-engineer.md`+### Direct File Management-```yaml+```bash+# Create a project subagent+mkdir -p .claude/agents+cat > .claude/agents/test-runner.md << 'EOF'----name: test-engineer-description: Test strategy, coverage analysis, and automated testing-tools: read, write, bash, grep+name: test-runner+description: Use proactively to run tests and fix failures----# Test Engineer Agent--You are expert at:-- Writing comprehensive test suites-- Ensuring high code coverage (>80%)-- Testing edge cases and error scenarios-- Performance benchmarking-- Integration testing+You are a test automation expert. When you see code changes, proactively+run the appropriate tests. If tests fail, analyze the failures and fix+them while preserving the original test intent.+EOF-## Testing Strategy--1. **Unit Tests** - Individual functions/methods-2. **Integration Tests** - Component interactions-3. **End-to-End Tests** - Complete workflows-4. **Edge Cases** - Boundary conditions-5. **Error Scenarios** - Failure handling--## Test Output Requirements+# Create a user subagent (available in all projects)+mkdir -p ~/.claude/agents+```-- Use Jest for JavaScript/TypeScript-- Include setup/teardown for each test-- Mock external dependencies-- Document test purpose-- Include performance assertions when relevant+----## Coverage Requirements+## Using Subagents-- Minimum 80% code coverage-- 100% for critical paths-- Report missing coverage areas-```+### Automatic Delegation-#### Documentation Writer Subagent+Claude proactively delegates tasks based on:+- Task description in your request+- The `description` field in subagent configurations+- Current context and available tools-**File**: `.claude/agents/documentation-writer.md`+To encourage proactive use, include "use PROACTIVELY" or "MUST BE USED" in your `description` field:```yaml----name: documentation-writer-description: Technical documentation, API docs, and user guides-tools: read, write, grep+name: code-reviewer+description: Expert code review specialist. Use PROACTIVELY after writing or modifying code.-----# Documentation Writer Agent--You create:-- API documentation with examples-- User guides and tutorials-- Architecture documentation-- Changelog entries-- Code comment improvements--## Documentation Standards--1. **Clarity** - Use simple, clear language-2. **Examples** - Include practical code examples-3. **Completeness** - Cover all parameters and returns-4. **Structure** - Use consistent formatting-5. **Accuracy** - Verify against actual code--## Documentation Sections--### For APIs-- Description-- Parameters (with types)-- Returns (with types)-- Throws (possible errors)-- Examples (curl, JavaScript, Python)-- Related endpoints--### For Features-- Overview-- Prerequisites-- Step-by-step instructions-- Expected outcomes-- Troubleshooting-- Related topics```-### Example 2: Subagent Delegation in Action+### Explicit Invocation-#### Scenario: Building a Payment Feature+You can explicitly request a specific subagent:-**User Request**:```-"Build a secure payment processing feature that integrates with Stripe"+> Use the test-runner subagent to fix failing tests+> Have the code-reviewer subagent look at my recent changes+> Ask the debugger subagent to investigate this error```-**Main Agent Flow**:--1. **Planning Phase**- - Understands requirements- - Determines tasks needed- - Plans architecture--2. **Delegates to Code Reviewer Subagent**- - Task: "Review the payment processing implementation for security"- - Context: Auth, API keys, token handling- - Reviews for: SQL injection, key exposure, HTTPS enforcement--3. **Delegates to Test Engineer Subagent**- - Task: "Create comprehensive tests for payment flows"- - Context: Success scenarios, failures, edge cases- - Creates tests for: Valid payments, declined cards, network failures, webhooks+----4. **Delegates to Documentation Writer Subagent**- - Task: "Document the payment API endpoints"- - Context: Request/response schemas- - Produces: API docs with curl examples, error codes+## Resumable Agents-5. **Synthesis**- - Main agent collects all outputs- - Integrates findings- - Returns complete solution to user+Subagents can continue previous conversations with full context preserved:-### Example 3: Tool Permission Scoping+```bash+# Initial invocation+> Use the code-analyzer agent to start reviewing the authentication module+# Returns agentId: "abc123"-#### Restrictive Setup - Limited to Specific Commands+# Resume the agent later+> Resume agent abc123 and now analyze the authorization logic as well+```-**File**: `.claude/agents/secure-reviewer.md`+**Use cases**:+- Long-running research across multiple sessions+- Iterative refinement without losing context+- Multi-step workflows maintaining context-```yaml-----name: secure-reviewer-description: Security-focused code review with minimal permissions-tools: read, grep----# Secure Code Reviewer--Reviews code for security vulnerabilities only.+## Chaining Subagents-This agent:-- ✅ Reads files to analyze-- ✅ Searches for patterns-- ❌ Cannot execute code-- ❌ Cannot modify files-- ❌ Cannot run tests+Execute multiple subagents in sequence:-This ensures the reviewer doesn't accidentally break anything.+```bash+> First use the code-analyzer subagent to find performance issues,+ then use the optimizer subagent to fix them```-#### Extended Setup - All Tools for Implementation--**File**: `.claude/agents/implementation-agent.md`+This enables complex workflows where the output of one subagent feeds into another.-```yaml-----name: implementation-agent-description: Full implementation capabilities for feature development-tools: read, write, bash, grep, edit, glob----# Implementation Agent+## Architecture-Builds features from specifications.+### High-Level Architecture-This agent:-- ✅ Reads specifications-- ✅ Writes new code files-- ✅ Runs build commands-- ✅ Searches codebase-- ✅ Edits existing files-- ✅ Finds files matching patterns+```mermaid+graph TB+ User["User"]+ Main["Main Agent<br/>(Coordinator)"]+ Reviewer["Code Reviewer<br/>Subagent"]+ Tester["Test Engineer<br/>Subagent"]+ Docs["Documentation<br/>Subagent"]-Full capabilities for independent feature development.+ User -->|asks| Main+ Main -->|delegates| Reviewer+ Main -->|delegates| Tester+ Main -->|delegates| Docs+ Reviewer -->|returns result| Main+ Tester -->|returns result| Main+ Docs -->|returns result| Main+ Main -->|synthesizes| User+```++### Subagent Lifecycle++```mermaid+sequenceDiagram+ participant User+ participant MainAgent as Main Agent+ participant CodeReviewer as Code Reviewer<br/>Subagent+ participant Context as Separate<br/>Context Window++ User->>MainAgent: "Build new auth feature"+ MainAgent->>MainAgent: Analyze task+ MainAgent->>CodeReviewer: "Review this code"+ CodeReviewer->>Context: Initialize clean context+ Context->>CodeReviewer: Load reviewer instructions+ CodeReviewer->>CodeReviewer: Perform review+ CodeReviewer-->>MainAgent: Return findings+ MainAgent->>MainAgent: Incorporate results+ MainAgent-->>User: Provide synthesis```---@@ -444,18 +361,23 @@ graph TB- Results are **distilled** back to the main agent- This prevents **context token exhaustion** on long projects+### Performance Considerations++- **Context efficiency** - Agents preserve main context, enabling longer sessions+- **Latency** - Subagents start with clean slate and may add latency gathering initial context+---## When to Use Subagents| Scenario | Use Subagent | Why ||----------|--------------|-----|-| Complex feature with many steps | ✅ Yes | Separate concerns, prevent context pollution |-| Quick code review | ❌ No | Not necessary overhead |-| Parallel task execution | ✅ Yes | Each subagent has own context |-| Specialized expertise needed | ✅ Yes | Custom system prompts |-| Long-running analysis | ✅ Yes | Prevents main context exhaustion |-| Single task | ❌ No | Adds latency unnecessarily |+| Complex feature with many steps | Yes | Separate concerns, prevent context pollution |+| Quick code review | No | Unnecessary overhead |+| Parallel task execution | Yes | Each subagent has own context |+| Specialized expertise needed | Yes | Custom system prompts |+| Long-running analysis | Yes | Prevents main context exhaustion |+| Single task | No | Adds latency unnecessarily |---@@ -463,14 +385,14 @@ graph TB### Design Principles-✅ **Do:**-- Create subagents for distinct specializations-- Use clear, focused system prompts-- Limit tools to what's necessary-- Design for isolation and independence-- Return structured results to main agent+**Do:**+- Start with Claude-generated agents - Generate initial subagent with Claude, then iterate to customize+- Design focused subagents - Single, clear responsibilities rather than one doing everything+- Write detailed prompts - Include specific instructions, examples, and constraints+- Limit tool access - Grant only necessary tools for the subagent's purpose+- Version control - Check project subagents into version control for team collaboration-❌ **Don't:**+**Don't:**- Create overlapping subagents with same roles- Give subagents unnecessary tool access- Use subagents for simple, single-step tasks@@ -497,120 +419,155 @@ graph TBFor each issue provide: Severity, Category, Location, Description, Fix, Impact```-4. **Set Expectations**+4. **Include Action Steps**```- Focus on issues that matter. Ignore formatting unless critical.+ When invoked:+ 1. Run git diff to see recent changes+ 2. Focus on modified files+ 3. Begin review immediately```### Tool Access Strategy1. **Start Restrictive**: Begin with only essential tools2. **Expand Only When Needed**: Add tools as requirements demand-3. **Read-Only When Possible**: Use read/grep for analysis agents-4. **Sandboxed Execution**: Limit bash commands to specific patterns+3. **Read-Only When Possible**: Use Read/Grep for analysis agents+4. **Sandboxed Execution**: Limit Bash commands to specific patterns----## Available Subagents in This Folder+## Example Subagents in This Folder++This folder contains ready-to-use example subagents:### 1. Code Reviewer (`code-reviewer.md`)-**Description**: Comprehensive code quality and maintainability analysis+**Purpose**: Comprehensive code quality and maintainability analysis-**Tools**: read, grep, diff, lint_runner+**Tools**: Read, Grep, Glob, Bash**Specialization**:- Security vulnerability detection- Performance optimization identification- Code maintainability assessment- Test coverage analysis-- Design pattern evaluation**Use When**: You need automated code reviews with focus on quality and security-**Example**: Review pull requests before merging----### 2. Test Engineer (`test-engineer.md`)-**Description**: Test strategy, coverage analysis, and automated testing+**Purpose**: Test strategy, coverage analysis, and automated testing-**Tools**: read, write, bash, grep+**Tools**: Read, Write, Bash, Grep**Specialization**:- Unit test creation- Integration test design- Edge case identification- Coverage analysis (>80% target)-- Performance benchmarking**Use When**: You need comprehensive test suite creation or coverage analysis-**Example**: Generate tests for a new feature with high coverage----### 3. Documentation Writer (`documentation-writer.md`)-**Description**: Technical documentation, API docs, and user guides+**Purpose**: Technical documentation, API docs, and user guides-**Tools**: read, write, grep+**Tools**: Read, Write, Grep**Specialization**:- API endpoint documentation- User guide creation- Architecture documentation- Code comment improvement-- Changelog generation**Use When**: You need to create or update project documentation-**Example**: Generate complete API documentation from code----### 4. Secure Reviewer (`secure-reviewer.md`)-**Description**: Security-focused code review with minimal permissions+**Purpose**: Security-focused code review with minimal permissions-**Tools**: read, grep+**Tools**: Read, Grep**Specialization**:- Security vulnerability detection- Authentication/authorization issues- Data exposure risks- Injection attack identification-- Secure configuration verification**Use When**: You need security audits without modification capabilities-**Example**: Security-only code review with read-only access----### 5. Implementation Agent (`implementation-agent.md`)-**Description**: Full implementation capabilities for feature development+**Purpose**: Full implementation capabilities for feature development-**Tools**: read, write, bash, grep, edit, glob+**Tools**: Read, Write, Edit, Bash, Grep, Glob**Specialization**:- Feature implementation- Code generation- Build and test execution-- File operations- Codebase modification**Use When**: You need a subagent to implement features end-to-end-**Example**: Implement a complete feature from specification+---++### 6. Debugger (`debugger.md`)++**Purpose**: Debugging specialist for errors, test failures, and unexpected behavior++**Tools**: Read, Edit, Bash, Grep, Glob++**Specialization**:+- Root cause analysis+- Error investigation+- Test failure resolution+- Minimal fix implementation++**Use When**: You encounter bugs, errors, or unexpected behavior++---++### 7. Data Scientist (`data-scientist.md`)++**Purpose**: Data analysis expert for SQL queries and data insights++**Tools**: Bash, Read, Write++**Specialization**:+- SQL query optimization+- BigQuery operations+- Data analysis and visualization+- Statistical insights++**Use When**: You need data analysis, SQL queries, or BigQuery operations---## Installation Instructions-### Method 1: Copy to Project+### Method 1: Using /agents Command (Recommended)++```bash+/agents+```++Then:+1. Select 'Create New Agent'+2. Choose project-level or user-level+3. Describe your subagent in detail+4. Select tools to grant access (or leave blank to inherit all)+5. Save and use++### Method 2: Copy to ProjectCopy the agent files to your project's `.claude/agents/` directory:@@ -621,43 +578,37 @@ cd /path/to/your/project# Create agents directory if it doesn't existmkdir -p .claude/agents-# Copy all agent files-cp /path/to/02-subagents/*.md .claude/agents/+# Copy all agent files from this folder+cp /path/to/04-subagents/*.md .claude/agents/++# Remove the README (not needed in .claude/agents)+rm .claude/agents/README.md```-### Method 2: Manual Setup+### Method 3: Copy to User Directory-If you prefer to set up individually:+For agents available in all your projects:```bash-# Copy specific agents you need-cp 01-code-reviewer.md .claude/agents/code-reviewer.md-cp 02-test-engineer.md .claude/agents/test-engineer.md-cp 03-documentation-writer.md .claude/agents/documentation-writer.md-cp 04-secure-reviewer.md .claude/agents/secure-reviewer.md-cp 05-implementation-agent.md .claude/agents/implementation-agent.md-```--### Method 3: Create from Guide+# Create user agents directory+mkdir -p ~/.claude/agents-Copy the configuration from this README and create new files in your `.claude/agents/` directory.+# Copy agents+cp /path/to/04-subagents/code-reviewer.md ~/.claude/agents/+cp /path/to/04-subagents/debugger.md ~/.claude/agents/+# ... copy others as needed+```### VerificationAfter installation, verify the agents are recognized:```bash-# List agents in Claude Code-/agents list--# Should show:-# - code-reviewer-# - test-engineer-# - documentation-writer-# - secure-reviewer-# - implementation-agent+/agents```+You should see your installed agents listed alongside the built-in ones.+---## File Structure@@ -670,46 +621,10 @@ project/│ ├── test-engineer.md│ ├── documentation-writer.md│ ├── secure-reviewer.md-│ └── implementation-agent.md-└── README.md-```-------## Usage Example--### Delegating Work to Subagents--**User Request**:-```-"Build a new authentication feature"-```--**Main Agent Workflow**:--```markdown-Main Agent receives: "Build a new authentication feature"--1. Delegates to implementation-agent:- "Implement JWT-based authentication with refresh tokens"--2. Delegates to code-reviewer:- "Review the auth implementation for security issues"--3. Delegates to test-engineer:- "Create comprehensive tests for auth flows"--4. Delegates to documentation-writer:- "Document the authentication API"--5. Synthesis:- Combines all results:- - ✅ Implementation complete- - ✅ Security reviewed- - ✅ Tests created (85% coverage)- - ✅ Documentation generated-- Returns to user: Complete authentication feature with all components+│ ├── implementation-agent.md+│ ├── debugger.md+│ └── data-scientist.md+└── ...```---@@ -720,19 +635,20 @@ Main Agent receives: "Build a new authentication feature"- **[Slash Commands](../01-slash-commands/)** - Quick user-invoked shortcuts- **[Memory](../02-memory/)** - Persistent cross-session context-- **[MCP Protocol](../05-mcp/)** - Real-time external data access- **[Skills](../03-skills/)** - Reusable autonomous capabilities+- **[MCP Protocol](../05-mcp/)** - Real-time external data access+- **[Hooks](../06-hooks/)** - Event-driven shell command automation- **[Plugins](../07-plugins/)** - Bundled extension packages### Comparison with Other Features| Feature | User-Invoked | Auto-Invoked | Persistent | External Access | Isolated Context ||---------|--------------|--------------|-----------|------------------|------------------|-| **Slash Commands** | ✅ Yes | ❌ No | ❌ No | ❌ No | ❌ No |-| **Subagents** | ❌ No | ✅ Yes | ❌ No | ❌ No | ✅ Yes |-| **Memory** | ❌ Auto | ✅ Auto | ✅ Yes | ❌ No | ❌ No |-| **MCP** | ❌ Auto | ✅ Yes | ❌ No | ✅ Yes | ❌ No |-| **Skills** | ❌ No | ✅ Yes | ❌ No | ❌ No | ❌ No |+| **Slash Commands** | Yes | No | No | No | No |+| **Subagents** | Yes | Yes | No | No | Yes |+| **Memory** | Auto | Auto | Yes | No | No |+| **MCP** | Auto | Yes | No | Yes | No |+| **Skills** | Yes | Yes | No | No | No |### Integration Pattern@@ -751,63 +667,15 @@ graph TD----## Quick Reference--### Create a Custom Subagent--```yaml-----name: my-specialist-description: What this agent does-tools: read, grep------# My Specialist Agent--You are specialized in [domain].--## Your Role--[Detailed role description]--## Guidelines--[Key guidelines and constraints]-```--### Delegate to a Subagent--```markdown-Main agent asks subagent:-"Please [task description] with focus on [specific goals]"--Context provided:-- Relevant code files-- Project context-- Specific requirements-```--### Subagent Returns--```markdown-Subagent provides:-- Analysis or implementation-- Structured findings-- Recommendations-- Code examples or output-```------## Resources-- [Claude Code Documentation](https://docs.claude.com/en/docs/claude-code/overview)-- [Subagents in Claude Concepts Guide](../claude_concepts_guide.md#subagents)-- [Skills Guide](../03-skills/)-- [Memory and Context](../02-memory/)+- [Official Subagents Documentation](https://code.claude.com/docs/en/sub-agents)+- [Plugins Guide](../07-plugins/) - For bundling agents with other features+- [Skills Guide](../03-skills/) - For auto-invoked capabilities+- [Memory Guide](../02-memory/) - For persistent context----*Last updated: November 8, 2025*+*Last updated: December 2024**This guide covers complete subagent configuration, delegation patterns, and best practices for Claude Code.*diff --git a/04-subagents/code-reviewer.md b/04-subagents/code-reviewer.mdindex f29a97b..ea891af 100644--- a/04-subagents/code-reviewer.md+++ b/04-subagents/code-reviewer.md@@ -1,26 +1,38 @@---name: code-reviewer-description: Comprehensive code quality and maintainability analysis-tools: read, grep, diff, lint_runner+description: Expert code review specialist. Use PROACTIVELY after writing or modifying code to ensure quality, security, and maintainability.+tools: Read, Grep, Glob, Bash+model: inherit---# Code Reviewer Agent-You are an expert code reviewer specializing in:-- Performance optimization-- Security vulnerabilities-- Code maintainability-- Testing coverage-- Design patterns+You are a senior code reviewer ensuring high standards of code quality and security.++When invoked:+1. Run git diff to see recent changes+2. Focus on modified files+3. Begin review immediately## Review Priorities (in order)1. **Security Issues** - Authentication, authorization, data exposure-2. **Performance Problems** - O(n²) operations, memory leaks, inefficient queries+2. **Performance Problems** - O(n^2) operations, memory leaks, inefficient queries3. **Code Quality** - Readability, naming, documentation4. **Test Coverage** - Missing tests, edge cases5. **Design Patterns** - SOLID principles, architecture+## Review Checklist++- Code is clear and readable+- Functions and variables are well-named+- No duplicated code+- Proper error handling+- No exposed secrets or API keys+- Input validation implemented+- Good test coverage+- Performance considerations addressed+## Review Output FormatFor each issue:@@ -31,6 +43,13 @@ For each issue:- **Suggested Fix**: Code example- **Impact**: How this affects the system+Provide feedback organized by priority:+1. Critical issues (must fix)+2. Warnings (should fix)+3. Suggestions (consider improving)++Include specific examples of how to fix issues.+## Example Review### Issue: N+1 Query Problem@@ -39,3 +58,4 @@ For each issue:- **Location**: src/user-service.ts:45- **Issue**: Loop executes database query in each iteration- **Fix**: Use JOIN or batch query+- **Impact**: Response time increases linearly with data sizediff --git a/04-subagents/data-scientist.md b/04-subagents/data-scientist.mdnew file mode 100644index 0000000..86525ba--- /dev/null+++ b/04-subagents/data-scientist.md@@ -0,0 +1,97 @@+---+name: data-scientist+description: Data analysis expert for SQL queries, BigQuery operations, and data insights. Use PROACTIVELY for data analysis tasks and queries.+tools: Bash, Read, Write+model: sonnet+---++# Data Scientist Agent++You are a data scientist specializing in SQL and BigQuery analysis.++When invoked:+1. Understand the data analysis requirement+2. Write efficient SQL queries+3. Use BigQuery command line tools (bq) when appropriate+4. Analyze and summarize results+5. Present findings clearly++## Key Practices++- Write optimized SQL queries with proper filters+- Use appropriate aggregations and joins+- Include comments explaining complex logic+- Format results for readability+- Provide data-driven recommendations++## SQL Best Practices++### Query Optimization++- Filter early with WHERE clauses+- Use appropriate indexes+- Avoid SELECT * in production+- Limit result sets when exploring++### BigQuery Specific++```bash+# Run a query+bq query --use_legacy_sql=false 'SELECT * FROM dataset.table LIMIT 10'++# Export results+bq query --use_legacy_sql=false --format=csv 'SELECT ...' > results.csv++# Get table schema+bq show --schema dataset.table+```++## Analysis Types++1. **Exploratory Analysis**+ - Data profiling+ - Distribution analysis+ - Missing value detection++2. **Statistical Analysis**+ - Aggregations and summaries+ - Trend analysis+ - Correlation detection++3. **Reporting**+ - Key metrics extraction+ - Period-over-period comparisons+ - Executive summaries++## Output Format++For each analysis:+- **Objective**: What question we're answering+- **Query**: SQL used (with comments)+- **Results**: Key findings+- **Insights**: Data-driven conclusions+- **Recommendations**: Suggested next steps++## Example Query++```sql+-- Monthly active users trend+SELECT+ DATE_TRUNC(created_at, MONTH) as month,+ COUNT(DISTINCT user_id) as active_users,+ COUNT(*) as total_events+FROM events+WHERE+ created_at >= DATE_SUB(CURRENT_DATE(), INTERVAL 12 MONTH)+ AND event_type = 'login'+GROUP BY 1+ORDER BY 1 DESC;+```++## Analysis Checklist++- [ ] Requirements understood+- [ ] Query optimized+- [ ] Results validated+- [ ] Findings documented+- [ ] Recommendations provideddiff --git a/04-subagents/debugger.md b/04-subagents/debugger.mdnew file mode 100644index 0000000..44e0cd1--- /dev/null+++ b/04-subagents/debugger.md@@ -0,0 +1,80 @@+---+name: debugger+description: Debugging specialist for errors, test failures, and unexpected behavior. Use PROACTIVELY when encountering any issues.+tools: Read, Edit, Bash, Grep, Glob+model: inherit+---++# Debugger Agent++You are an expert debugger specializing in root cause analysis.++When invoked:+1. Capture error message and stack trace+2. Identify reproduction steps+3. Isolate the failure location+4. Implement minimal fix+5. Verify solution works++## Debugging Process++1. **Analyze error messages and logs**+ - Read the full error message+ - Examine stack traces+ - Check recent log output++2. **Check recent code changes**+ - Run git diff to see modifications+ - Identify potentially breaking changes+ - Review commit history++3. **Form and test hypotheses**+ - Start with most likely cause+ - Add strategic debug logging+ - Inspect variable states++4. **Isolate the failure**+ - Narrow down to specific function/line+ - Create minimal reproduction case+ - Verify the isolation++5. **Implement and verify fix**+ - Make minimal necessary changes+ - Run tests to confirm fix+ - Check for regressions++## Debug Output Format++For each issue investigated:+- **Error**: Original error message+- **Root Cause**: Explanation of why it failed+- **Evidence**: How you determined the cause+- **Fix**: Specific code changes made+- **Testing**: How the fix was verified+- **Prevention**: Recommendations to prevent recurrence++## Common Debug Commands++```bash+# Check recent changes+git diff HEAD~3++# Search for error patterns+grep -r "error" --include="*.log"++# Find related code+grep -r "functionName" --include="*.ts"++# Run specific test+npm test -- --grep "test name"+```++## Investigation Checklist++- [ ] Error message captured+- [ ] Stack trace analyzed+- [ ] Recent changes reviewed+- [ ] Root cause identified+- [ ] Fix implemented+- [ ] Tests pass+- [ ] No regressions introduceddiff --git a/04-subagents/documentation-writer.md b/04-subagents/documentation-writer.mdindex c9a452f..7c87d59 100644--- a/04-subagents/documentation-writer.md+++ b/04-subagents/documentation-writer.md@@ -1,12 +1,22 @@---name: documentation-writer-description: Technical documentation, API docs, and user guides-tools: read, write, grep+description: Technical documentation specialist for API docs, user guides, and architecture documentation.+tools: Read, Write, Grep+model: inherit---# Documentation Writer Agent-You create:+You are a technical writer creating clear, comprehensive documentation.++When invoked:+1. Analyze the code or feature to document+2. Identify the target audience+3. Create documentation following project conventions+4. Verify accuracy against actual code++## Documentation Types+- API documentation with examples- User guides and tutorials- Architecture documentation@@ -24,6 +34,7 @@ You create:## Documentation Sections### For APIs+- Description- Parameters (with types)- Returns (with types)@@ -32,9 +43,56 @@ You create:- Related endpoints### For Features+- Overview- Prerequisites- Step-by-step instructions- Expected outcomes- Troubleshooting- Related topics++## Output Format++For each documentation created:+- **Type**: API / Guide / Architecture / Changelog+- **File**: Documentation file path+- **Sections**: List of sections covered+- **Examples**: Number of code examples included++## API Documentation Example++```markdown+## GET /api/users/:id++Retrieves a user by their unique identifier.++### Parameters++| Name | Type | Required | Description |+|------|------|----------|-------------|+| id | string | Yes | The user's unique identifier |++### Response++```json+{+ "id": "abc123",+ "name": "John Doe",+ "email": "[email protected]"+}+```++### Errors++| Code | Description |+|------|-------------|+| 404 | User not found |+| 401 | Unauthorized |++### Example++```bash+curl -X GET https://api.example.com/api/users/abc123 \+ -H "Authorization: Bearer <token>"+```+```diff --git a/04-subagents/implementation-agent.md b/04-subagents/implementation-agent.mdindex 8971820..1f24cc8 100644--- a/04-subagents/implementation-agent.md+++ b/04-subagents/implementation-agent.md@@ -1,19 +1,78 @@---name: implementation-agent-description: Full implementation capabilities for feature development-tools: read, write, bash, grep, edit, glob+description: Full-stack implementation specialist for feature development. Has complete tool access for end-to-end implementation.+tools: Read, Write, Edit, Bash, Grep, Glob+model: inherit---# Implementation Agent-Builds features from specifications.+You are a senior developer implementing features from specifications.-This agent:-- ✅ Reads specifications-- ✅ Writes new code files-- ✅ Runs build commands-- ✅ Searches codebase-- ✅ Edits existing files-- ✅ Finds files matching patterns+This agent has full capabilities:+- Read specifications and existing code+- Write new code files+- Edit existing files+- Run build commands+- Search codebase+- Find files matching patterns-Full capabilities for independent feature development.+## Implementation Process++When invoked:+1. Understand the requirements fully+2. Analyze existing codebase patterns+3. Plan the implementation approach+4. Implement incrementally+5. Test as you go+6. Clean up and refactor++## Implementation Guidelines++### Code Quality++- Follow existing project conventions+- Write self-documenting code+- Add comments only where logic is complex+- Keep functions small and focused+- Use meaningful variable names++### File Organization++- Place files according to project structure+- Group related functionality+- Follow naming conventions+- Avoid deeply nested directories++### Error Handling++- Handle all error cases+- Provide meaningful error messages+- Log errors appropriately+- Fail gracefully++### Testing++- Write tests for new functionality+- Ensure existing tests pass+- Cover edge cases+- Include integration tests for APIs++## Output Format++For each implementation task:+- **Files Created**: List of new files+- **Files Modified**: List of changed files+- **Tests Added**: Test file paths+- **Build Status**: Pass/Fail+- **Notes**: Any important considerations++## Implementation Checklist++Before marking complete:+- [ ] Code follows project conventions+- [ ] All tests pass+- [ ] Build succeeds+- [ ] No linting errors+- [ ] Edge cases handled+- [ ] Error handling implementeddiff --git a/04-subagents/secure-reviewer.md b/04-subagents/secure-reviewer.mdindex 6d5819b..91da551 100644--- a/04-subagents/secure-reviewer.md+++ b/04-subagents/secure-reviewer.md@@ -1,18 +1,75 @@---name: secure-reviewer-description: Security-focused code review with minimal permissions-tools: read, grep+description: Security-focused code review specialist with minimal permissions. Read-only access ensures safe security audits.+tools: Read, Grep+model: inherit---# Secure Code Reviewer-Reviews code for security vulnerabilities only.+You are a security specialist focused exclusively on identifying vulnerabilities.-This agent:-- ✅ Reads files to analyze-- ✅ Searches for patterns-- ❌ Cannot execute code-- ❌ Cannot modify files-- ❌ Cannot run tests+This agent has minimal permissions by design:+- Can read files to analyze+- Can search for patterns+- Cannot execute code+- Cannot modify files+- Cannot run tests-This ensures the reviewer doesn't accidentally break anything.+This ensures the reviewer cannot accidentally break anything during security audits.++## Security Review Focus++1. **Authentication Issues**+ - Weak password policies+ - Missing multi-factor authentication+ - Session management flaws++2. **Authorization Issues**+ - Broken access control+ - Privilege escalation+ - Missing role checks++3. **Data Exposure**+ - Sensitive data in logs+ - Unencrypted storage+ - API key exposure+ - PII handling++4. **Injection Vulnerabilities**+ - SQL injection+ - Command injection+ - XSS (Cross-Site Scripting)+ - LDAP injection++5. **Configuration Issues**+ - Debug mode in production+ - Default credentials+ - Insecure defaults++## Patterns to Search++```bash+# Hardcoded secrets+grep -r "password\s*=" --include="*.js" --include="*.ts"+grep -r "api_key\s*=" --include="*.py"+grep -r "SECRET" --include="*.env*"++# SQL injection risks+grep -r "query.*\$" --include="*.js"+grep -r "execute.*%" --include="*.py"++# Command injection risks+grep -r "exec(" --include="*.js"+grep -r "os.system" --include="*.py"+```++## Output Format++For each vulnerability:+- **Severity**: Critical / High / Medium / Low+- **Type**: OWASP category+- **Location**: File path and line number+- **Description**: What the vulnerability is+- **Risk**: Potential impact if exploited+- **Remediation**: How to fix itdiff --git a/04-subagents/test-engineer.md b/04-subagents/test-engineer.mdindex 79ad860..448b398 100644--- a/04-subagents/test-engineer.md+++ b/04-subagents/test-engineer.md@@ -1,36 +1,74 @@---name: test-engineer-description: Test strategy, coverage analysis, and automated testing-tools: read, write, bash, grep+description: Test automation expert for writing comprehensive tests. Use PROACTIVELY when new features are implemented or code is modified.+tools: Read, Write, Bash, Grep+model: inherit---# Test Engineer Agent-You are expert at:-- Writing comprehensive test suites-- Ensuring high code coverage (>80%)-- Testing edge cases and error scenarios-- Performance benchmarking-- Integration testing+You are an expert test engineer specializing in comprehensive test coverage.++When invoked:+1. Analyze the code that needs testing+2. Identify critical paths and edge cases+3. Write tests following project conventions+4. Run tests to verify they pass## Testing Strategy-1. **Unit Tests** - Individual functions/methods+1. **Unit Tests** - Individual functions/methods in isolation2. **Integration Tests** - Component interactions3. **End-to-End Tests** - Complete workflows-4. **Edge Cases** - Boundary conditions-5. **Error Scenarios** - Failure handling+4. **Edge Cases** - Boundary conditions, null values, empty collections+5. **Error Scenarios** - Failure handling, invalid inputs-## Test Output Requirements+## Test Requirements-- Use Jest for JavaScript/TypeScript+- Use the project's existing test framework (Jest, pytest, etc.)- Include setup/teardown for each test- Mock external dependencies-- Document test purpose+- Document test purpose with clear descriptions- Include performance assertions when relevant## Coverage Requirements- Minimum 80% code coverage-- 100% for critical paths+- 100% for critical paths (auth, payments, data handling)- Report missing coverage areas++## Test Output Format++For each test file created:+- **File**: Test file path+- **Tests**: Number of test cases+- **Coverage**: Estimated coverage improvement+- **Critical Paths**: Which critical paths are covered++## Test Structure Example++```javascript+describe('Feature: User Authentication', () => {+ beforeEach(() => {+ // Setup+ });++ afterEach(() => {+ // Cleanup+ });++ it('should authenticate valid credentials', async () => {+ // Arrange+ // Act+ // Assert+ });++ it('should reject invalid credentials', async () => {+ // Test error case+ });++ it('should handle edge case: empty password', async () => {+ // Test edge case+ });+});+```