Claude Code Subagents: Troubleshooting Guide
Common Issues and Solutions
1. Subagent Task Drift
Problem: Subagents ignore their specific task and try to solve the entire problem.
// Problem example
const taskDriftExample = `
Main request: "Implement user authentication"
Task 1: "Analyze existing auth code"
Result: Subagent implements entire auth system instead of analyzing
`;
// Solution: Clear boundaries and stop conditions
const preventTaskDrift = `
Task 1: ONLY analyze existing auth code in src/auth/
- DO NOT implement new features
- DO NOT modify any files
- STOP after creating analysis report
- Return: List of current auth methods and potential issues
`;2. Context Window Exhaustion
Problem: Subagents lose context after compaction, requiring file re-reading.
// Symptoms
interface ContextExhaustionSymptoms {
symptoms: [
'Subagent forgets previously read files',
'Repeated file reading in logs',
'Incomplete task execution',
'Missing references to earlier findings'
];
}
// Solution: Context preservation strategy
const contextPreservation = `
1. Main agent creates context-summary.md before spawning subagents
2. Each subagent reads context-summary.md first
3. Subagents write key findings to findings-{taskId}.md
4. Main agent reads all findings files for synthesis
Example structure:
/temp
/context-summary.md # Created by main agent
/findings-task1.md # Created by subagent 1
/findings-task2.md # Created by subagent 2
`;3. Batch Processing Delays
Problem: Tasks wait for entire batch to complete before next batch starts.
// Problem scenario
const batchDelayProblem = `
10 tasks requested:
- Tasks 1-9: Complete in 30 seconds
- Task 10: Takes 5 minutes
- Tasks 11-20: Wait 5 minutes to start
`;
// Workaround strategies
const batchOptimization = {
strategy1: 'Dont specify parallelism level - let Claude optimize',
strategy2: 'Group similar-duration tasks together',
strategy3: 'Use progressive task deployment',
example: `
// Instead of requesting 20 tasks at once:
Phase 1: "Analyze codebase with 5 quick exploration tasks"
Phase 2: "Based on findings, deploy appropriate implementation tasks"
`
};4. Token Consumption Explosion
Problem: Subagents consume 3-4x more tokens than expected.
// Monitoring pattern
const tokenMonitoring = `
Before using subagents, calculate:
- Base context size: ~X tokens
- Per-subagent overhead: ~Y tokens
- Number of subagents: N
- Estimated total: (X + Y) * N * 3.5
If total > token_budget:
- Reduce number of subagents
- Minimize context per subagent
- Use direct tools instead
`;
// Token reduction techniques
interface TokenReduction {
useStructuredOutputs: 'Enforce specific, concise output formats';
limitFileReading: 'Specify exact files/directories to analyze';
avoidDuplication: 'Prevent multiple agents reading same files';
summarizeEarly: 'Have subagents create summaries, not full reports';
}5. Subagent Communication Failures
Problem: No real-time communication between parent and subagents.
// Problem example
const communicationProblem = `
Parent: "Find all API endpoints"
Subagent: Finds critical security issue
Parent: Doesn't know about security issue until task completes
`;
// Workaround: Structured checkpoints
const checkpointPattern = `
Implement pseudo-communication via files:
Task instruction:
"If you find CRITICAL issues:
1. Create CRITICAL-{timestamp}.md immediately
2. Continue with main task
3. Main agent will check for CRITICAL-*.md files"
Main agent:
"After subagents complete, first check for CRITICAL-*.md files"
`;6. Hook Interference
Problem: Stop hooks or other hooks interfere with Task tool.
// Diagnosis
const hookDiagnosis = `
Symptoms:
- Tasks fail to start
- "Blocked by hook" messages
- Unexpected task termination
Check: ~/.claude/settings.json for hook configurations
`;
// Solutions
interface HookSolutions {
solution1: {
action: 'Temporarily disable hooks',
command: 'claude --no-hooks',
};
solution2: {
action: 'Configure hook exclusions',
config: {
hooks: {
'task-start': {
exclude: ['Task', 'subagent']
}
}
}
};
solution3: {
action: 'Use hook-friendly task names',
example: 'Prefix tasks with "SUBTASK:" to bypass filters'
};
}7. Deceptive Subagent Behavior
Problem: Subagents simulate work instead of actually performing it.
// Detection pattern
const deceptionDetection = `
Warning signs:
- Suspiciously fast completion
- Vague or generic results
- No specific file:line references
- Claims of "simulated" or "example" outputs
Prevention:
1. Request specific file paths and line numbers
2. Ask for exact error messages or output
3. Require code snippets in responses
4. Validate results with direct tool usage
`;
// Verification strategy
const verifySubagentWork = `
After subagents complete:
1. Spot-check claimed modifications with Read tool
2. Run tests to verify implementations
3. Check git diff for actual changes
4. Validate file paths exist
`;8. Memory and State Management Issues
Problem: Subagents lack persistent memory between invocations.
// Problem scenario
const memoryProblem = `
Task 1: Analyzes codebase, finds 10 issues
Task 2: Needs to fix the 10 issues
Result: Task 2 doesn't know what issues Task 1 found
`;
// Solution: External state management
const stateManagement = `
Pattern 1: Markdown-based state
- Create state.md before tasks
- Each task updates state.md
- Later tasks read state.md
Pattern 2: Git-based state
- Commit after each task
- Use commit messages for state
- Later tasks read git log
Pattern 3: Comment-based state
- Add TODO comments in code
- Later tasks search for TODOs
`;Debugging Techniques
1. Subagent Output Analysis
// Debug prompt template
const debugPrompt = `
[YOUR NORMAL TASK]
DEBUG INFO - Include in response:
- Start time: {timestamp}
- Files accessed: {list}
- Tools used: {list}
- Errors encountered: {list}
- Token estimate: {number}
- Completion status: {percentage}
`;2. Progressive Debugging
// Start simple, add complexity
const progressiveDebug = {
step1: 'Test with 1 subagent on known task',
step2: 'Test with 2 subagents on independent tasks',
step3: 'Test with 5 subagents on related tasks',
step4: 'Full implementation with all subagents',
validateEachStep: [
'Check token usage',
'Verify output quality',
'Measure completion time',
'Validate no task drift'
]
};3. Common Error Messages
interface ErrorSolutions {
'Context window exceeded': {
cause: 'Too much context provided to subagent',
solution: 'Reduce initial context, use summaries'
},
'Task failed to complete': {
cause: 'Subagent encountered unhandled error',
solution: 'Add error handling to task prompt'
},
'Circular dependency detected': {
cause: 'Tasks depend on each other\'s output',
solution: 'Restructure tasks to be independent'
},
'Token limit reached': {
cause: 'Cumulative token usage too high',
solution: 'Reduce number of subagents or scope'
}
}Prevention Strategies
1. Pre-flight Checklist
const preflightChecklist = `
Before launching subagents:
- [ ] Clear, bounded task definitions
- [ ] No circular dependencies
- [ ] Reasonable token budget
- [ ] Output format specified
- [ ] Error handling included
- [ ] Success criteria defined
- [ ] Context minimized
- [ ] Hooks configured properly
`;2. Task Template
// Robust task template
const robustTaskTemplate = `
TASK: {specific_action}
SCOPE: {exact_boundaries}
INPUT: {required_context}
OUTPUT: {expected_format}
CONSTRAINTS:
- Do not exceed {scope}
- Stop when {condition}
- Return empty result if {error_condition}
ERROR_HANDLING:
- If file not found: {action}
- If permission denied: {action}
SUCCESS_CRITERIA: {measurable_outcome}
`;3. Monitoring Dashboard
// Create monitoring file
const monitoringSetup = `
Create monitor.md with:
## Subagent Status
| Task | Status | Start | End | Tokens | Result |
|------|---------|--------|------|---------|---------|
| 1 | Running | 10:00 | - | - | - |
Update after each task completes.
`;Recovery Procedures
When Things Go Wrong
-
Interrupt and Assess
- Use Escape to stop execution
- Check partial outputs
- Identify failed tasks
-
Salvage Partial Results
- Read any created files
- Check git status for changes
- Preserve useful outputs
-
Restart with Refinements
- Adjust task definitions
- Reduce scope if needed
- Add error handling
-
Alternative Approaches
- Use direct tools instead
- Break into smaller sequential steps
- Reduce parallelism