[FEATURE] Agent Output Limit Handoffs and Multi-Agent Task Orchestration
Preflight Checklist
- [x] I have searched existing requests and this feature hasn't been requested yet
- [x] This is a single feature request (not multiple features)
Problem Statement
When working on complex, large-scale tasks (e.g., refactoring 50+ files,
comprehensive codebase migrations, multi-service feature implementations), individual
agents frequently hit output token limits before completing their work. Currently,
when this happens:
- The agent truncates its output mid-task
- Remaining work is lost or requires manual coordination
- No mechanism exists for the agent to hand off incomplete work to a successor agent
- Context and progress aren't preserved for continuation
This creates a hard ceiling on task complexity that Claude Code can handle
autonomously.
Proposed Solution
Multi-Agent Orchestration Framework
Implement a three-tier agent system that enables complex tasks to be automatically
decomposed, distributed across multiple agents, and integrated into a cohesive
result.
Architecture Overview:
graph TD
A[Planning Agent - Orchestrator] --> B[Executor Agent 1: Files 1-30]
A --> C[Executor Agent 2: Files 31-60]
A --> D[Executor Agent 3: Files 61-90]
A --> E[Executor Agent N: Files 91-N]
B --> F[Integrator Agent]
C --> F
D --> F
E --> F
style A fill:#e1f5ff
style F fill:#fff4e1
Workflow Phases:
- Planning Phase: Orchestrator analyzes task and creates execution plan
- Execution Phase: Multiple executor agents work on subtasks (sequential or
parallel)
- Integration Phase: Integrator validates, synthesizes, and verifies results
---
Core Components
- Planning Agent (Orchestrator)
Capabilities:
- Analyzes task complexity and estimates required agent count
- Creates hierarchical execution plan with clear subtask boundaries
- Assigns subtasks to executor agents with defined success criteria
- Monitors progress and adapts plan if agents fail/succeed early
Output Format:
{
"task_id": "migrate-typescript-2024-10-02",
"estimated_agents": 8,
"execution_strategy": "sequential",
"plan": [
{
"step": 1,
"agent_type": "code-analyzer",
"description": "Analyze codebase and identify conversion order",
"success_criteria": [
"dependency graph generated",
"migration order defined"
],
"estimated_output_tokens": 5000
},
{
"step": 2,
"agent_type": "typescript-converter",
"description": "Convert files 1-30 to TypeScript",
"depends_on": [1],
"input_context": "migration-order.json",
"success_criteria": [
"30 files converted",
"no syntax errors"
],
"handoff_strategy": "sequential"
}
]
}
---
- Executor Agents (Workers)
New Capabilities:
A. Output Limit Detection:
- Agents monitor their remaining output token budget in real-time
- At 80% capacity: Begin handoff preparation (summarize progress)
- At 95% capacity: Force handoff with full state preservation
- Prevents truncated outputs and lost work
B. State Preservation:
Each agent outputs a handoff manifest before reaching output limits:
{
"agent_id": "executor-2-typescript-converter",
"status": "handoff_required",
"completed_items": [
"src/file1.ts",
"src/file2.ts",
"src/file30.ts"
],
"in_progress_item": {
"file": "src/file31.ts",
"line_number": 145,
"last_action": "converted function declaration",
"remaining_work": [
"convert class methods",
"add type exports"
]
},
"pending_items": [
"src/file32.ts",
"src/file33.ts",
"src/file60.ts"
],
"decisions_made": [
{
"decision": "using strict mode for all conversions",
"rationale": "team standard from tsconfig.json"
},
{
"decision": "preferring interfaces over types for objects",
"rationale": "better for extension and declaration merging"
}
],
"issues_encountered": [
{
"file": "src/file15.ts",
"issue": "circular dependency detected",
"resolution": "deferred to integration phase"
}
],
"patterns_established": [
"React components use functional style with hooks",
"Utility functions exported as const",
"Test files mirror source file structure"
]
}
C. Context Inheritance:
Successor agents automatically receive:
- ✅ Full handoff manifest from predecessor
- ✅ Original planning agent's context and execution plan
- ✅ Accumulated decisions, patterns, and conventions from all previous agents
- ✅ Exact position in overall task (no duplicate work)
- ✅ Known issues and their resolutions
This ensures seamless continuation as if a single agent had unlimited output
capacity.
---
- Integrator Agent (Synthesizer)
Responsibilities:
- Receives and analyzes results from all executor agents
- Validates consistency across outputs (same patterns, conventions, style)
- Detects and resolves conflicts between different agents' approaches
- Performs final quality gates (tests, builds, linting, security scans)
- Generates comprehensive summary report for user
Example Integration Report:
## Integration Validation Report
### Consistency Checks
✅ All 200 files use same TypeScript strict mode settings
✅ Import paths consistent across all conversions
✅ Error handling patterns unified
⚠️ Agents 2 and 5 used different patterns for React components
→ Resolved: Standardized to Agent 2's pattern (functional components)
→ Re-converted 8 files from Agent 5's output
### Quality Gates
✅ TypeScript compilation: 0 errors, 0 warnings
✅ All existing tests passing (342/342)
✅ Type coverage: 97% (target: 95%)
✅ Linting: 0 issues
❌ 3 files have circular dependencies → Flagged for manual review
- src/models/user.ts ↔ src/models/post.ts
- src/utils/logger.ts ↔ src/config/index.ts
### Performance Validation
✅ Build time: 12.3s (baseline: 11.8s, +4% acceptable)
✅ Bundle size: 2.1MB (baseline: 2.0MB, +5% acceptable)
### Summary
Files converted: 200/200 ✅
Agents used: 7 executors + 1 integrator
Total time: 12 minutes
Issues requiring review: 3 circular dependencies
Estimated time saved vs manual coordination: ~4 hours
---
User Experience
Simple Invocation:
# CLI command
claude-code orchestrate "Migrate entire codebase to TypeScript"
# Or in interactive mode
> Please migrate this entire codebase to TypeScript using agent orchestration
Real-Time Progress Output:
🎯 Task: Migrate entire codebase to TypeScript
📋 Planning phase...
├─ Analyzing codebase: 200 JavaScript files found
├─ Checking dependencies: 15 external, 185 internal
├─ Estimating complexity: High (200 files, deep nesting)
├─ Agents needed: 7 executors + 1 integrator
└─ Strategy: Sequential execution with dependency ordering
✅ Execution plan created (2.3s)
🚀 Execution phase...
├─ Agent 1/7: Converting files 1-30...
│ ├─ Progress: [████████████████████] 30/30 files
│ └─ Status: ✅ Complete (28,450 tokens, handoff triggered)
│
├─ Agent 2/7: Converting files 31-60...
│ ├─ Progress: [████████████████████] 30/30 files
│ └─ Status: ✅ Complete (29,102 tokens, handoff triggered)
│
├─ Agent 3/7: Converting files 61-90...
│ ├─ Progress: [████████████████████] 30/30 files
│ └─ Status: ✅ Complete (27,889 tokens, handoff triggered)
│
├─ Agent 4/7: Converting files 91-120...
│ ├─ Progress: [████████████████████] 30/30 files
│ └─ Status: ✅ Complete (30,234 tokens, handoff triggered)
│
├─ Agent 5/7: Converting files 121-150...
│ ├─ Progress: [████████████████████] 30/30 files
│ └─ Status: ✅ Complete (28,567 tokens, handoff triggered)
│
├─ Agent 6/7: Converting files 151-180...
│ ├─ Progress: [████████████████████] 30/30 files
│ └─ Status: ✅ Complete (29,445 tokens, handoff triggered)
│
└─ Agent 7/7: Converting files 181-200...
├─ Progress: [████████████████████] 20/20 files
└─ Status: ✅ Complete (15,234 tokens, task finished)
🔗 Integration phase...
├─ Collecting results from 7 agents...
├─ Validating consistency... ✅
├─ Checking patterns alignment... ⚠️ 2 conflicts found, resolving...
├─ Running TypeScript compiler... ✅ 0 errors
├─ Running existing tests... ✅ 342/342 passed
├─ Checking type coverage... ✅ 97%
├─ Running linter... ✅ 0 issues
└─ Generating integration report... ✅
✨ Task completed successfully!
📊 Summary:
• Total files migrated: 200/200
• Agents used: 8 (7 executors + 1 integrator)
• Total time: 12 minutes
• Issues found: 3 circular dependencies (see report)
• View detailed report:
.claude/orchestration/migrate-typescript-2024-10-02/report.md
⚠️ Action required:
3 files have circular dependencies that need manual review.
Run: claude-code review
.claude/orchestration/migrate-typescript-2024-10-02/issues.json
User Control Options:
# Start orchestrated task
claude-code orchestrate "large refactoring task"
# Monitor progress of running orchestration
claude-code orchestrate status
# Require approval between phases
claude-code orchestrate --approve-phases
# Limit maximum agents (cost control)
claude-code orchestrate --max-agents 5
# Use parallel execution when possible
claude-code orchestrate --parallel --max-parallel 3
# Resume failed orchestration from last checkpoint
claude-code orchestrate resume --task-id migrate-typescript-2024-10-02
# View orchestration history
claude-code orchestrate list
# Clean up completed orchestration artifacts
claude-code orchestrate cleanup --older-than 7d
Alternative Solutions
Alternative Solutions Considered
We explored several approaches before proposing the full orchestration framework.
Each has significant limitations that make it unsuitable as a complete solution.
---
Alternative 1: Manual Multi-Agent Coordination (Current Approach)
How it works:
- User manually breaks large task into smaller chunks
- Invokes separate agents sequentially via multiple Task tool calls
- Manually copies context/results between agent invocations
- User acts as the "orchestrator" coordinating all handoffs
Example workflow:
# User breaks down task manually
- "Analyze first 30 files and convert to TypeScript"
→ Agent completes, returns results
- "Here's what the previous agent did: [paste results]. Now convert files 31-60"
→ Agent completes, returns results
- "Previous agents used these patterns: [paste]. Convert files 61-90"
→ Agent completes, returns results
# ... repeat 7-10 times ...
- "Review all conversions for consistency"
→ Agent finds conflicts, user must manually resolve
Priority
Critical - Blocking my work
Feature Category
Other
Use Case Example
- Large-Scale Refactoring
Task: Refactor 100+ files to use new architecture pattern
Without orchestration:
- Manual breakdown into chunks
- 10+ separate agent invocations
- Risk of pattern inconsistencies
- 3-4 hours of coordination overhead
With orchestration:
- Single invocation with orchestration
- Automatic work distribution across agents
- Pattern consistency enforced by integrator
- 15 minutes of autonomous execution
- Codebase Migration
Task: Migrate from React class components to hooks (200 components)
Orchestration plan:
- Planning agent: Analyze component dependencies, create conversion order
- Executors 1-6: Convert components in dependency order (30-35 each)
- Executor 7: Update tests to match new patterns
- Integrator: Verify all tests pass, check for prop-drilling issues
- Comprehensive Feature Implementation
Task: Add authentication system across frontend, backend, and database
Orchestration plan:
- Planning agent: Design auth flow, identify all touch points
- Executor 1: Database schema and migrations
- Executor 2: Backend API endpoints and middleware
- Executor 3: Frontend auth components and routing
- Executor 4: Integration tests
- Integrator: End-to-end validation, security audit
- Documentation Generation
Task: Generate API documentation for 50+ endpoints across 10 microservices
Orchestration plan:
- Planning agent: Catalog all endpoints, determine documentation structure
- Executors 1-10: Document endpoints per service (one agent per service)
- Integrator: Create unified navigation, ensure consistent format, generate examples
- Test Suite Creation
Task: Write unit tests for 80+ untested modules (target: 90% coverage)
Orchestration plan:
- Planning agent: Analyze modules, prioritize by complexity/risk
- Executors 1-4: Write tests for assigned modules (20 modules each)
- Integrator: Run coverage report, identify gaps, ensure consistent test patterns
- Security Audit and Remediation
Task: Audit codebase for security vulnerabilities and fix all issues
Orchestration plan:
- Planning agent: Run security scanners, categorize findings
- Executor 1: Fix SQL injection vulnerabilities
- Executor 2: Fix XSS vulnerabilities
- Executor 3: Update dependencies with security patches
- Executor 4: Add input validation across API surface
- Integrator: Re-run security scans, verify all issues resolved
Additional Context
Technical Implementation
- Agent Communication Protocol
Handoff Message Format:
interface AgentHandoff {
taskId: string;
fromAgent: AgentMetadata;
toAgent: AgentMetadata;
reason: 'output_limit' | 'subtask_complete' | 'error_recovery';
context: {
originalTask: string;
executionPlan: Plan;
currentStep: number;
completedSteps: Step[];
};
state: {
completedWork: WorkItem[];
inProgressWork?: {
item: WorkItem;
progress: number; // 0-100
partialState: any;
};
pendingWork: WorkItem[];
};
knowledgeBase: {
decisions: Decision[];
patterns: Pattern[];
issues: Issue[];
};
}
- State Persistence
- Store handoff manifests in .claude/orchestration/{task-id}/
- Each agent writes: agent-{n}-handoff.json
- Planning agent writes: plan.json
- Integrator writes: integration-report.json
- Failure Recovery
If executor agent fails:
- Orchestrator detects failure
- Analyzes partial work completed
- Options:
- Retry with same agent (transient error)
- Re-plan remaining work (persistent error)
- Escalate to user (critical error)
If integrator finds conflicts:
- Attempts automated resolution using patterns
- If unresolvable, presents conflict to user with options
- User chooses resolution strategy
- Re-runs affected executor agents if needed
- Configuration
~/.claude/settings.json:
{
"orchestration": {
"enabled": true,
"maxAgents": 10,
"outputTokenThreshold": 0.8,
"requireApproval": false,
"approvePhases": ["planning", "integration"],
"persistState": true,
"stateDirectory": "~/.claude/orchestration",
"defaultIntegrator": "general-integrator",
"parallelExecution": true,
"maxParallelAgents": 3
}
}
- API Extensions
New Task tool parameters:
{
subagent_type: string;
orchestration_mode?: 'single' | 'orchestrated';
max_agents?: number;
handoff_strategy?: 'sequential' | 'parallel';
integration_required?: boolean;
This issue has 3 comments on GitHub. Read the full discussion on GitHub ↗