# Orchestrator Flow Diagram

## System Architecture

```
┌─────────────────────────────────────────────────────────────────────┐
│                         USER                                        │
│                           │                                         │
│                           ▼                                         │
│                ┌────────────────────┐                               │
│                │  Project Manager   │  (Root Workspace)            │
│                │   (Orchestrator)   │                               │
│                └────────┬───────────┘                               │
│                         │                                           │
│                         │ Delegates tasks                           │
│                         │                                           │
│          ┌──────────────┴──────────────┐                           │
│          ▼                              ▼                           │
│  ┌───────────────────┐        ┌───────────────────┐               │
│  │  Research Team    │        │ Development Team  │               │
│  │   (Workspace 1)   │        │   (Workspace 2)   │               │
│  └───────────────────┘        └───────────────────┘               │
│          │                              │                           │
│          ├─ Research Lead               ├─ Tech Lead                │
│          ├─ Data Analyst                ├─ Backend Dev             │
│          └─ Report Writer               └─ Frontend Dev            │
│                                                                      │
│          │                              │                           │
│          └──────────┬──────────────────┘                           │
│                     │                                               │
│                     ▼                                               │
│            Returns results to                                       │
│            Project Manager                                          │
│                     │                                               │
│                     ▼                                               │
│            Project Manager                                          │
│            synthesizes and                                          │
│            reports to USER                                          │
└─────────────────────────────────────────────────────────────────────┘
```

## Message Flow Example

### Phase 1: Initial Delegation

```
USER
  │
  │ "Build a social media analytics dashboard..."
  │
  ▼
Project Manager
  │
  ├─────────────────────────────────────┐
  │                                     │
  │ "Research market & competitors"     │ "Design backend & frontend"
  │                                     │
  ▼                                     ▼
Research Lead                        Tech Lead
```

### Phase 2: Team Collaboration

```
Research Team Workspace:                Development Team Workspace:

Research Lead                           Tech Lead
  │                                       │
  │ "Analyze competitor data"             │ "Design API architecture"
  │                                       │
  ▼                                       ▼
Data Analyst                            Backend Dev
  │                                       │
  │ Returns analysis                      │ Returns API design
  │                                       │
  ▼                                       ▼
Research Lead                           Tech Lead
  │                                       │
  │ "Write report"                        │ "Design UI components"
  │                                       │
  ▼                                       ▼
Report Writer                           Frontend Dev
  │                                       │
  │ Returns report                        │ Returns UI design
  │                                       │
  ▼                                       ▼
Research Lead                           Tech Lead
```

### Phase 3: Result Aggregation

```
Research Lead                           Tech Lead
  │                                       │
  │ [subteam_result]                      │ [subteam_result]
  │ "Market research complete"            │ "Technical design complete"
  │                                       │
  └────────────────┬───────────────────────┘
                   │
                   ▼
            Project Manager
                   │
                   │ Synthesizes results
                   │
                   ▼
                 USER
```

## Execution Timeline

```
Time  │ Root Workspace        │ Research Team           │ Development Team
──────┼───────────────────────┼─────────────────────────┼──────────────────────
  0   │ USER → PM: "Task..."  │                         │
  1   │ PM analyzes           │                         │
  2   │ PM → Research Lead    │                         │
  3   │                       │ RL → Data Analyst       │
  4   │ PM → Tech Lead        │                         │ TL analyzes
  5   │                       │ DA → RL (analysis)      │ TL → Backend Dev
  6   │                       │ RL → Report Writer      │ TL → Frontend Dev
  7   │                       │                         │ BD → TL (API design)
  8   │                       │ RW → RL (report)        │ FD → TL (UI design)
  9   │                       │ RL → PM [result]        │ TL → PM [result]
 10   │ PM synthesizes        │                         │
 11   │ PM → USER: "Done!"    │                         │
```

Legend:
- PM = Project Manager
- RL = Research Lead
- DA = Data Analyst
- RW = Report Writer
- TL = Tech Lead
- BD = Backend Dev
- FD = Frontend Dev

## Key Communication Patterns

### 1. Parent → Child (Delegation)

```python
# Project Manager sends task to team lead
await workspace.route_message(
    sender="Project Manager",
    recipient="Research Lead",
    content="Research competitors and user needs",
    manager=workspace_manager
)
```

The message automatically routes from root workspace to child workspace.

### 2. Within Workspace (Collaboration)

```python
# Research Lead delegates to Data Analyst (same workspace)
return {
    "send_to": "Data Analyst",
    "content": "Analyze competitor features"
}
```

### 3. Child → Parent (Results)

When a child workspace completes, the execution engine automatically sends a `[subteam_result]` message to the parent workspace:

```python
# Automatically generated by execution engine
await parent_workspace.route_message(
    sender="Research Lead",
    recipient="Project Manager",
    content="[subteam_result] Research complete: ...",
    manager=workspace_manager
)
```

