# Multi-Agent Patterns Quick Reference
## Actionable Patterns for Genesis Implementation

**Created**: 2026-02-15
**Status**: ACTIVE PROTOCOL
**Authority**: Extracted from 6-framework deep research

---

## The Golden Rules (Non-Negotiable)

1. **Context Isolation Over Shared History**
   - Lead agent = compact state (plan + decisions + artifacts)
   - Workers = isolated context windows
   - Multi-agent uses **15× more tokens** than single-agent

2. **Hub-and-Spoke Over Peer-to-Peer**
   - Central orchestrator coordinates all agents
   - No agent-to-agent chatter (communication scales O(n²))
   - Clear ownership boundaries

3. **Summaries Over Full Content**
   - Workers return 500-word summaries, not 50K outputs
   - File references instead of content duplication
   - Aggressive compression at phase boundaries

4. **One Job Per Agent**
   - Specialized workers > generalist workers
   - Clear task boundaries
   - No role overlap

5. **Model Mixing for Cost**
   - Expensive lead (Claude Opus 4.6) for orchestration
   - Cheap workers (Gemini Flash, Claude Sonnet) for execution
   - 90%+ improvement with mixed models vs. single expensive model

---

## Pattern 1: Orchestrator-Worker (RECOMMENDED)

**Source**: Claude Agent SDK + Anthropic Research System

### Architecture

```
Lead Agent (Compact Context)
    ├──► spawn(Worker 1, scoped_context)  [Isolated]
    ├──► spawn(Worker 2, scoped_context)  [Isolated]
    └──► spawn(Worker 3, scoped_context)  [Isolated]
         │
         └──► Each returns: 500-word summary
              │
              └──► Lead synthesizes → Final result
```

### Implementation

```python
# Lead Agent (main Claude Code session)
def orchestrate(query: str):
    # 1. Decompose into parallel subtasks
    subtasks = [
        {"objective": "Research approach A", "context": {...}},
        {"objective": "Research approach B", "context": {...}},
        {"objective": "Research approach C", "context": {...}}
    ]

    # 2. Spawn isolated workers
    summaries = []
    for task in subtasks:
        worker = spawn_subagent(
            task=task["objective"],
            context=task["context"],  # SCOPED, not full lead history
            expected_output="500-word summary with key findings"
        )
        summaries.append(worker.execute())

    # 3. Synthesize (lead context stays compact)
    return synthesize_findings(summaries)
```

### When to Use
- Research and analysis tasks
- Parallel exploration of alternatives
- Operations with verbose outputs (tests, logs, docs)
- Token efficiency is critical

### Token Savings
- **High**: Prevents context explosion in lead
- Workers can run 50K token operations, lead sees only 500 words

---

## Pattern 2: Task DAG Coordination

**Source**: LangGraph + Claude Code Task tool

### Architecture

```
Task Graph (Shared State via Task System)

Research Task ──results──► Design Task ──spec──► Implementation Task
    │                          │                       │
    └──────────────────────────┴───────────────────────┴──► Shared State
```

### Implementation

```python
from claude_code import TaskCreate, TaskUpdate

# Define task graph
research = TaskCreate(
    title="Research Phase",
    description="Investigate approach options",
    dependencies=[]
)

design = TaskCreate(
    title="Design Phase",
    description="Create architecture based on research",
    dependencies=[research.id]  # Waits for research
)

implementation = TaskCreate(
    title="Implementation Phase",
    description="Build based on design",
    dependencies=[design.id]
)

# Agents execute tasks, update state
TaskUpdate(research.id, status="completed", result="...")
# → Triggers design task
```

### When to Use
- Clear sequential dependencies
- Need resumable workflows (checkpointing)
- Explicit coordination required
- Complements RWL loops

### Benefits
- **Lowest latency** (benchmarked vs. other frameworks)
- Deterministic execution order
- Built-in checkpointing

---

## Pattern 3: Hub-and-Spoke Team

**Source**: CrewAI + Claude Code Agent Teams

### Architecture

```
Lead Agent (Hub)
    ├──► Teammate: Research Specialist
    ├──► Teammate: Implementation Specialist
    └──► Teammate: QA Specialist

All communication flows through Lead (no peer-to-peer)
```

### Implementation

