Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:29:28 +08:00
commit 87c03319a3
50 changed files with 21409 additions and 0 deletions

View File

@@ -0,0 +1,385 @@
---
skill: task-orchestration
description: Dependency-aware parallel task execution with automatic specialist routing, progress monitoring, and cascading completion. Replaces Task Management Skill with enhanced capabilities.
---
# Task Orchestration Skill
Intelligent task execution management with parallel processing, dependency-aware batching, and automatic specialist coordination.
## When to Use This Skill
**Activate for:**
- "Execute tasks for feature X"
- "What tasks are ready to start?"
- "Launch next batch of tasks"
- "Complete task Y"
- "Monitor parallel execution"
- "Show task progress"
**This skill handles:**
- Dependency-aware task batching
- Parallel specialist launching
- Progress monitoring
- Task completion with summaries
- Dependency cascade triggering
- Specialist routing
## Tools Available
- `query_container` - Read tasks, features, dependencies
- `query_sections` - Read sections with tag filtering (**Token optimized**)
- `manage_container` - Update task status, create tasks
- `query_workflow_state` - Check workflow state, cascade events, dependencies (**NEW**)
- `query_dependencies` - Analyze task dependencies
- `recommend_agent` - Route tasks to specialists
- `manage_sections` - Update task sections
## Section Tag Taxonomy
**When reading task/feature sections, use tag filtering for token efficiency:**
**Actionable Tags** (Implementation Specialist reads from tasks):
- **workflow-instruction** - Step-by-step implementation processes
- **checklist** - Validation checklists, completion criteria
- **commands** - Bash commands to execute
- **guidance** - Implementation patterns and best practices
- **process** - Workflow processes to follow
- **acceptance-criteria** - Definition of done, success conditions
**Contextual Tags** (Planning Specialist reads from features):
- **context** - Business context, user needs, dependencies
- **requirements** - Functional requirements, must-haves, constraints
**Reference Tags** (Read as needed):
- **reference** - Examples, patterns, reference material
- **technical-details** - Deep technical specifications
**Example - Efficient Task Section Reading:**
```javascript
// Implementation Specialist reads only actionable content from task
sections = query_sections(
entityType="TASK",
entityId=taskId,
tags="workflow-instruction,checklist,commands,guidance,process,acceptance-criteria",
includeContent=true
)
// Token cost: ~800-1,500 tokens (vs 3,000-5,000 with all sections)
// Savings: 45-60% token reduction
// Skip contextual sections (already in task description):
// - context (business context)
// - requirements (captured in description field)
```
**Note:** Implementation Specialist subagent automatically uses tag filtering. This reference is for direct tool usage.
## Dependency Cascade Detection (Automatic)
**Recommended Approach:** Use `query_workflow_state` to automatically check for dependency cascades and unblocked tasks.
```javascript
// After task completion, check for cascades
workflowState = query_workflow_state(
containerType="task",
id=taskId
)
// Check for detected cascade events (feature progression)
if (workflowState.detectedEvents.length > 0) {
"✅ Task completion triggered cascade events:
${workflowState.detectedEvents.map(e => e.reason).join(', ')}
Feature status may need to progress. Use Status Progression Skill."
}
// Check for unblocked dependencies (other tasks can now start)
dependencies = query_dependencies(
taskId=taskId,
direction="outgoing",
includeTaskInfo=true
)
// Filter for now-unblocked tasks
for (dep of dependencies) {
if (dep.toTask.status == "blocked" || dep.toTask.status == "pending") {
"✅ Task ${dep.toTask.title} is now unblocked and ready to start!"
}
}
```
**Benefits:**
- Automatic cascade detection based on config
- Dependency-aware unblocking
- Works with custom user workflows
- Handles complex prerequisite checking
## Status Progression Trigger Points (Manual Detection)
**Legacy Pattern:** Manual detection is still available but `query_workflow_state` is preferred.
**CRITICAL:** Never directly change task status. Always use Status Progression Skill for ALL status changes.
These are universal events that trigger status progression checks, regardless of the user's configured status flow:
| Event | When to Check | Detection Pattern | Condition | Action |
|-------|---------------|-------------------|-----------|--------|
| **work_started** | Specialist begins task implementation | Before specialist starts work | Task is in backlog/pending | Use Status Progression Skill to move to in-progress |
| **implementation_complete** | Code + tests written, sections updated | After specialist finishes coding | Summary populated (300-500 chars), sections updated | Use Status Progression Skill to move to next validation status |
| **tests_running** | Test execution begins | After triggering tests | Tests initiated | Use Status Progression Skill if needed |
| **tests_passed** | All tests successful | After test execution | `testResults.allPassed == true` | Use Status Progression Skill to move toward completion |
| **tests_failed** | Any tests failed | After test execution | `testResults.anyFailed == true` | Use Status Progression Skill (may move backward to in-progress) |
| **review_submitted** | Code submitted for review | After implementation complete | Code ready for review | Use Status Progression Skill to move to in-review |
| **review_approved** | Code review passed | After reviewer approval | Review completed with approval | Use Status Progression Skill to move forward (testing or completion) |
| **changes_requested** | Review rejected, needs rework | After reviewer rejection | Changes needed | Use Status Progression Skill (move backward to in-progress) |
| **blocker_detected** | Cannot proceed with work | When specialist encounters issue | External dependency or technical blocker | Use Status Progression Skill to move to blocked status |
| **task_cancelled** | Work no longer needed | User decides to cancel | Scope change | Use Status Progression Skill to move to cancelled |
### Detection Example: Implementation Complete
```javascript
// After specialist finishes code + tests
task = query_container(operation="get", containerType="task", id=taskId)
// Check implementation is complete
sectionsUpdated = true // Specialist updated Implementation Details section
filesChanged = true // Specialist created Files Changed section
summaryLength = task.summary?.length || 0
if (sectionsUpdated && filesChanged && summaryLength >= 300 && summaryLength <= 500) {
// EVENT DETECTED: implementation_complete
// Delegate to Status Progression Skill
"Use Status Progression Skill to progress task status.
Context: Implementation complete, summary populated (${summaryLength} chars)."
// Status Progression Skill will:
// 1. Call get_next_status(taskId, event="implementation_complete")
// 2. get_next_status reads user's config.yaml
// 3. Determines active flow based on task tags
// 4. Recommends next status based on that flow
// 5. Validates prerequisites
// 6. Returns recommendation
// Possible outcomes based on user's config:
// - default_flow: in-progress → testing
// - with_review: in-progress → in-review (code review first)
// - documentation_flow: in-progress → in-review (no testing for docs)
// - hotfix_flow: in-progress → completed (skip validation)
// - bug_fix_flow: in-progress → testing
}
```
### Detection Example: Task Completion (Cascade Check)
```javascript
// After marking task complete, check for dependency cascade
completedTask = query_container(operation="get", containerType="task", id=taskId)
// Check if this unblocks other tasks
outgoingDeps = query_dependencies(
taskId=taskId,
direction="outgoing",
includeTaskInfo=true
)
if (outgoingDeps.dependencies.length > 0) {
// This task blocks other tasks
// Check each dependent task to see if now unblocked
for (dep of outgoingDeps.dependencies) {
dependentTask = dep.toTask
// Check all incoming dependencies for the dependent task
incomingDeps = query_dependencies(
taskId=dependentTask.id,
direction="incoming",
includeTaskInfo=true
)
// Count incomplete blockers
incompleteBlockers = incomingDeps.dependencies.filter(d =>
d.fromTask.status != "completed" && d.fromTask.status != "cancelled"
).length
if (incompleteBlockers == 0) {
// This task is now unblocked!
notify(`Task "${dependentTask.title}" is now unblocked and ready to start.`)
// Feature Orchestration Skill can now launch specialist for this task
}
}
}
// Also check if feature can progress (see Feature Orchestration Skill)
if (completedTask.featureId) {
// Trigger Feature Orchestration Skill to check feature progress
// (see Feature Orchestration Skill event: all_tasks_complete)
}
```
## Specialist Architecture (v2.0)
**Implementation Specialist (Haiku)** - Standard implementation (70-80% of tasks)
- Fast execution, cost-effective
- Loads domain Skills on-demand: backend-implementation, frontend-implementation, database-implementation, testing-implementation, documentation-implementation
- Escalates to Senior Engineer when blocked
**Senior Engineer (Sonnet)** - Complex problem solving (10-20%)
- Debugging, bug investigation, unblocking
- Performance optimization, tactical architecture
**Feature Architect (Opus)** - Feature design from ambiguous requirements
**Planning Specialist (Sonnet)** - Task decomposition with execution graphs
## Pre-Execution Checklist
**CRITICAL: Before launching specialists, ALWAYS check parent feature status.**
When starting task execution (Phase 3 of feature development):
1. **Check parent feature status:**
```javascript
feature = query_container(operation="get", containerType="feature", id=featureId)
if (feature.status == "planning" || feature.status == "draft") {
// Feature status doesn't reflect execution phase
// Delegate to Feature Orchestration Skill or Status Progression Skill
"⚠️ Feature is still in ${feature.status}.
Use Status Progression Skill to progress feature status before launching specialists.
Cascade Event: tasks_ready_to_execute
The skill will use get_next_status to determine the appropriate next status based on workflow config.
Why: Feature status must reflect current development phase (not hardcoded - config determines next status)."
// STOP - Don't proceed with specialist launches until feature status updated
return
}
```
2. **Identify ready tasks** (no blocking dependencies)
3. **Create execution batches** (parallel groups)
4. **Then proceed with specialist launches**
**Why this matters:**
- Feature status should accurately reflect the current development phase
- Cascade event system determines appropriate next status (config-driven)
- Missing this step causes feature to jump directly to completion, skipping execution phase statuses
- Different workflows may use different status names (default: "in-development", but config controls this)
**When to check:**
- At the start of Phase 3 (task execution)
- Before launching the first batch of specialists
- When resuming paused work
## Core Workflows
### 1. Dependency-Aware Batching
**High-level steps:**
1. Get all pending tasks: `query_container(operation="search", containerType="task", featureId="...", status="pending")`
2. For each task, check dependencies: `query_dependencies(taskId="...", direction="incoming", includeTaskInfo=true)`
3. Group into batches:
- Batch 1: Tasks with NO incomplete blocking dependencies (parallel)
- Batch 2: Tasks blocked only by Batch 1 (sequential)
- Batch 3+: Continue until all tasks assigned
4. Detect circular dependencies (task blocked by another task that's also blocked)
See [examples.md](examples.md) for detailed batching examples and output format.
### 2. Parallel Specialist Launch
**High-level steps:**
1. For each task in parallel batch: `recommend_agent(taskId="...")`
2. Prepare launch instructions for orchestrator
3. Orchestrator launches specialists in parallel (using Task tool)
**Key:** Skill identifies WHICH specialists to launch; orchestrator does the actual launching.
See [examples.md](examples.md) for orchestrator instruction format.
### 3. Progress Monitoring
**High-level steps:**
1. Keep list of task IDs currently being worked on
2. Check each task status: `query_container(operation="overview", containerType="task", id="...")`
3. Analyze status distribution (completed, in-progress, blocked, pending)
4. Determine if batch complete
5. Report progress: "Batch X: Y/Z tasks complete (N%)"
### 4. Dependency Cascade
**High-level steps:**
1. After task completes, check if it unblocks others: `query_dependencies(taskId="...", direction="outgoing", includeTaskInfo=true)`
2. For each dependent task, check if ALL blockers complete
3. Report newly available tasks
4. Recommend launching next batch
See [examples.md](examples.md) for cascade detection pattern.
### 5. Specialist Routing
**High-level steps:**
1. Get recommendation: `recommend_agent(taskId="...")`
2. Use recommendation if provided
3. If no recommendation, use fallback (Implementation Specialist or ask user)
**Routing patterns:**
- [backend, frontend, database, testing, documentation] → Implementation Specialist (Haiku)
- [bug, error, blocker, complex] → Senior Engineer (Sonnet)
- [feature-creation] → Feature Architect (Opus)
- [planning, task-breakdown] → Planning Specialist (Sonnet)
### 6. Task Completion
**High-level steps:**
1. Create task summary section (300-500 chars)
2. Create files changed section
3. Use Status Progression Skill to mark complete (validates prerequisites)
4. Check for cascade (trigger next batch if available)
**Note:** Specialists typically mark their own tasks complete. This is for orchestrator-driven completion.
## Integration with Other Skills
**Works alongside:**
- **Feature Orchestration Skill** - Receives task execution requests
- **Dependency Orchestration Skill** - For complex dependency analysis
- **Status Progression Skill** - For ALL status changes
**Launches subagents:**
- All specialist subagents based on recommend_agent results
## Token Efficiency
- Use `overview` operations for batch status checks (95% token reduction)
- Batch specialist launches in single message
- Return minimal progress reports
- Query only necessary dependency information
**Savings:** Overview batch (1.2k tokens) vs Get each task fully (28k tokens for 10 tasks)
## Best Practices
1. **Always analyze dependencies** before execution
2. **Use recommend_agent** for all routing (never guess)
3. **Monitor parallel progress** actively
4. **Handle failures gracefully** without cascade
5. **Trigger cascades automatically** when batch completes
6. **Report clear progress** to users
7. **Maximum 3-5 parallel tasks** for manageable monitoring
## Success Metrics
- 40% reduction in feature completion time with parallelism
- 95% successful specialist routing on first attempt
- Zero circular dependencies in production
- Automated cascade triggering (no manual intervention)
- 500-900 token average per orchestration session
## Additional Resources
- **Detailed Examples**: See [examples.md](examples.md) for complete walkthroughs
- **Execution Patterns**: See [patterns.md](patterns.md) for strategies, configuration, and error handling

View File

@@ -0,0 +1,631 @@
# Task Orchestration Skill - Examples
## Example 1: Execute Feature Tasks with Parallel Batching
**User Request:**
> "Execute tasks for authentication feature"
**Scenario:**
- 5 tasks total
- Dependencies: Database → Backend → Tests
- UI has no dependencies
**Actions:**
1. Get all pending tasks
2. Query dependencies for each
3. Create execution batches
**Batch Analysis:**
```
Batch 1 (Parallel):
├─ T1: Create database schema (no dependencies)
└─ T3: Create UI components (no dependencies)
Can run simultaneously
Batch 2 (Sequential):
└─ T2: Implement API (depends on T1)
Must wait for database
Batch 3 (Parallel):
├─ T4: Unit tests (depends on T2)
└─ T5: Documentation (depends on T2)
Can run simultaneously after API
```
**Output:**
```
Execution Plan Created: 3 batches, 40% time saved
Batch 1 - Ready to Launch (Parallel):
1. Database Engineer → Create database schema
2. Frontend Developer → Create UI components
Launch these 2 specialists in parallel now?
Next batch will launch automatically when Batch 1 completes.
```
---
## Example 2: Launch Parallel Batch
**User Request:**
> "Launch next task batch"
**Actions:**
1. Get next ready batch (Batch 1)
2. For each task, recommend specialist
3. Prepare parallel launch instructions
**Output:**
```
Launching Batch 1 in PARALLEL:
Specialist 1: Database Engineer
Task: Create database schema (T1)
Complexity: 5
Tags: database, schema, migration
Specialist 2: Frontend Developer
Task: Create UI components (T3)
Complexity: 6
Tags: frontend, ui, react
Both specialists launching now...
Monitor progress with: "show task progress"
```
---
## Example 3: Monitor Parallel Execution
**User Request:**
> "Show task progress"
**Actions:**
1. Get current batch tasks
2. Check status of each task
3. Calculate completion percentage
**Output:**
```
Batch 1 Progress: 1/2 (50%)
✓ Create database schema (T1)
Status: completed
Specialist: Database Engineer
Duration: 25 minutes
⏳ Create UI components (T3)
Status: in-progress (80% done)
Specialist: Frontend Developer
Est. completion: 5 minutes
Batch 2 is queued and will launch automatically when T3 completes.
```
---
## Example 4: Dependency Cascade Triggering
**User Request:**
> "Task T1 is complete"
**Actions:**
1. Mark T1 as completed
2. Check if batch complete
3. Batch not complete (T3 still running)
4. Wait for T3
**5 minutes later, T3 completes:**
**Actions:**
1. Mark T3 as completed
2. Check if batch complete: Yes
3. Get next batch (Batch 2)
4. Check dependencies satisfied: Yes
5. Trigger cascade
**Output:**
```
✓ Batch 1 Complete (2/2 tasks)
• Database schema ✓
• UI components ✓
Triggering Batch 2:
Specialist: Backend Engineer
Task: Implement API endpoints (T2)
Complexity: 7
Dependencies: T1 (satisfied)
Launching specialist now...
```
---
## Example 5: Task Completion with Summary
**User Request:**
> "Complete API implementation task"
**Actions:**
1. Specialist reports work complete
2. Create summary section
3. Create files changed section
4. Mark task completed
5. Check for cascade
**Output:**
```
✓ Task Completed: Implement API endpoints
Summary:
Implemented REST API with 5 endpoints:
- POST /auth/register
- POST /auth/login
- POST /auth/logout
- POST /auth/refresh
- GET /auth/status
Includes JWT token handling, validation, and error responses.
Test coverage: 85%
Files Changed:
- src/api/auth.controller.ts (new)
- src/api/auth.service.ts (new)
- src/api/auth.dto.ts (new)
- tests/api/auth.test.ts (new)
Cascade: Batch 2 complete. Launching Batch 3 (2 parallel tasks)...
```
---
## Example 6: Specialist Routing with Fallback
**User Request:**
> "Execute task: Optimize performance"
**Scenario:**
- Task has no domain-specific tags
- recommend_agent returns no match
**Actions:**
1. recommend_agent(task_id) → no match
2. Check config: fallback_behavior = "use_default"
3. Use default_specialist: "Backend Engineer"
**Output:**
```
Task: Optimize performance
Tags: optimization, performance (no domain match)
No specialist matched by tags.
Using fallback: Backend Engineer (default)
Launching Backend Engineer for this task.
Note: Consider adding more specific tags:
- For DB: database, query-optimization
- For frontend: frontend, ui-performance
- For backend: backend, api-optimization
```
---
## Example 7: Handle Blocked Task
**User Request:**
> "Why won't task T5 start?"
**Actions:**
1. Check task dependencies
2. Find incomplete blockers
3. Report blocking tasks
**Output:**
```
Task T5 (Integration tests) is BLOCKED
Blocked by 2 incomplete dependencies:
1. T2: Implement API endpoints
Status: in-progress (60% complete)
Est. completion: 20 minutes
2. T3: Create UI components
Status: pending (not started)
Blocker: Waiting for batch slot
Resolution:
- T2 is actively being worked on
- T3 will start when slot available
- T5 will automatically unblock when both complete
Estimated unblock: 30 minutes
```
---
## Example 8: Circular Dependency Detection
**User Request:**
> "Execute feature tasks"
**Actions:**
1. Build dependency graph
2. Detect circular dependency
3. Cannot create batches
**Output:**
```
✗ Error: Circular Dependencies Detected
Cycle found:
T2 → T5 → T7 → T2
Tasks involved:
- T2: Implement API
- T5: Add caching layer
- T7: Update API for cache
Resolution options:
1. Remove T7 → T2 dependency (likely unnecessary)
2. Split T2 into two tasks (API-v1, API-v2)
3. Reorder: Complete T2 before T5
Use Dependency Orchestration Skill for detailed analysis.
```
---
## Example 9: Resource-Limited Parallel Execution
**Configuration:**
```yaml
parallelism:
max_parallel_tasks: 3
```
**Scenario:**
- Batch 1 has 5 parallelizable tasks
- Must respect limit of 3
**Actions:**
1. Split batch into sub-batches
2. Launch first 3 tasks
3. Queue remaining 2 tasks
**Output:**
```
Batch 1 split into sub-batches (max_parallel_tasks: 3)
Sub-batch 1a (launching now):
├─ T1: Database schema
├─ T2: Email service
└─ T3: UI components
Sub-batch 1b (queued):
├─ T4: Notification service
└─ T5: File upload service
Sub-batch 1b will launch when any task from 1a completes.
```
---
## Example 10: All Tasks Complete - Feature Ready
**User Request:**
> "Check task status"
**Actions:**
1. Monitor last batch
2. All batches complete
3. Notify feature ready
**Output:**
```
✓ All Task Batches Complete
Feature: Authentication System
Tasks completed: 5/5
Batch Summary:
- Batch 1: 2 tasks (parallel) - 25 min
- Batch 2: 1 task (sequential) - 30 min
- Batch 3: 2 tasks (parallel) - 15 min
Total time: 70 minutes
Time saved: 40% (vs 120 min sequential)
Feature Status: All tasks complete
Next: Use Feature Orchestration Skill to:
- Trigger testing
- Validate quality gates
- Mark feature complete
```
---
## Integration Patterns
### Pattern 1: Full Automated Workflow
```
1. Feature Orchestration: Creates feature + tasks
2. Task Orchestration: Creates execution batches
3. Task Orchestration: Launches Batch 1 (parallel)
4. Specialists: Complete tasks, return summaries
5. Task Orchestration: Auto-cascades to Batch 2
6. Repeat until all batches complete
7. Feature Orchestration: Validates and completes
```
### Pattern 2: Manual Batch Control
```yaml
# Configuration
parallelism:
auto_launch: false # Suggest only, don't launch
```
```
1. Task Orchestration: Analyzes and suggests batches
2. User: Reviews and approves
3. User: "Launch batch 1"
4. Task Orchestration: Launches approved batch
5. Repeat for each batch
```
### Pattern 3: With Dependency Analysis
```
1. User: "This feature has complex dependencies"
2. Dependency Orchestration: Analyzes graph
3. Dependency Orchestration: Finds bottlenecks
4. Task Orchestration: Uses analysis for batching
5. Task Orchestration: Prioritizes critical path
```
---
## Token Efficiency Examples
### Efficient Batch Status Check
```javascript
// Check batch without full task details
tasks_overview = query_container(
operation="search",
containerType="task",
featureId="uuid",
status="in-progress"
)
// Returns: ~400 tokens (ID, title, status only)
```
### Batch Launch Instructions
```javascript
// Minimal specialist context
"Launch Backend Engineer for task T2 (uuid-2)"
// Specialist reads full context themselves
// Total: ~50 tokens to orchestrator
```
**vs Old Pattern (Feature/Task Managers):**
```javascript
// Pass full task context to manager
"Here's the complete task with all sections..."
// Then manager passes to specialist
// Total: ~2,900 tokens
```
**Savings: 98% token reduction in routing**
---
## Detailed Batching Example with Output Format
**Given 4 tasks with dependencies:**
- T1 (Database Schema) - no dependencies
- T2 (API Implementation) - depends on T1
- T3 (UI Components) - no dependencies
- T4 (Integration Tests) - depends on T2 and T3
**Batching Result:**
- Batch 1: T1, T3 (parallel - no dependencies)
- Batch 2: T2 (sequential - depends on T1)
- Batch 3: T4 (sequential - depends on T2, T3)
**JSON Output Format:**
```json
{
"batches": [
{
"batch_number": 1,
"parallel": true,
"task_count": 2,
"tasks": [
{
"id": "uuid-1",
"title": "Create database schema",
"complexity": 5,
"specialist": "Implementation Specialist",
"skills_loaded": ["database-implementation"],
"dependencies": []
},
{
"id": "uuid-3",
"title": "Create UI components",
"complexity": 6,
"specialist": "Implementation Specialist",
"skills_loaded": ["frontend-implementation"],
"dependencies": []
}
]
},
{
"batch_number": 2,
"parallel": false,
"task_count": 1,
"tasks": [
{
"id": "uuid-2",
"title": "Implement API endpoints",
"complexity": 7,
"specialist": "Implementation Specialist",
"skills_loaded": ["backend-implementation"],
"dependencies": ["uuid-1"]
}
]
}
],
"total_batches": 2,
"estimated_time_savings": "40%"
}
```
---
## Orchestrator Launch Instruction Format
**For parallel batch launch:**
```markdown
Launch the following specialists in PARALLEL (Batch 1):
1. **Implementation Specialist (Haiku)**
- Task: Create database schema (uuid-1)
- Complexity: 5
- Skills: database-implementation
2. **Implementation Specialist (Haiku)**
- Task: Create UI components (uuid-3)
- Complexity: 6
- Skills: frontend-implementation
Wait for both to complete before proceeding to Batch 2.
```
**Key:** Orchestrator launches specialists using Task tool, not the skill itself.
---
## Parallel Execution Patterns
### Pattern 1: Domain Isolation
```
Database tasks → Backend tasks
Frontend tasks ↗
```
**Analysis:** Database and Frontend can run parallel (different domains, no shared dependencies).
### Pattern 2: Layer Separation
```
Data Layer → Business Logic → Presentation Layer
```
**Analysis:** Must be sequential (dependencies between layers).
### Pattern 3: Feature Isolation
```
Auth module → Integration
Reporting module ↗
```
**Analysis:** Independent modules can run parallel, integrate at the end.
### Pattern 4: Test Parallelism
```
Unit tests (parallel)
Integration tests (parallel)
E2E tests (sequential after all)
```
**Analysis:** Test types can often run concurrently, E2E waits for all code complete.
---
## Cascade Detection Pattern
**After task completes:**
```javascript
// Step 1: Get completed task
completedTask = query_container(operation="get", containerType="task", id=taskId)
// Step 2: Check if this task blocks other tasks
outgoingDeps = query_dependencies(
taskId=taskId,
direction="outgoing",
includeTaskInfo=true
)
if (outgoingDeps.dependencies.length > 0) {
// Step 3: Check each dependent task to see if now unblocked
for (dep of outgoingDeps.dependencies) {
dependentTask = dep.toTask
// Step 4: Check ALL incoming dependencies for the dependent task
incomingDeps = query_dependencies(
taskId=dependentTask.id,
direction="incoming",
includeTaskInfo=true
)
// Step 5: Count incomplete blockers
incompleteBlockers = incomingDeps.dependencies.filter(d =>
d.fromTask.status != "completed" && d.fromTask.status != "cancelled"
).length
// Step 6: If no incomplete blockers, task is unblocked!
if (incompleteBlockers == 0) {
notify(`Task "${dependentTask.title}" is now unblocked and ready to start.`)
}
}
}
// Step 7: Check if feature can progress
if (completedTask.featureId) {
// Trigger Feature Orchestration Skill to check feature progress
}
```
---
## Event Detection Examples
### Detection: Implementation Complete
```javascript
// After specialist finishes code + tests
task = query_container(operation="get", containerType="task", id=taskId)
// Check implementation is complete
sectionsUpdated = true // Specialist updated Implementation Details section
filesChanged = true // Specialist created Files Changed section
summaryLength = task.summary?.length || 0
if (sectionsUpdated && filesChanged && summaryLength >= 300 && summaryLength <= 500) {
// EVENT DETECTED: implementation_complete
"Use Status Progression Skill to progress task status.
Context: Implementation complete, summary populated (${summaryLength} chars)."
// Status Progression Skill determines next status based on config:
// - default_flow: in-progress → testing
// - with_review: in-progress → in-review
// - documentation_flow: in-progress → in-review (no testing)
// - hotfix_flow: in-progress → completed (skip validation)
}
```
### Detection: Task Completion (Cascade Check)
```javascript
// After marking task complete, check for dependency cascade
completedTask = query_container(operation="get", containerType="task", id=taskId)
// Check if this unblocks other tasks (see Cascade Detection Pattern above)
// Also check if feature can progress
if (completedTask.featureId) {
// Trigger Feature Orchestration Skill to check all_tasks_complete event
}
```

View File

@@ -0,0 +1,652 @@
# Task Orchestration - Execution Patterns
Comprehensive guide to execution strategies, configuration patterns, and error handling.
## Execution Strategies
### Strategy 1: Sequential Execution
**When to use:**
- All tasks have dependencies on previous tasks
- No parallelization opportunities
- Linear workflow required
**Pattern:**
```
T1 → T2 → T3 → T4
```
**Implementation:**
```javascript
// Launch one task at a time
for (task of tasks) {
recommendedAgent = recommend_agent(taskId=task.id)
launchSpecialist(recommendedAgent)
waitForCompletion()
}
```
**Time:** Total = sum of all task durations
**Use case:** Data pipeline, migration scripts, deployment steps
---
### Strategy 2: Full Parallel Execution
**When to use:**
- No dependencies between tasks
- Independent work streams
- Maximum speed required
**Pattern:**
```
T1
T2
T3
T4
```
**Implementation:**
```javascript
// Launch all tasks simultaneously (respecting max_parallel_tasks)
allTasks = query_container(operation="search", containerType="task", featureId="...", status="pending")
for (task of allTasks) {
recommendedAgent = recommend_agent(taskId=task.id)
launchSpecialistAsync(recommendedAgent) // Don't wait
}
// Monitor all in parallel
monitorParallelExecution(allTasks)
```
**Time:** Total = longest task duration
**Savings:** Up to 75% if all tasks equal duration
**Use case:** Independent features, test suites, documentation tasks
---
### Strategy 3: Hybrid Batched Execution
**When to use:**
- Mix of dependencies and parallel opportunities
- Most common real-world scenario
- Optimize for both speed and correctness
**Pattern:**
```
Batch 1: T1, T3 (parallel)
Batch 2: T2 (depends on T1)
Batch 3: T4 (depends on T2, T3)
```
**Implementation:**
```javascript
// Step 1: Build dependency graph
batches = createExecutionBatches(featureId)
// Step 2: Execute batch by batch
for (batch of batches) {
if (batch.parallel) {
// Launch all tasks in batch simultaneously
for (task of batch.tasks) {
launchSpecialistAsync(task)
}
waitForBatchComplete(batch)
} else {
// Launch tasks sequentially within batch
for (task of batch.tasks) {
launchSpecialist(task)
waitForCompletion()
}
}
}
```
**Time:** Total = sum of batch durations (batches run sequentially, tasks within batch run in parallel)
**Savings:** 30-50% typical for standard features
**Use case:** Standard feature development (database → backend → frontend → tests)
---
### Strategy 4: Resource-Aware Execution
**When to use:**
- Configuration specifies resource limits
- System constraints (memory, API limits)
- Controlled parallelism required
**Pattern:**
```
max_parallel_tasks: 3
Batch 1a: T1, T2, T3 (parallel)
Batch 1b: T4, T5 (wait for slot)
```
**Implementation:**
```javascript
// Step 1: Get resource limit from config
maxParallel = 3 // From .taskorchestrator/config.yaml
// Step 2: Split large batches
batch = batches[0] // Has 5 parallelizable tasks
if (batch.tasks.length > maxParallel) {
// Split into sub-batches
subBatch1 = batch.tasks.slice(0, maxParallel) // T1, T2, T3
subBatch2 = batch.tasks.slice(maxParallel) // T4, T5
// Launch first sub-batch
for (task of subBatch1) {
launchSpecialistAsync(task)
}
// Queue remaining tasks
queuedTasks = subBatch2
}
// Step 3: Fill slots as tasks complete
onTaskComplete = (completedTaskId) => {
if (queuedTasks.length > 0) {
nextTask = queuedTasks.shift()
launchSpecialist(nextTask)
}
}
```
**Time:** Total = (total tasks / max_parallel) × average task duration
**Use case:** Resource-constrained environments, rate-limited APIs, memory-intensive tasks
---
## Configuration Guidance
**Note:** Configuration patterns are documented here for AI reference. Configuration is NOT dynamically loaded via MCP tools.
### Parallelism Strategy
**Default recommended settings:**
```yaml
# .taskorchestrator/config.yaml (documented pattern)
parallelism:
max_parallel_tasks: 5 # Maximum concurrent tasks
auto_launch: true # Auto-cascade to next batch
respect_dependencies: true # Always check dependencies (CRITICAL)
```
**Best practices:**
- **max_parallel_tasks**: 3-5 for most projects (manageable monitoring)
- **auto_launch**: `true` for automation, `false` for manual control
- **respect_dependencies**: ALWAYS `true` (prevents blocking issues)
### Specialist Routing
**Routing rules (from agent-mapping.yaml pattern):**
```yaml
# Tags → Specialist mapping
backend: Implementation Specialist (Haiku)
frontend: Implementation Specialist (Haiku)
database: Implementation Specialist (Haiku)
testing: Implementation Specialist (Haiku)
documentation: Implementation Specialist (Haiku)
bug: Senior Engineer (Sonnet)
error: Senior Engineer (Sonnet)
blocker: Senior Engineer (Sonnet)
complex: Senior Engineer (Sonnet)
feature-creation: Feature Architect (Opus)
planning: Planning Specialist (Sonnet)
task-breakdown: Planning Specialist (Sonnet)
```
**Routing algorithm:**
1. Call `recommend_agent(taskId)`
2. If recommendation provided → use it
3. If no recommendation:
- Check fallback_behavior in config
- If `ask_user` → prompt user for specialist choice
- If `use_default` → use default_specialist (Implementation Specialist Haiku)
4. **Never guess** or hardcode specialist assignments
**Fallback configuration pattern:**
```yaml
specialist_routing:
fallback_behavior: "use_default" # or "ask_user"
default_specialist: "Implementation Specialist"
```
### Quality Gates (Optional)
**Hook-based validation pattern:**
```yaml
quality_gates:
enabled: false # Disable until hooks implemented
task_gates:
testing:
hook: "run_tests"
required: true
completion:
hook: "validate_summary"
required: false # Warning only
```
**Behavior:**
- `required: true` → Blocks status transition if gate fails
- `required: false` → Shows warning but allows progression
**Use case:** CI/CD integration, automated testing, code coverage checks
---
## Error Handling
### Error 1: Task Blocked During Execution
**Symptom:**
Task status changes to "blocked" mid-execution
**Detection:**
```javascript
// Monitor task status
task = query_container(operation="get", containerType="task", id=taskId)
if (task.status == "blocked") {
// Specialist encountered blocker
}
```
**Actions:**
1. Notify orchestrator: "Task T2 blocked - waiting for external API access"
2. Suggest unblocking actions based on blocker type:
- External dependency → "Contact team X for access"
- Technical issue → "Launch Senior Engineer to investigate"
- Missing information → "Clarify requirements with stakeholder"
3. Do NOT cascade to next batch
4. Report blocker in batch progress: "Batch 2: 0/1 (blocked)"
**Resolution:**
```javascript
// After blocker resolved
"Use Status Progression Skill to unblock task and resume work"
```
---
### Error 2: Specialist Fails Task
**Symptom:**
Task marked as failed by specialist
**Detection:**
```javascript
task = query_container(operation="get", containerType="task", id=taskId)
if (task.status == "failed") {
// Specialist could not complete task
}
```
**Actions:**
1. Report failure to user: "Task T3 failed - specialist encountered errors"
2. Analyze failure reason (from task sections/specialist report)
3. Suggest remediation:
- Code errors → "Fix issues and retry task"
- Test failures → "Address failing tests"
- Blocker → "Resolve external dependency"
4. **Do NOT cascade** to next batch (prevents cascading failures)
5. Pause feature execution until issue resolved
**Resolution:**
```javascript
// After fixing issues
"Use Status Progression Skill to reset task to pending and retry"
```
---
### Error 3: Max Parallel Limit Reached
**Symptom:**
Trying to launch more tasks than max_parallel_tasks allows
**Detection:**
```javascript
inProgressTasks = query_container(
operation="search",
containerType="task",
status="in-progress"
)
if (inProgressTasks.length >= maxParallelTasks) {
// At capacity
}
```
**Actions:**
1. Queue remaining tasks: "5 tasks in progress (max). Queueing 2 additional tasks."
2. Wait for slot to open
3. When task completes, automatically launch next queued task
4. Report queued tasks to user: "Sub-batch 1b queued (2 tasks waiting for slots)"
**Implementation:**
```javascript
// Maintain queue
queuedTasks = []
onTaskComplete = (completedTaskId) => {
if (queuedTasks.length > 0) {
nextTask = queuedTasks.shift()
launchSpecialist(nextTask)
notify(`Launched queued task: ${nextTask.title}`)
}
}
```
---
### Error 4: No Specialist Matched
**Symptom:**
recommend_agent returns no recommendation
**Detection:**
```javascript
recommendation = recommend_agent(taskId=taskId)
if (!recommendation.recommended) {
// No specialist matched by tags
}
```
**Actions:**
1. Check fallback_behavior from config (documented pattern, not dynamically loaded)
2. If `ask_user`:
```
Task: Optimize performance
Tags: optimization, performance (no domain match)
No specialist matched by tags.
Which specialist should handle this task?
1. Backend Engineer
2. Frontend Developer
3. Senior Engineer (complex)
```
3. If `use_default`:
```
No specialist matched.
Using fallback: Implementation Specialist (default)
Note: Consider adding more specific tags:
- For DB: database, query-optimization
- For frontend: frontend, ui-performance
- For backend: backend, api-optimization
```
**Prevention:**
- Improve task tagging during creation
- Update agent-mapping.yaml with missing patterns
- Add domain-specific tags (backend, frontend, database, etc.)
---
### Error 5: Circular Dependency Detected
**Symptom:**
Cannot create execution batches due to circular dependency
**Detection:**
```javascript
batches = createExecutionBatches(featureId)
if (batches.error == "circular_dependency") {
// T2 → T5 → T7 → T2
}
```
**Actions:**
1. Report circular dependency to user:
```
✗ Error: Circular Dependencies Detected
Cycle found:
T2 (Implement API) → T5 (Add caching) → T7 (Update API) → T2
Resolution options:
1. Remove T7 → T2 dependency (likely unnecessary)
2. Split T2 into two tasks (API-v1, API-v2)
3. Reorder: Complete T2 before T5
```
2. Suggest using Dependency Orchestration Skill for detailed analysis:
```
Use Dependency Orchestration Skill to:
- Visualize dependency graph
- Identify critical path
- Suggest dependency removals
```
3. **Do NOT proceed** with execution until resolved
**Resolution:**
User must manually resolve circular dependency by removing or reordering dependencies.
---
### Error 6: Batch Timeout
**Symptom:**
Batch taking longer than expected
**Detection:**
```javascript
batchStartTime = Date.now()
expectedDuration = batch.estimatedDuration
checkInterval = setInterval(() => {
elapsed = Date.now() - batchStartTime
if (elapsed > expectedDuration * 1.5) { // 50% overtime
// Batch running long
}
}, 60000) // Check every minute
```
**Actions:**
1. Report delay to user: "Batch 2 running 50% over estimated time (45 min vs 30 min)"
2. Check task statuses for issues:
```javascript
for (task of batch.tasks) {
taskStatus = query_container(operation="get", containerType="task", id=task.id)
if (taskStatus.status == "blocked") {
report(`Task ${task.title} is blocked`)
}
}
```
3. Suggest user intervention if needed
4. Continue monitoring until batch completes or user intervenes
**Not an error if:**
- Complex task legitimately taking longer
- Specialist working through issues
- All tasks still in-progress (not blocked/failed)
---
## Token Efficiency Patterns
### Pattern 1: Batch Status Checks
**Inefficient:**
```javascript
// Get full task details for each task
for (task of batchTasks) {
fullTask = query_container(
operation="get",
containerType="task",
id=task.id,
includeSections=true // 2,800 tokens per task
)
}
// Total: 2,800 × 10 tasks = 28,000 tokens
```
**Efficient:**
```javascript
// Get minimal task overview for batch
tasks = query_container(
operation="search",
containerType="task",
featureId=featureId,
status="in-progress"
)
// Total: ~1,200 tokens for all 10 tasks (95% savings)
```
---
### Pattern 2: Specialist Launch Instructions
**Inefficient:**
```javascript
// Pass full task context to orchestrator
fullTask = query_container(
operation="get",
containerType="task",
id=taskId,
includeSections=true
)
"Launch Backend Engineer with this task: [full task JSON]"
// Total: ~2,900 tokens
```
**Efficient:**
```javascript
// Minimal specialist reference
recommendation = recommend_agent(taskId=taskId)
"Launch ${recommendation.agent} for task ${taskId}"
// Specialist reads full context themselves
// Total: ~50 tokens (98% savings)
```
---
### Pattern 3: Progress Reporting
**Inefficient:**
```javascript
// Return full batch details
return {
batch: fullBatchData,
tasks: allTaskDetails,
progress: calculations
}
// Total: ~3,500 tokens
```
**Efficient:**
```javascript
// Minimal progress summary
return "Batch 1: 3/5 tasks complete (60%)"
// Total: ~20 tokens (99% savings)
```
---
## Best Practices Summary
### 1. Dependency Management
- ✅ **Always** check dependencies before launching tasks
- ✅ Use `query_dependencies` with `includeTaskInfo=true`
- ✅ Validate no circular dependencies before batching
- ❌ **Never** launch tasks without dependency analysis
### 2. Specialist Routing
- ✅ **Always** use `recommend_agent` tool
- ✅ Respect recommendation if provided
- ✅ Use documented fallback behavior if no match
- ❌ **Never** guess or hardcode specialist assignments
### 3. Resource Management
- ✅ Respect `max_parallel_tasks` configuration
- ✅ Queue tasks when at capacity
- ✅ Monitor resource usage during execution
- ❌ **Never** exceed parallelism limits
### 4. Progress Monitoring
- ✅ Check task status regularly during execution
- ✅ Report progress to user proactively
- ✅ Detect blockers and failures early
- ❌ **Never** launch and forget (silent execution)
### 5. Error Handling
- ✅ Handle failures gracefully without cascade
- ✅ Report clear error messages with remediation steps
- ✅ Pause execution on critical errors
- ❌ **Never** cascade to next batch on failure
### 6. Token Efficiency
- ✅ Use `overview` operations for status checks
- ✅ Return minimal progress reports
- ✅ Batch specialist launches in single message
- ✅ Cache batch information to avoid re-querying
- ❌ **Never** include full task details in progress reports
### 7. Status Management
- ✅ **Always** use Status Progression Skill for status changes
- ✅ Detect events and delegate to Status Progression Skill
- ✅ Let Status Progression Skill read config and validate
- ❌ **Never** directly change task status
---
## Configuration Reference
**Note:** These are documented patterns for AI reference. Configuration is NOT dynamically loaded via MCP tools. All configuration should be documented in CLAUDE.md or skill files.
```yaml
# .taskorchestrator/config.yaml (documented pattern)
# Parallelism settings
parallelism:
max_parallel_tasks: 5 # Concurrent task limit
auto_launch: true # Auto-cascade to next batch
respect_dependencies: true # Always validate dependencies (CRITICAL)
# Specialist routing
specialist_routing:
fallback_behavior: "use_default" # or "ask_user"
default_specialist: "Implementation Specialist"
# Quality gates (optional)
quality_gates:
enabled: false
task_gates:
testing:
hook: "run_tests"
required: true
```
**Key settings:**
- `max_parallel_tasks`: 3-5 recommended
- `auto_launch`: `true` for automation, `false` for manual control
- `respect_dependencies`: ALWAYS `true`
- `fallback_behavior`: `use_default` recommended
- `quality_gates.enabled`: `false` until hooks implemented
---
## Related Documentation
- **Examples**: See `examples.md` for detailed walkthroughs
- **SKILL.md**: See `SKILL.md` for core workflows and trigger points
- **Status Progression**: See `.claude/skills/status-progression/SKILL.md`
- **Event-Driven Pattern**: See `docs/event-driven-status-progression-pattern.md`