## Workspace Lifecycle

```
1. CREATION
   ├─ WorkspaceManager.create_workspace()
   ├─ Agents cloned from registry
   ├─ MessageRouter initialized
   └─ Parent-child links established

2. INITIALIZATION
   ├─ Agents receive [startup] events
   └─ Workspace marked as ready

3. EXECUTION
   ├─ Messages routed via MessageRouter
   ├─ Agents process messages
   ├─ Responses scheduled
   └─ Child workspaces triggered as needed

4. COMPLETION
   ├─ Agent sends to USER (root) or PROJECT MANAGER (child)
   ├─ [subteam_result] sent to parent (if child)
   └─ Workspace marked as complete

5. CLEANUP
   ├─ Transcripts saved
   ├─ Workspace removed from manager
   └─ Temporary files deleted
```

## Agent Memory Isolation

Each workspace has **independent agent instances** with separate memory:

```
Root Workspace:
  └─ Project Manager (instance 1)
      └─ Memory: conversation with USER + team results

Research Team Workspace:
  ├─ Research Lead (instance 1)
  │   └─ Memory: conversation with Data Analyst & Report Writer
  ├─ Data Analyst (instance 1)
  │   └─ Memory: conversation with Research Lead
  └─ Report Writer (instance 1)
      └─ Memory: conversation with Research Lead

Development Team Workspace:
  ├─ Tech Lead (instance 1)
  │   └─ Memory: conversation with Backend & Frontend Devs
  ├─ Backend Dev (instance 1)
  │   └─ Memory: conversation with Tech Lead
  └─ Frontend Dev (instance 1)
      └─ Memory: conversation with Tech Lead
```

**Key Point**: Even though we use the same logic functions (e.g., `tech_lead_logic`), each workspace gets its own **cloned instance** with independent memory. Changes in one workspace don't affect others.

## Scaling the Pattern

### Adding More Teams

```
Project Manager (Root)
  │
  ├─ Research Team (3 agents)
  ├─ Development Team (3 agents)
  ├─ QA Team (3 agents)            ← New team
  ├─ Marketing Team (3 agents)     ← New team
  └─ Operations Team (3 agents)    ← New team
```

### Deeper Nesting

```
Project Manager (Root)
  │
  └─ Development Team
      │
      ├─ Backend Team
      │   ├─ API Dev
      │   ├─ Database Dev
      │   └─ DevOps
      │
      └─ Frontend Team
          ├─ UI Dev
          ├─ UX Designer
          └─ QA Engineer
```

### Dynamic Team Creation

Agents can request new subteams on-demand:

```python
# Project Manager requests a specialized ML team
return {
    "action": "request_subteam",
    "reason": "Need ML expertise for predictive analytics",
    "requesting_agent": "Project Manager"
}

# PlannerLLM creates new subteam workspace dynamically
```

## Performance Considerations

### Message Count Scaling

For a task with:
- Root workspace: ~8 messages
- Research Team: ~12 messages  
- Development Team: ~10 messages
- **Total: ~30 messages**

### Cost Estimation

With Claude Sonnet 4.5:
- Average agent response: 200 tokens output
- Total: 30 messages × 200 tokens = 6,000 tokens
- Cost: ~$0.03 per task (at $0.005 per 1K output tokens)

### Execution Time

Typical timing:
- Async execution: 15-30 seconds total
- Sequential would be: 60-90 seconds
- **Speedup: 2-3x with hierarchical async execution**

## Best Practices

### 1. Clear Agent Responsibilities
Each agent should have a well-defined role and clear routing rules.

### 2. Explicit Completion Signals
Teams should explicitly signal completion (e.g., send result to Project Manager).

### 3. Bounded Iteration
Use `max_agent_turns` to prevent infinite loops.

### 4. Error Handling
Implement fallback logic for when teams fail to complete tasks.

### 5. Result Validation
Project Manager should validate team results before sending to USER.

## Debugging Tips

### View Full Transcripts

```python
# Root workspace transcript
root_transcript = root_workspace.router.get_transcript()
for entry in root_transcript:
    print(f"{entry['from']} → {entry['to']}: {entry['content']}")

# Research team transcript
research_transcript = research_workspace.router.get_transcript()
# ... similar
```

### Enable Debug Logging

```python
import logging
logging.basicConfig(level=logging.DEBUG)
```

### Check Agent Memory

```python
# Inspect agent's message history
agent = workspace.agents["Research Lead"]
messages = agent.memory.get_messages()
for msg in messages:
    print(f"{msg.sender} → {msg.content[:50]}...")
```

## Conclusion

The orchestrator pattern with two teams demonstrates:
- ✅ Hierarchical workspace management
- ✅ Independent agent instances per workspace
- ✅ Cross-workspace communication
- ✅ Parallel team execution
- ✅ Result aggregation

This pattern scales to any number of teams and any depth of nesting, making it suitable for complex multi-agent systems.

