Claude Code Subagents and Plan Mode: The New Era of Intelligent Collaboration
Claude Code 2.0 Core Features Deep Dive Series
This is Part 2 of the series. The complete series includes:
- Skills and Sandbox - Enhancing Extensibility and Security
- Subagents and Plan Mode - The New Era of Intelligent Collaboration (This Article)
- Hooks System and Migration Guide - Workflow Automation and Smooth Upgrades
Claude Code 2.0.28 introduces the revolutionary Plan Subagent and enhanced Subagent system, combined with v2.0.21’s Interactive Questions feature, pioneering a new collaborative model for AI-assisted development. This article provides an in-depth exploration of Subagent enhancements, Plan Mode mechanisms, and how to build smarter development workflows through interactive Q&A.
Plan Subagent: Intelligent Assistant Focused on Planning
Plan Subagent Operating Principles
Plan Subagent is a special subagent type specifically designed for the planning phase, operating under Plan Mode and focusing on information gathering and analysis without performing any modifications.
graph TB
A[User Request] --> B{Enter Plan Mode}
B --> C[Main Agent Analyzes Task]
C --> D{Need Code Exploration?}
D -->|Yes| E[Launch Plan Subagent]
D -->|No| F[Main Agent Direct Planning]
E --> G[Plan Subagent Read-Only Analysis]
G --> H[Use Read/Grep/Glob]
H --> I[Collect Code Information]
I --> J[Report Analysis Results]
J --> K[Main Agent Integrates Information]
F --> K
K --> L[Ask Clarifying Questions]
L --> M[Interactive Questions]
M --> N[User Answers]
N --> O[Main Agent Generates Complete Plan]
O --> P{User Confirms?}
P -->|Yes| Q[Exit Plan Mode]
P -->|No| L
Q --> R[Execute Plan]
style A fill:#e1f5fe
style E fill:#fff3e0
style M fill:#c8e6c9
style R fill:#c8e6c9
Comparing Plan Subagent with Other Subagent Types
| Feature | Plan Subagent | Explore Subagent | General Subagent |
|---|---|---|---|
| Primary Purpose | Planning phase analysis | Code exploration | General task execution |
| Available Tools | Read-only tools | All tools | All tools |
| Execution Mode | Plan Mode only | Any mode | Any mode |
| Modification Capability | None (read-only) | Yes | Yes |
| Recommended Model | Sonnet/Haiku | Sonnet | Sonnet/Opus |
| Use Cases | Pre-analysis for complex tasks | Codebase exploration | Independent subtasks |
Configuration and Usage
Basic Configuration
Plan Subagents typically don’t require manual configuration; Claude automatically uses them under Plan Mode. However, you can create custom Plan-focused subagents:
---
name: architecture-planner
description: Architecture design planning expert for analyzing existing code architecture and proposing improvement plans
model: sonnet
disallowedTools: [Write, Edit, Bash, NotebookEdit]
---
# Architecture Design Planning Expert
You are a software architecture planning expert, focused on analyzing existing code architecture and proposing improvement solutions.
## Analysis Focus
### 1. Architecture Pattern Identification
- Identify currently used architecture patterns (MVC, MVVM, Clean Architecture, etc.)
- Evaluate completeness and consistency of pattern implementation
- Find deviations from standard patterns
### 2. Dependency Analysis
- Draw module dependency diagrams
- Identify circular dependencies
- Evaluate coupling and cohesion
- Find violations of dependency inversion principle
### 3. Scalability Assessment
- Analyze system's horizontal scaling capability
- Evaluate vertical scaling limitations
- Identify potential bottlenecks
- Assess microservices feasibility
### 4. Code Organization
- Evaluate directory structure rationality
- Check module division clarity
- Analyze file size and complexity distribution
- Identify areas needing refactoring
## Output Format
### Current Status Analysis
\```markdown
## Architecture Status
### Adopted Patterns
- Primary pattern: [Pattern name]
- Implementation level: [Percentage]
- Advantages:
- [Advantage 1]
- [Advantage 2]
- Disadvantages:
- [Disadvantage 1]
- [Disadvantage 2]
### Dependency Diagram
\```mermaid
graph LR
A[Module A] --> B[Module B]
B --> C[Module C]
C --> A
style C fill:#ff6b6b
\```
(Circular dependencies marked in red)
### Issue List
1. **Circular Dependency** (Critical)
- Location: Module A <-> Module C
- Impact: Difficult to test and maintain
2. **High Coupling** (Major)
- Location: Module B
- Impact: High modification cost
\```
### Improvement Suggestions
\```markdown
## Refactoring Plan
### Short-term Improvements (1-2 weeks)
1. Resolve circular dependencies
- Step 1: Create interface layer
- Step 2: Inject dependencies
- Expected effect: Improve testability
2. Extract common logic
- Goal: Reduce duplicate code by 30%
- Method: Create common utility module
### Medium-term Improvements (1-2 months)
1. Implement layered architecture
- Presentation Layer
- Business Logic Layer
- Data Access Layer
2. Introduce dependency injection container
- Tool recommendation: [Specific tool]
- Expected effect: Reduce coupling
### Long-term Vision (3-6 months)
1. Microservices feasibility assessment
- Candidate services: [List]
- Data isolation strategy
- API gateway design
## Risk Assessment
- Refactoring risk: [High/Medium/Low]
- Recommended strategy: [Incremental refactoring/Big bang refactoring]
- Testing requirements: [Specific requirements]
\```
Practical Application Scenarios
Scenario 1: Large Project Architecture Analysis
User request:
Help me analyze the architecture of this 100k-line codebase and suggest refactoring improvements
Plan Mode workflow:
- Main Agent enters Plan Mode
- Launch Plan Subagent to analyze code structure
- Plan Subagent uses Glob to find all source files
- Use Read to read key config files and entry files
- Use Grep to search for architecture pattern keywords
- Report analysis results to main Agent
- Main Agent asks clarifying questions (using Interactive Questions)
- Generate complete refactoring plan after integrating information
Scenario 2: Performance Optimization Planning
My API response time is too slow, help me find bottlenecks and plan optimization solutions
Plan Subagent analysis steps:
- Search all API route definitions
- Analyze database query patterns
- Check for N+1 query issues
- Identify queries missing indexes
- Analyze caching strategy implementation
- Check for blocking I/O operations
- Suggest optimization priorities
Scenario 3: Testing Strategy Planning
This module lacks tests, help me plan test coverage strategy
Plan Subagent work:
- Analyze module’s public API
- Identify key business logic
- Find boundary conditions and exception cases
- Evaluate dependencies (parts needing mocking)
- Suggest test types (unit/integration/E2E)
- Generate test file structure suggestions
- Estimate test writing workload
Interactive Questions: Interactive Development Experience
AskUserQuestion Tool Explained
Interactive Questions feature enables Claude to proactively ask users for clarification of requirements or preferences when needed.
Tool Parameter Structure
{
questions: [
{
question: string; // Complete question text
header: string; // Short label (max 12 characters)
multiSelect: boolean; // Allow multiple selections?
options: [
{
label: string; // Option display text (1-5 words)
description: string; // Detailed option description
}
]; // 2-4 options
}
]; // 1-4 questions
}
Single-Select Question Example
{
questions: [
{
question: "Which authentication method should this API use?",
header: "Auth Method",
multiSelect: false,
options: [
{
label: "JWT",
description: "JSON Web Token, suitable for stateless auth, supports distributed systems"
},
{
label: "OAuth 2.0",
description: "Industry standard, suitable for third-party login and auth delegation"
},
{
label: "Session",
description: "Traditional session-based auth, simple but requires state management"
},
{
label: "API Key",
description: "Simple API key auth, suitable for internal services or simple scenarios"
}
]
}
]
}
Multi-Select Question Example
{
questions: [
{
question: "Which additional features should this functionality implement?",
header: "Extra Features",
multiSelect: true, // Allow multi-select
options: [
{
label: "Caching",
description: "Implement caching with Redis, improve query performance"
},
{
label: "Rate Limiting",
description: "Prevent API abuse, protect system stability"
},
{
label: "Audit Logs",
description: "Record all operations, meet compliance requirements"
},
{
label: "Data Validation",
description: "Validate input data using JSON Schema"
}
]
}
]
}
Multi-Question Combination Example
{
questions: [
{
question: "Choose database type",
header: "Database",
multiSelect: false,
options: [
{ label: "PostgreSQL", description: "Relational DB, ACID guarantees, JSON support" },
{ label: "MongoDB", description: "Document-oriented DB, flexible schema" },
{ label: "MySQL", description: "Mature relational DB, complete ecosystem" }
]
},
{
question: "Choose ORM/ODM tool",
header: "Data Access",
multiSelect: false,
options: [
{ label: "Prisma", description: "Modern TypeScript ORM, type-safe" },
{ label: "TypeORM", description: "Feature-complete ORM, supports multiple databases" },
{ label: "Mongoose", description: "MongoDB ODM, schema validation" },
{ label: "Raw Queries", description: "Direct database driver use, maximum flexibility" }
]
},
{
question: "Which features to implement?",
header: "Features",
multiSelect: true,
options: [
{ label: "Full-text Search", description: "Using Elasticsearch or DB full-text index" },
{ label: "Real-time Notifications", description: "WebSocket or Server-Sent Events" },
{ label: "File Uploads", description: "Support large file uploads and processing" }
]
}
]
}
Q&A Interaction in Plan Mode
In Plan Mode, Claude uses Interactive Questions more frequently to clarify requirements.
Interaction Flow Diagram
graph TD
A[Plan Mode Start] --> B[Analyze User Request]
B --> C{Requirements Clear?}
C -->|No| D[Ask Clarifying Questions]
C -->|Yes| E{Multiple Implementation Options?}
D --> F[AskUserQuestion]
F --> G[Wait for User Response]
G --> H[Integrate Answers into Context]
H --> B
E -->|Yes| I[Ask Selection Questions]
E -->|No| J[Generate Unique Plan]
I --> F
J --> K[ExitPlanMode Present Plan]
K --> L{User Confirms?}
L -->|No| D
L -->|Yes| M[Start Execution]
style A fill:#e1f5fe
style F fill:#fff3e0
style M fill:#c8e6c9
Known Issues and Solutions
Issue: AskUserQuestion in Skills Not Working Properly
Symptoms: When using AskUserQuestion in Skills, questions don’t display correctly or cause errors.
Cause: Skills may not correctly handle interactive questions before Plan Mode is first enabled.
Solution:
# 1. Restart Claude Code
# 2. Manually switch to Plan Mode first
/plan
# 3. Then use the Skill that needs to ask questions
Alternative: Explicitly guide Claude to use AskUserQuestion in CLAUDE.md:
# CLAUDE.md
## Interactive Questions Guide
When facing these situations, use the AskUserQuestion tool:
1. **Unclear Requirements**
- Multiple implementation approaches available
- Technical selection needs decision
- Unclear feature scope
2. **Question Design Principles**
- Maximum 4 options per question
- Keep option labels short (1-5 words)
- Descriptions clearly explain choice impacts
- Use multiSelect when options aren't mutually exclusive
3. **Example Scenarios**
- Choose authentication method
- Decide database type
- Confirm feature priorities
- Technology stack selection
Subagent Enhancements
Subagent Resumption
Starting from v2.0.28, Claude can resume existing subagents instead of always creating new ones.
Operating Principle
Traditional Mode:
User request → Create new Subagent A → Complete task
User request → Create new Subagent B → Complete task
(Each time is a new subagent, no context continuity)
Resumption Mode:
User request → Create Subagent A → Complete task
User request → Resume Subagent A → Complete task (retain previous context)
(Reuse subagent, maintain context continuity)
Actual Benefits
Scenario: Multi-stage refactoring task
Stage 1: Analyze code architecture
→ Launch Explore Subagent (ID: explore-001)
→ Analysis complete, report results
Stage 2: Propose refactoring plan based on analysis
→ Resume Explore Subagent (ID: explore-001)
→ Has Stage 1 context, directly propose plan
Stage 3: Check plan feasibility
→ Resume Explore Subagent (ID: explore-001)
→ Verify plan based on complete context
Advantages:
- Avoid duplicate analysis
- Maintain context continuity
- Improve execution efficiency
- Reduce token usage
Dynamic Model Selection
Subagents can choose different models based on task characteristics.
Model Options
---
name: my-subagent
description: Example subagent
model: sonnet # Options: sonnet, opus, haiku, inherit
---
| Model Option | Description | Applicable Scenarios | Cost |
|---|---|---|---|
sonnet |
Claude Sonnet 4.5 | Balance performance and cost, suitable for most tasks | Medium |
opus |
Claude Opus | Highest quality, complex reasoning tasks | High |
haiku |
Claude Haiku 4.5 | Fast simple tasks | Low |
inherit |
Inherit from main Agent | Keep consistent with main Agent | Depends on main |
Model Selection Strategy
Example 1: Quick Code Search Using Haiku
---
name: quick-search
description: Quick code search to find specific functions or class locations
model: haiku
---
# Quick Search Expert
Your task is to quickly find specific elements in code:
- Use Grep to search function definitions
- Use Glob to find related files
- Report locations and brief descriptions
No need for in-depth analysis, just quick location.
Example 2: Complex Architecture Analysis Using Opus
---
name: architecture-analyzer
description: Deep analysis of complex system architecture, provide professional advice
model: opus
---
# Architecture Analysis Expert
You need to perform deep analysis:
- Understand complex system design
- Identify subtle architecture issues
- Provide in-depth improvement suggestions
- Consider multiple trade-off factors
disallowedTools: Tool Blocking Mechanism
Starting from v2.0.30, you can explicitly prohibit subagents from using specific tools.
Basic Syntax
---
name: safe-analyzer
description: Secure read-only analysis subagent
disallowedTools: [Write, Edit, Bash, NotebookEdit]
---
# Secure Analysis Expert
You can only read and analyze code, cannot make any modifications.
Difference from allowed-tools
| Feature | allowed-tools |
disallowedTools |
|---|---|---|
| Semantics | Whitelist: Can only use these | Blacklist: Cannot use these |
| Applies to | Skills | Subagents (v2.0.30+) |
| Use When | Clearly know which tools needed | Clearly know which tools to prohibit |
| Default Behavior | Unlisted tools prohibited | Unlisted tools allowed |
Security Best Practices
Read-Only Analysis Subagent:
---
name: read-only-explorer
description: Read-only code exploration, absolutely no modifications
model: sonnet
disallowedTools:
- Write
- Edit
- Bash
- NotebookEdit
- TodoWrite # Also cannot create todos
---
# Read-Only Exploration Expert
Your responsibility is to explore and analyze code, provide insights and suggestions.
## Allowed Operations
- Read: Read files
- Grep: Search content
- Glob: Find files
- WebFetch: Check documentation
## Prohibited Operations
- Any file modifications
- Execute commands
- Create new files
- Edit notebooks
## Working Method
1. Collect information using Read/Grep/Glob
2. Analyze and understand code
3. Provide detailed text reports
4. Suggest specific improvement directions (but don't implement)
Combined Configuration Example
Complete subagent definition combining multiple restrictions:
---
name: secure-code-auditor
description: Secure code audit, read-only and offline
model: sonnet
disallowedTools:
# Prohibit modifications
- Write
- Edit
- NotebookEdit
# Prohibit execution
- Bash
- KillShell
# Prohibit network access
- WebFetch
- WebSearch
# Prohibit interaction (automated audit)
- AskUserQuestion
# Prohibit task management
- TodoWrite
- Task
---
# Secure Code Auditor Expert
You are an automated code security audit tool, performing unattended security scans.
## Workflow
### 1. Information Gathering
- Use Read to read all source code files
- Use Grep to search security-related patterns
- Use Glob to find specific file types
### 2. Security Checks
#### Common Vulnerability Scanning
- SQL injection risks
- XSS attack vectors
- CSRF protection checks
- Path traversal vulnerabilities
- Unsafe deserialization
#### Sensitive Data Checks
- Hardcoded passwords, API keys
- Unencrypted sensitive data
- Insecure encryption algorithm usage
#### Dependency Security
- Check dependency versions with known vulnerabilities
- Outdated packages
### 3. Report Generation
Generate structured Markdown report:
\```markdown
# Security Audit Report
## Execution Time
[Timestamp]
## Scan Scope
- Files: [Count]
- Lines of Code: [Count]
## Found Issues
### 🔴 Critical (Immediate Fix Required)
1. **SQL Injection Risk**
- File: `src/db/users.ts:45`
- Code: `db.query("SELECT * FROM users WHERE id = " + userId)`
- Risk: User input directly concatenated into SQL query
- Recommendation: Use parameterized queries
### 🟡 Major (Should Fix)
[...]
### 🟢 Minor (Optional Improvements)
[...]
## Statistics Summary
- Critical: [Count]
- Major: [Count]
- Minor: [Count]
## Recommended Priorities
1. [Highest priority item]
2. [Second priority item]
\```
Complete Workflow Integration
Plan Mode → Execution Complete Flow
sequenceDiagram
participant U as User
participant M as Main Agent
participant PS as Plan Subagent
participant Q as Interactive Questions
participant E as Execution Agent
U->>M: Submit Request
M->>M: Activate Plan Mode
M->>PS: Launch Plan Subagent
PS->>PS: Analyze with Read/Grep/Glob
PS->>M: Report Analysis Results
M->>Q: Initiate Clarifying Questions
Q->>U: Display Options
U->>Q: Select Answers
Q->>M: Return Answers
M->>M: Integrate Info and Generate Plan
M->>U: ExitPlanMode Present Plan
U->>M: Confirm Plan
M->>M: Exit Plan Mode
M->>E: Start Execution
E->>E: Implement Features
E->>M: Complete
M->>U: Report Results
Series Navigation
← Previous: Skills and Sandbox - Enhancing Extensibility and Security
Next: Hooks System and Migration Guide - Workflow Automation and Smooth Upgrades →
View complete series: Claude Code 2.0 Core Features Deep Dive