```python
# Lead Agent (Hub)
def coordinate_team(task: str):
    # Spawn specialized teammates
    researcher = spawn_teammate("research-specialist", context="...")
    builder = spawn_teammate("builder-specialist", context="...")
    tester = spawn_teammate("qa-specialist", context="...")

    # Hub delegates
    send_message(researcher, "Investigate approach X")

    # Wait for result
    research_result = wait_for_message(researcher)

    # Delegate next step
    send_message(builder, f"Implement: {research_result.summary}")

    # No researcher ↔ builder direct communication
```

### When to Use
- Clear role specialization
- Need to prevent communication explosion
- Team of 3-5 agents
- Enterprise-style workflows

### Benefits
- **O(n) communication** instead of O(n²)
- Clear ownership boundaries
- Easy to debug (all traffic visible to hub)

---

## Pattern 4: Parallel Scouts (Research)

**Source**: Anthropic Research System

### Architecture

```
Lead: "What's the best approach for X?"
    ├──► Scout 1: Investigate Option A [parallel]
    ├──► Scout 2: Investigate Option B [parallel]
    └──► Scout 3: Investigate Option C [parallel]
         │
         └──► Lead: Synthesize findings → Recommendation
```

### Implementation

```python
# Parallel independent investigations
scouts = [
    spawn_subagent("Research Option A", isolated=True),
    spawn_subagent("Research Option B", isolated=True),
    spawn_subagent("Research Option C", isolated=True)
]

# Each scout explores independently (no shared history)
findings = parallel_execute(scouts)

# Lead synthesizes
recommendation = synthesize_with_tradeoffs(findings)
```

### When to Use
- Multiple competing hypotheses
- Need independent perspectives
- Avoid path dependency
- Research-first protocol

### Benefits
- **90.2% improvement** over single-agent (Anthropic benchmark)
- No groupthink
- Parallel = faster

---

## Pattern 5: Handoff Chain (Simple)

**Source**: OpenAI Swarm

### Architecture

```
Agent A (Active) ──handoff──► Agent B (Active) ──handoff──► Agent C (Active)
    │                             │                             │
    └─────────────────────────────┴─────────────────────────────┴─► Shared History
```

### Implementation

```python
# Sequential handoff
result_a = agent_a.execute(task)

if result_a.needs_specialization:
    result_b = agent_b.execute(result_a.context)  # Handoff
    return result_b
else:
    return result_a
```

### When to Use
- Simple linear workflows
- Clear specialization boundaries
- Learning multi-agent patterns
- **NOT for complex parallel workflows**

### Limitations
- Sequential (slower than parallel)
- Shared history overhead
- Best for 2-3 agents max

---

## Critical Pitfalls (AVOID)

### 1. Context Explosion

**DON'T**:
```python
# BAD: Full history to every subagent
subagent.execute(full_lead_context)  # 100K tokens!
```

**DO**:
```python
# GOOD: Scoped context
subagent.execute({
    "task": "Research X",
    "relevant_context": summary_of_relevant_info  # 2K tokens
})
```

### 2. Unbounded Looping

**DON'T**:
```python
# BAD: No exit condition
while True:
    agent_a.respond()
    agent_b.respond()
    agent_c.respond()
```

**DO**:
```python
# GOOD: Max iterations + convergence check
for round in range(max_rounds=3):
    responses = [a.respond() for a in agents]
    if converged(responses):
        break
```

### 3. Peer-to-Peer Chatter

**DON'T**:
```python
# BAD: 10 agents = 45 relationships
agent_1.message(agent_2)
agent_2.message(agent_3)
agent_3.message(agent_1)  # Chaos!
```

**DO**:
```python
# GOOD: Hub coordinates all
lead.message(agent_1)
response = lead.receive(agent_1)
lead.message(agent_2)  # 10 agents = 10 relationships
```

### 4. Verbose Outputs in Lead Context

**DON'T**:
```python
# BAD: 50K test logs in lead context
test_results = run_all_tests()  # Huge output!
lead_context.append(test_results)
```

**DO**:
```python
# GOOD: Isolate verbose operation
test_summary = subagent.run_tests()  # Returns 500-word summary
lead_context.append(test_summary)
```

---

## Genesis Implementation Blueprint

### Hybrid Pattern (Recommended)

```
┌─────────────────────────────────────────────────┐
│         Genesis Multi-Agent Stack               │
├─────────────────────────────────────────────────┤
│                                                 │
│  Lead Agent: Claude Opus 4.6 (Orchestrator)    │
│       │                                         │
│       ├──► Task DAG (Coordination Layer)       │
│       │       ├── Research (Agent Teams)       │
│       │       ├── Design (Single Agent)        │
│       │       └── Implementation (RWL Swarm)   │
│       │                                         │
│       ├──► Agent Teams (Parallel Research)     │
│       │       └── Hub-and-Spoke coordination   │
│       │                                         │
│       ├──► RWL Swarm (Gemini Execution)       │
│       │       └── Gemini Flash for coding      │
│       │                                         │
│       └──► Supermemory (Context Offload)       │
│               └── Persistent storage            │
└─────────────────────────────────────────────────┘
```

### Workflow

1. **Claude Orchestrates**:
   - Decompose query into tasks
   - Create Task DAG for dependencies
   - Spawn Agent Teams for research
   - Dispatch RWL Swarm for implementation

2. **Agent Teams Execute Research**:
   - Hub-and-Spoke coordination
   - Parallel scouts for alternatives
   - Context isolation per teammate
   - Summaries returned to Lead

3. **RWL Swarm Implements**:
   - Gemini workers execute atomic stories
   - Lead monitors via Task system
   - Results committed to Supermemory

4. **Lead Synthesizes**:
   - Pull summaries from agents
   - Pull results from Supermemory
   - Compact state maintained
   - Final result to user

### Token Optimization Checklist

- [ ] Lead maintains: plan + decisions + artifacts (< 10K tokens)
- [ ] Subagents spawned with scoped context (< 5K tokens each)
- [ ] Verbose operations isolated (tests, logs, docs)
- [ ] File references used (not content duplication)
- [ ] Phase boundaries = summarization
- [ ] Model mixing: Opus lead, Gemini/Sonnet workers
- [ ] Max iterations on all loops (no unbounded)
- [ ] Hub-and-Spoke communication (O(n) not O(n²))
- [ ] State pruned after major phases
- [ ] Context offloaded to Supermemory

---

## Framework Selection (Quick)

| Task Type | Framework Pattern | Reason |
|-----------|------------------|--------|
| Research / Analysis | **Orchestrator-Worker** | Token efficient, parallel |
| Complex State Machine | **Task DAG** | Deterministic, resumable |
| Role-Based Team | **Hub-and-Spoke** | Clear ownership, scalable |
| Code Generation | **RWL Swarm** (existing) | Optimized for coding |
| Simple Handoff | **Handoff Chain** | Easy to understand |

---

## Token Cost Reality Check

**Single-Agent Claude Opus**:
- Input: $15 / MTok
- Output: $75 / MTok
- Typical research task: 50K tokens = $0.75 - $3.75

**Multi-Agent Claude Opus** (4 agents):
- **15× token multiplier** (Anthropic data)
- Same task: 750K tokens = $11.25 - $56.25

**Multi-Agent Mixed Models** (Opus lead + 3 Sonnet workers):
- Lead: 50K tokens × $15/$75 = $0.75 - $3.75
- Workers: 600K tokens × $3/$15 = $1.80 - $9.00
- **Total: $2.55 - $12.75** (77% cheaper than all-Opus)
- **Quality: 90.2% better** than single Opus (Anthropic)

**Genesis Hybrid** (Claude lead + Gemini RWL):
- Lead: 50K tokens × $15/$75 = $0.75 - $3.75
- RWL: 600K tokens × Gemini pricing (~$0.10/MTok) = $0.06 - $0.30
- **Total: $0.81 - $4.05** (95% cheaper, nearly same quality)

**Conclusion**: Model mixing is MANDATORY for production scale.

---

## References

Full research report: `/mnt/e/genesis-system/Research reports/MULTI_AGENT_FRAMEWORK_COMPARISON_2026.md`

Key sources:
- Anthropic Research System (Claude Agent SDK patterns)
- LangGraph (state machine, lowest token usage)
- CrewAI (hub-and-spoke, role-based)
- AutoGen (multi-model routing, cost tracking)
- MetaGPT (assembly-line, scoped documents)
- OpenAI Swarm/Agents SDK (handoff patterns)

---

**Last Updated**: 2026-02-15
**Status**: ACTIVE — Use these patterns for all Genesis multi-agent implementations
