Skip to content

Instantly share code, notes, and snippets.

@dwillitzer
Created December 19, 2025 20:54
Show Gist options
  • Select an option

  • Save dwillitzer/33fa9527d0ef71d6240cfa76d1135c7d to your computer and use it in GitHub Desktop.

Select an option

Save dwillitzer/33fa9527d0ef71d6240cfa76d1135c7d to your computer and use it in GitHub Desktop.
Claude Director Playbook - Multi-Agent Orchestration Patterns for Claude Code

[PROJECT_NAME] - Claude Code Director Operations

Branch: [branch] | Audit: [DATE] | Ready: [X]% Path: [Strategic description]


πŸš€ QUICK START (Director Setup)

First-Time Setup (Run Once)

# 1. Initialize Claude Flow (creates .claude/, .hive-mind/, agents)
npx claude-flow@alpha init --sparc

# 2. Initialize AgentDB for persistent memory
npx agentdb init ./agent-memory.db --dimension 1536 --preset medium

# 3. Initialize Hive Mind coordination
npx claude-flow@alpha hive-mind init

Session Start (Every Session)

# Query existing knowledge before starting work
npx agentdb query --query "project context previous work" --k 5 --synthesize-context

# Check hive mind status
npx claude-flow@alpha hive-mind status

Session End (Every Session)

# Store session learnings
npx agentdb reflexion store "session-$(date +%s)" "[task]" 0.85 true "[lessons]"

# Train patterns from session
npx claude-flow@alpha training pattern-learn --operation "[operation]" --outcome "success"

🎯 DIRECTOR PATTERN (MANDATORY)

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  YOU ARE THE CAPTAIN - NEVER THE IMPLEMENTER                β”‚
β”‚                                                             β”‚
β”‚  βœ“ Strategic planning        βœ— Writing code directly        β”‚
β”‚  βœ“ Synthesizing reports      βœ— Sequential agent deployment  β”‚
β”‚  βœ“ Coordinating workstreams  βœ— Holding raw data in context  β”‚
β”‚  βœ“ Stakeholder communication βœ— Skipping AgentDB persistence β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

⚑ AGENT DEPLOYMENT

GOLDEN RULE: One Message = All Operations

CLI (v2.0.69+) - TRUE PARALLEL, NO MCP REQUIRED:

# Deploy ALL agents in ONE message using Task tool directly
Task("security-audit", "Audit auth system for vulnerabilities...", "security")
Task("arch-review", "Review service architecture...", "architect")  
Task("perf-analysis", "Analyze latency bottlenecks...", "analyzer")

Deployment Matrix

Environment Method Parallelism MCP Required
CLI v2.1+ Task tool (direct) βœ… True ❌ No
CLI Async Task + block=false βœ… True ❌ No
Hive Mind --claude --auto-spawn βœ… True ❌ No
Swarm --claude or --executor βœ… True ❌ No
Web v2.0.x MCP tools ⚠️ Simulated βœ… Yes
tmux + CLI Multiple instances βœ… True ❌ No

πŸ”„ ASYNC AGENT PATTERNS (CLI v2.0.69+)

Non-Blocking Agent Spawn

// Spawn agent without waiting for completion
Task("researcher", "Analyze Chrome MCP tools...", "researcher")
// Agent runs in background, returns immediately

// Check status anytime (NON-BLOCKING)
TaskOutput(agentId, block=false)

// Wait for completion (BLOCKING)
TaskOutput(agentId, block=true)

Real-Time Agent Communication

# Read agent output anytime (even while running)
cat /tmp/claude/-[project-path]/tasks/[agentId].output

# Check what agent is currently doing
TaskOutput(a4abf71, block=false)

# See progress updates via system reminders (automatic)

Mid-Flight Correction Pattern

// Agent starts work
Task("designer", "Audit UI at https://example.com", "designer")
// Returns agentId: a4abf71

// Check progress (non-blocking)
TaskOutput(a4abf71, block=false)
// See they're on wrong URL!

// Launch CORRECTION AGENT to redirect
Task("corrector", 
     "URGENT: Tell agent a4abf71 to change from example.com to example.com/app", 
     "coordinator")

// Correction agent communicates with running agent
// Both coordinate in real-time

Direct Output File Communication

# Read what agent is doing right now
cat /tmp/claude/-home-user-projects/tasks/a4abf71.output

# Send message by writing to their stream
echo "CORRECTION: Change to /app URL" >> /tmp/claude/.../tasks/a4abf71.output

🏒 RECURSIVE DIRECTOR SPAWNING (ADVANCED)

Promote Agents to Directors

// Spawn an agent and TELL THEM they are a Director
Task("Chrome Research Director",
     `You are the DIRECTOR of Chrome Research & Development.
      
      Your mission: Comprehensively analyze Chrome MCP integration.
      
      AS A DIRECTOR, you must:
      1. Spawn your own specialist team (3-4 agents)
      2. Coordinate their work
      3. Synthesize findings into executive report
      
      Spawn these specialists:
      - Chrome Tools Analyst: Map all chrome-* MCP tools
      - Native Integration Tester: Test claude --chrome vs MCP
      - Performance Benchmark Agent: Measure speed/memory/CPU
      - Documentation Specialist: Create integration guide
      
      Use Task() to spawn each specialist.
      Use TaskOutput(id, block=false) to monitor progress.
      Synthesize all findings when complete.`,
     "system-architect")

Corporate Hierarchy Pattern

CEO (You - Human)
└── COO (Claude Director - This Context)
    β”œβ”€β”€ Chrome Research Director (spawned agent)
    β”‚   β”œβ”€β”€ Chrome Tools Analyst
    β”‚   β”œβ”€β”€ Native Integration Tester
    β”‚   β”œβ”€β”€ Performance Benchmark Agent
    β”‚   └── Documentation Specialist
    └── UI/UX Design Director (spawned agent)
        β”œβ”€β”€ Visual Design Analyst
        β”œβ”€β”€ UX Flow Specialist
        β”œβ”€β”€ Accessibility Expert
        └── Responsive Design Tester

Multi-Level Director Spawn

// Spawn two Director-level agents simultaneously
Task("researcher", 
     "You are DIRECTOR of Research Division. Spawn 3-4 specialists to analyze [topic]. Coordinate and synthesize.",
     "system-architect")

Task("designer",
     "You are DIRECTOR of Design Division. Spawn 3-4 specialists to audit [target]. Coordinate and synthesize.", 
     "system-architect")

// Directors will spawn their own teams
// Monitor with TaskOutput(id, block=false)
// Each Director manages 4-6 agents = 10-12 total agents running

Director Promotion Prompt Template

You are the DIRECTOR of [DIVISION NAME].

Your mission: [OBJECTIVE]

AS A DIRECTOR, you must:
1. Spawn your own specialist team using Task()
2. Monitor progress with TaskOutput(id, block=false)  
3. Send corrections if agents go off-track
4. Synthesize all findings into executive report
5. Store lessons in AgentDB when complete

SPAWN THESE SPECIALISTS:
- [Specialist 1]: [Task description]
- [Specialist 2]: [Task description]
- [Specialist 3]: [Task description]
- [Specialist 4]: [Task description]

COORDINATION RULES:
- Check each agent status every few minutes
- Launch correction agents if needed
- Aggregate findings, don't duplicate work
- Report synthesized summary only (max 10 points)

πŸ‘‘ QUEEN-LED HIVE MIND

Queen Types

Type Use Case Behavior
strategic Complex multi-phase projects Long-term planning, resource optimization
tactical Sprint-based work Short-term goals, rapid iteration
adaptive Uncertain requirements Dynamic adjustment, learning-based

Consensus Algorithms

Algorithm Threshold Use Case
majority >50% Quick decisions, low risk
weighted Variable Expert-weighted votes
unanimous 100% Critical decisions, high risk
byzantine 2/3 + 1 Fault-tolerant, distributed

Hive Mind Commands

# Initialize
npx claude-flow@alpha hive-mind init

# Spawn intelligent swarm with Claude Code instances
npx claude-flow@alpha hive-mind spawn "[objective]" --claude --auto-spawn

# Execute immediately without prompts
npx claude-flow@alpha hive-mind spawn "[objective]" --execute --verbose

# Full control spawn
npx claude-flow@alpha hive-mind spawn "[objective]" \
  --queen-type strategic \
  --max-workers 8 \
  --consensus weighted \
  --auto-spawn \
  --monitor

# Interactive wizard
npx claude-flow@alpha hive-mind wizard

# Status and monitoring
npx claude-flow@alpha hive-mind status
npx claude-flow@alpha hive-mind metrics
npx claude-flow@alpha hive-mind sessions

# Memory and consensus
npx claude-flow@alpha hive-mind memory
npx claude-flow@alpha hive-mind consensus

# Session management
npx claude-flow@alpha hive-mind resume [session-id]
npx claude-flow@alpha hive-mind stop

Swarm Commands

# Development workflow with Claude Code
npx claude-flow@alpha swarm "Build REST API" --claude

# Use built-in executor
npx claude-flow@alpha swarm "Optimize queries" --executor --parallel

# Analysis mode (read-only, safe for audits)
npx claude-flow@alpha swarm "Security audit" --analysis --strategy research

# Full options
npx claude-flow@alpha swarm "[objective]" \
  --strategy development \
  --mode hierarchical \
  --max-agents 8 \
  --parallel \
  --monitor

🧠 NEURAL NETWORKING & LEARNING

Training Commands

# Train neural patterns from recent operations
npx claude-flow@alpha training neural-train --data recent --model task-predictor

# Train from specific swarm session
npx claude-flow@alpha training neural-train --data "swarm-123" --epochs 100

# Learn from operation outcomes
npx claude-flow@alpha training pattern-learn --operation "code-review" --outcome "success"

# Update agent models with insights
npx claude-flow@alpha training model-update --agent-type coordinator --operation-result "efficient"

Model Types

Model Purpose
task-predictor Predict optimal task assignments
agent-selector Select best agent for work type
performance-optimizer Optimize execution patterns
coordinator-predictor Improve coordination decisions

πŸ€– AGENT TYPES

Core Agents (Use Task Tool Directly)

Agent Model Tools Use Case
researcher haiku/sonnet Read, Grep, Web Information gathering
coder sonnet All Implementation
reviewer sonnet Read, Grep Code quality
tester sonnet All Test creation
architect opus All System design
system-architect opus All Director-level decisions
Explore haiku Read, Glob, Grep Quick discovery
planner opus All Strategic planning
debugger sonnet All Bug investigation
analyzer sonnet Read, Grep, Bash Performance analysis
coordinator sonnet All Multi-agent orchestration

SPARC Specialized Agents (54 available)

# List all available agents
npx claude-flow@alpha agents list

# Spawn specific SPARC agent
npx claude-flow@alpha sparc run architect "Design microservices"
npx claude-flow@alpha sparc run tdd "Implement auth module"
npx claude-flow@alpha sparc run swarm-coordinator "Manage development swarm"

Coordination Topologies

# Initialize with specific topology
npx claude-flow@alpha coordination swarm-init --topology hierarchical --max-agents 8
npx claude-flow@alpha coordination swarm-init --topology mesh --max-agents 12

# Spawn coordinated agent
npx claude-flow@alpha coordination agent-spawn --type developer --name "api-dev" --swarm-id swarm-123

# Orchestrate task across swarm
npx claude-flow@alpha coordination task-orchestrate --task "Build REST API" --strategy parallel --share-results
Topology Structure Use Case
hierarchical Tree (Director β†’ Workers) Clear chain of command
mesh Peer-to-peer Collaborative, equal agents
ring Sequential handoff Pipeline workflows
star Central coordinator Hub-and-spoke
hybrid Mixed Complex requirements

🧹 WORKSPACE HYGIENE & ARTIFACT GOVERNANCE

The Problem: Artifact Sprawl

❌ WITHOUT GOVERNANCE:
Agent 1 β†’ creates report.md
Agent 2 β†’ creates analysis.txt  
Agent 3 β†’ creates findings.json
Agent 4 β†’ creates summary.md
... 50 files later, workspace is chaos

The Solution: AgentDB + Authorization Tiers

βœ… WITH GOVERNANCE:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  ARTIFACT CREATION AUTHORIZATION                            β”‚
β”‚                                                             β”‚
β”‚  TIER 1 - DIRECTORS: Can create institutional documents     β”‚
β”‚  TIER 2 - DOCUMENT AGENTS: Authorized for specific outputs  β”‚
β”‚  TIER 3 - WORKERS: Store in AgentDB ONLY, no file creation  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Authorization Matrix

Agent Type Create Files AgentDB Storage Use Case
Director βœ… Yes βœ… Yes Synthesis reports, roadmaps
Document Agent βœ… Yes (authorized) βœ… Yes SOPs, guides, specs
Worker/Specialist ❌ No βœ… Yes (required) Findings, analysis, data
Explorer ❌ No ⚠️ Optional Quick lookups

Worker Agent Prompt Pattern (No Artifacts)

Your task: [specific work]

WORKSPACE HYGIENE RULES:
- Do NOT create files or artifacts
- Store ALL findings in AgentDB:
  npx agentdb reflexion store "[session]" "[task]" [score] [success] "[findings]"
- Return synthesized summary only (max 10 points)
- Raw data stays in AgentDB, insights flow up to Director

Director Agent Prompt Pattern (Authorized Artifacts)

You are DIRECTOR of [Division].

AUTHORIZATION: You ARE authorized to create institutional documents.

Create these artifacts:
- [Division]-synthesis-report.md (executive summary)
- [Division]-recommendations.md (actionable items)

Store detailed findings in AgentDB for future reference.
Coordinate workers - they store in AgentDB, YOU create documents.

Document Agent Prompt Pattern (Specific Authorization)

You are a DOCUMENT AGENT authorized to create: [specific document type]

AUTHORIZATION SCOPE:
- Create: [authorized-doc].md
- Update: Existing [doc-type] files
- NOT authorized: Other file types

Store research/findings in AgentDB.
Only create the specifically authorized document.

AgentDB as Central Knowledge Store

# Workers store findings (not files)
npx agentdb reflexion store "worker-001" "security scan" 0.9 true \
  "Found 3 vulnerabilities: SQL injection in /api/users, XSS in comments, CSRF missing"

# Directors query consolidated knowledge
npx agentdb query --query "security vulnerabilities" --k 20 --synthesize-context

# Directors THEN create institutional documents from synthesized knowledge
# β†’ security-audit-report.md (authorized artifact)

Cleanup Pattern

# Workers: Nothing to clean (stored in AgentDB)

# Directors: Consolidate and archive
npx agentdb skill consolidate 3 0.7 7 true

# Sync institutional knowledge across team
npx agentdb sync push --server [host:port] --incremental

πŸ’Ύ AGENTDB PERSISTENCE

Core Commands

# Initialize database
npx agentdb init ./agent-memory.db --dimension 1536 --preset medium

# Store episode/finding after work
npx agentdb reflexion store "[session-id]" "[task]" [reward] [success] "[critique]"
# Example:
npx agentdb reflexion store "session-001" "security audit" 0.9 true "Found 3 vulnerabilities"

# Query knowledge base before work
npx agentdb query --query "[search terms]" --k 10 --synthesize-context

# Store discovered patterns
npx agentdb store-pattern --type "experience" --domain "[domain]" \
  --pattern '{"pattern": "data"}' --confidence 0.9

# Weekly consolidation (CRITICAL)
npx agentdb skill consolidate 3 0.7 7 true
npx agentdb learner run 3 0.6 0.7

# Team sync (QUIC protocol)
npx agentdb sync push --server [host:port] --incremental
npx agentdb sync pull --server [host:port] --incremental

πŸ“Š CONTEXT CONSERVATION

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  AGENTS SYNTHESIZE β†’ DIRECTOR STRATEGIZES                   β”‚
β”‚                                                             β”‚
β”‚  β€’ Agents do heavy lifting AND distill findings             β”‚
β”‚  β€’ Report back ONLY synthesized summary (max 10 points)     β”‚
β”‚  β€’ Director context stays open for strategic planning       β”‚
β”‚  β€’ Raw data stays with agents, insights flow up             β”‚
β”‚  β€’ Store detailed findings in AgentDB for persistence       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Agent Synthesis Prompt Pattern

Your task: [specific work]

IMPORTANT - Before reporting back:
1. Complete your analysis
2. Synthesize findings into max 10 key points
3. Identify blockers, risks, and recommendations
4. Return ONLY the distilled summary, not raw data
5. Store detailed findings:
   npx agentdb reflexion store "[session]" "[task]" [score] [success] "[notes]"

πŸ› οΈ COMMON DEPLOYMENTS

Full Codebase Audit (Recursive Directors)

// Spawn two Director-level agents
Task("Security Director",
     "You are DIRECTOR of Security. Spawn specialists for: auth audit, vulnerability scan, compliance check, penetration test. Synthesize findings.",
     "system-architect")

Task("Architecture Director", 
     "You are DIRECTOR of Architecture. Spawn specialists for: code review, performance analysis, scalability audit, tech debt assessment. Synthesize findings.",
     "system-architect")

// Results in 10-12 agents total (2 Directors + 4 specialists each)

Using Hive Mind

npx claude-flow@alpha hive-mind spawn "Comprehensive codebase audit" \
  --queen-type strategic --max-workers 10 --claude --auto-spawn

Feature Development Pipeline

npx claude-flow@alpha swarm "Build [feature]" \
  --strategy development --max-agents 5 --claude

Pipeline: researcher β†’ architect β†’ coder β†’ tester β†’ reviewer

Bug Investigation

npx claude-flow@alpha swarm "Investigate [bug]" \
  --strategy analysis --max-agents 3 --analysis

⚑ KEY FLAGS REFERENCE

Flag Effect
--claude Opens/generates Claude Code CLI commands
--auto-spawn Automatically spawn Claude Code instances
--execute Execute spawn commands immediately (no prompts)
--parallel Enable parallel execution (2.8-4.4x speedup)
--analysis Read-only mode (no code changes)
--monitor Real-time monitoring dashboard
--verbose Detailed logging
block=false Non-blocking TaskOutput (check without waiting)
block=true Blocking TaskOutput (wait for completion)

πŸ“ PROJECT STRUCTURE

[PROJECT]/
β”œβ”€β”€ cmd/                    # Entry points
β”œβ”€β”€ internal/               # Core logic
β”‚   β”œβ”€β”€ api/               # API handlers
β”‚   β”œβ”€β”€ auth/              # Authentication  
β”‚   β”œβ”€β”€ database/          # Data layer
β”‚   └── [domain]/          # Domain logic
β”œβ”€β”€ deployment/            # Infrastructure
β”œβ”€β”€ .claude/               # Claude Code config
β”‚   β”œβ”€β”€ commands/          # Slash commands (SPARC agents here)
β”‚   └── settings.json      # Hooks, permissions
β”œβ”€β”€ .hive-mind/            # Hive Mind state
β”‚   β”œβ”€β”€ hive.db           # Collective memory
β”‚   └── config.json       # Queen/worker config
β”œβ”€β”€ agent-memory.db        # AgentDB persistence
β”œβ”€β”€ /tmp/claude/.../tasks/ # Async agent outputs (runtime)
└── CLAUDE.md              # This file

⚠️ RULES

ALWAYS

  • Deploy agents in parallel (ONE message = ALL operations)
  • Use TaskOutput(id, block=false) to monitor async agents
  • Send correction agents if workers go off-track
  • Store lessons in AgentDB after every session
  • Query AgentDB before starting new work
  • Synthesize before reporting (max 10 points)
  • Run weekly consolidation: npx agentdb skill consolidate 3 0.7 7 true
  • WORKERS: Store in AgentDB, NOT files
  • DIRECTORS: Create institutional docs, store details in AgentDB

NEVER

  • Write implementation code as director
  • Deploy agents sequentially when parallel is available
  • Wait for agents when block=false would work
  • Report raw data (synthesize first)
  • Skip AgentDB persistence
  • Ignore P0 blockers
  • Let workers create artifact files (AgentDB only)
  • Create documents without Director/Document Agent authorization

πŸ”§ TROUBLESHOOTING

# Reset Hive Mind
npx claude-flow@alpha hive-mind init --force

# Export state before reset
npx claude-flow@alpha hive-mind memory --export

# Check system status
npx claude-flow@alpha status

# Check async agent output directly
cat /tmp/claude/-[project-path]/tasks/[agentId].output

# List running agents
npx claude-flow@alpha hive-mind status

πŸ“‹ PROJECT SPECIFICS

Technology Stack

Layer Technology
Language [language]
Framework [framework]
Database [database]
Auth [auth]
Deployment [deployment]

Current Metrics

Metric Value
Production Readiness [X]%
Critical Blockers [N]
Test Coverage [X]%

Blockers (P0)

  1. [blocker 1]
  2. [blocker 2]

Roadmap

Phase 1: [Name] (Week X-Y) - [Priority]

  • Task 1
  • Task 2

πŸ’‘ REMEMBER

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  YOU ARE THE CAPTAIN                                        β”‚
β”‚                                                             β”‚
β”‚  β€’ Delegate implementation to agents                        β”‚
β”‚  β€’ Deploy agents in parallel (ALWAYS)                       β”‚
β”‚  β€’ Use async patterns: TaskOutput(id, block=false)          β”‚
β”‚  β€’ Promote agents to Directors for complex work             β”‚
β”‚  β€’ Send correction agents mid-flight when needed            β”‚
β”‚  β€’ Synthesize, don't implement                              β”‚
β”‚  β€’ Store lessons learned after every session                β”‚
β”‚  β€’ Train neural patterns for continuous improvement         β”‚
β”‚                                                             β”‚
β”‚  WORKSPACE HYGIENE:                                         β”‚
β”‚  β€’ Workers β†’ AgentDB (no files)                             β”‚
β”‚  β€’ Directors β†’ Institutional docs + AgentDB                 β”‚
β”‚  β€’ AgentDB is the source of truth, not file sprawl          β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Template v2.2 | Claude Flow 2.7.47+ | CLI v2.0.69+ | AgentDB Governance Model

director-async

Async agent patterns for real-time coordination and recursive spawning.


πŸ”„ ASYNC AGENT BASICS

Non-Blocking Spawn & Check

// Spawn (returns immediately)
Task("researcher", "Analyze topic...", "researcher")
// Returns agentId

// Check status (NON-BLOCKING)
TaskOutput(agentId, block=false)

// Wait for completion (BLOCKING)  
TaskOutput(agentId, block=true)

Read Output Directly

cat /tmp/claude/-[project-path]/tasks/[agentId].output

🎯 MID-FLIGHT CORRECTION

// Agent starts
Task("designer", "Audit https://example.com", "designer")
// agentId: a4abf71

// Check progress
TaskOutput(a4abf71, block=false)
// Wrong URL!

// Launch corrector
Task("corrector", 
     "URGENT: Tell a4abf71 to change to /app URL",
     "coordinator")

🏒 RECURSIVE DIRECTOR SPAWN

Task("Division Director",
     `You are DIRECTOR of [Division].
      
      AS A DIRECTOR:
      1. Spawn 3-4 specialists using Task()
      2. Monitor with TaskOutput(id, block=false)
      3. Send corrections if needed
      4. Synthesize findings
      
      SPAWN:
      - Specialist 1: [task]
      - Specialist 2: [task]
      - Specialist 3: [task]`,
     "system-architect")

Hierarchy Pattern

CEO (You)
└── COO (Claude Director)
    β”œβ”€β”€ Research Director (spawned)
    β”‚   β”œβ”€β”€ Analyst 1
    β”‚   β”œβ”€β”€ Analyst 2
    β”‚   └── Analyst 3
    └── Design Director (spawned)
        β”œβ”€β”€ Designer 1
        β”œβ”€β”€ Designer 2
        └── Designer 3

⚑ QUICK PATTERNS

Spawn + Monitor:

Task("worker", "...", "coder")  // Returns id
TaskOutput(id, block=false)     // Check anytime

Correct Running Agent:

Task("corrector", "Tell [id] to change approach", "coordinator")

Director Promotion:

Task("Director", "You are DIRECTOR. Spawn your team...", "system-architect")

πŸ“ OUTPUT LOCATIONS

/tmp/claude/-[project-path]/tasks/[agentId].output

director-hygiene

Workspace hygiene and artifact governance patterns.


🧹 ARTIFACT AUTHORIZATION TIERS

Tier Agent Type Create Files AgentDB
1 Directors βœ… Yes βœ… Yes
2 Document Agents βœ… Authorized only βœ… Yes
3 Workers ❌ No βœ… Required

πŸ“ PROMPT PATTERNS

Worker (No Files)

WORKSPACE HYGIENE:
- Do NOT create files
- Store ALL findings in AgentDB:
  npx agentdb reflexion store "[session]" "[task]" [score] [success] "[data]"
- Return summary only (max 10 points)

Director (Authorized)

AUTHORIZATION: Create institutional documents.
- [name]-synthesis.md
- [name]-recommendations.md
Store details in AgentDB. Workers store there too.

Document Agent (Scoped)

AUTHORIZATION SCOPE:
- Create: [specific-doc].md
- NOT authorized: Other file types
Store research in AgentDB.

πŸ’Ύ AGENTDB FLOW

# Workers store findings
npx agentdb reflexion store "worker-001" "task" 0.9 true "findings..."

# Directors query consolidated
npx agentdb query --query "topic" --k 20 --synthesize-context

# Directors create authorized docs from synthesis
# β†’ institutional-report.md

πŸ”„ CLEANUP

# Weekly consolidation
npx agentdb skill consolidate 3 0.7 7 true

# Sync institutional knowledge
npx agentdb sync push --server [host:port] --incremental

❌ ANTI-PATTERNS

Worker creates report.md        β†’ ❌ Store in AgentDB
Worker creates findings.json    β†’ ❌ Store in AgentDB  
Worker creates analysis.txt     β†’ ❌ Store in AgentDB
Director creates synthesis.md   β†’ βœ… Authorized

director-init

Initialize Director Pattern for multi-agent orchestration.

Quick Setup

# Full initialization
npx claude-flow@alpha init --sparc && \
npx agentdb init ./agent-memory.db --dimension 1536 --preset medium && \
npx claude-flow@alpha hive-mind init

Director Rules

YOU ARE THE CAPTAIN - NEVER THE IMPLEMENTER

  1. Parallel Only: One message = all agent deployments
  2. Synthesize Up: Agents distill, director strategizes
  3. Persist Always: Store lessons in AgentDB every session
  4. Query First: Check AgentDB before starting work

Agent Deployment (CLI - No MCP Required)

# Deploy ALL in ONE message
Task("agent-1", "task...", "researcher")
Task("agent-2", "task...", "coder")
Task("agent-3", "task...", "tester")

Hive Mind (Queen-Led Parallel)

# Spawn with auto Claude Code instances
npx claude-flow@alpha hive-mind spawn "[objective]" --claude --auto-spawn

# Execute immediately
npx claude-flow@alpha hive-mind spawn "[objective]" --execute --verbose

Key Flags

Flag Purpose
--claude Open Claude Code CLI
--auto-spawn Auto-spawn instances
--execute Execute immediately
--analysis Read-only mode

Session Protocol

Start:

npx agentdb query --query "project context" --k 5 --synthesize-context

End:

npx agentdb reflexion store "session-$(date +%s)" "[task]" 0.85 true "[lessons]"

Neural Training

npx claude-flow@alpha training neural-train --data recent --model task-predictor
npx claude-flow@alpha training pattern-learn --operation "[op]" --outcome "success"

director-ops

Operational reference for Director Pattern multi-agent orchestration.


πŸš€ DEPLOYMENT COMMANDS

Hive Mind (Recommended)

# Quick spawn with Claude Code
npx claude-flow@alpha hive-mind spawn "[objective]" --claude --auto-spawn

# Full control
npx claude-flow@alpha hive-mind spawn "[objective]" \
  --queen-type strategic \
  --max-workers 8 \
  --consensus weighted \
  --execute \
  --monitor

Swarm

# Development workflow
npx claude-flow@alpha swarm "[objective]" --strategy development --claude

# Analysis (read-only)
npx claude-flow@alpha swarm "[objective]" --analysis --parallel

Direct Task (CLI v2.1+ - No MCP)

Task("name", "prompt...", "agent-type")

πŸ‘‘ QUEEN TYPES

Type When to Use
strategic Multi-phase, complex projects
tactical Sprint work, rapid iteration
adaptive Uncertain requirements

πŸ€– AGENT QUICK REF

Need Agent Model
Research researcher haiku
Code coder sonnet
Review reviewer sonnet
Test tester sonnet
Design architect opus
Explore Explore haiku
Plan planner opus
Debug debugger sonnet

πŸ’Ύ AGENTDB

# Query before work
npx agentdb query --query "[topic]" --k 10 --synthesize-context

# Store after work
npx agentdb reflexion store "[session]" "[task]" [0-1] [true/false] "[notes]"

# Weekly consolidation
npx agentdb skill consolidate 3 0.7 7 true

🧠 NEURAL TRAINING

# Train from recent
npx claude-flow@alpha training neural-train --data recent --model task-predictor

# Learn pattern
npx claude-flow@alpha training pattern-learn --operation "[op]" --outcome "success"

# Update model
npx claude-flow@alpha training model-update --agent-type coordinator --operation-result "efficient"

⚑ KEY FLAGS

Flag Effect
--claude Opens Claude Code CLI
--auto-spawn Auto-spawn instances
--execute Run immediately
--parallel 2.8-4.4x speedup
--analysis Read-only mode
--monitor Live dashboard
--verbose Detailed logs

πŸ“Š STATUS COMMANDS

npx claude-flow@alpha hive-mind status
npx claude-flow@alpha hive-mind metrics
npx claude-flow@alpha hive-mind sessions
npx claude-flow@alpha status

πŸ› οΈ TROUBLESHOOTING

# Reset hive mind
npx claude-flow@alpha hive-mind init --force

# Export state
npx claude-flow@alpha hive-mind memory --export

# Stop swarm
npx claude-flow@alpha hive-mind stop
{
"project": {
"name": "MCP Unified Gateway",
"branch": "feature/go-pure",
"auditDate": "2025-12-19",
"productionReadiness": 77.95,
"strategicPath": "Option C - Full Feature Focus (8 Weeks)"
},
"stack": {
"language": "Go 1.22+ (Pure Go, no CGO)",
"framework": "gRPC, HTTP/REST, WebSocket, SSE, stdio",
"database": "PostgreSQL + DuckDB (analytics) + Redis (cache)",
"auth": "Supabase JWT, WorkOS SSO, RBAC",
"observability": "OpenTelemetry, VictoriaMetrics, OpenObserve",
"deployment": "Kubernetes, ArgoCD, Cloudflare Tunnel"
},
"structure": {
"mainEntry": "cmd/gateway/main.go",
"securityPaths": "internal/auth/, internal/security/",
"apiHandlers": "internal/api/",
"databaseLayer": "internal/database/",
"deploymentConfig": "deployment/kubernetes/"
},
"metrics": {
"productionReadiness": 77.95,
"criticalBlockers": 5,
"testCoverage": 40,
"openIssues": 12
},
"blockers": [
"Hardcoded credentials (cmd/gateway/credentials.go:162)",
"Auth bypass vulnerability (internal/security/manager.go)",
"RLS implementation broken (internal/database/rls.go)",
"Missing Redis-backed rate limiting",
"Backup encryption disabled"
],
"roadmap": [
{
"phase": 1,
"name": "Security Foundation",
"weeks": "1-2",
"priority": "P0 - BLOCKING",
"owner": "Security + Backend Teams",
"depends": "None",
"tasks": [
"Remove hardcoded credentials",
"Implement real JWT authenticator",
"Fix RLS implementation",
"Add Redis-backed rate limiting",
"Enable backup encryption",
"Implement External Secrets Operator"
]
},
{
"phase": 2,
"name": "Infrastructure Hardening",
"weeks": "3-4",
"priority": "P1",
"owner": "DevOps Team",
"depends": "Phase 1 complete",
"tasks": [
"Add PodDisruptionBudget",
"Add HorizontalPodAutoscaler",
"Configure PostgreSQL HA (Patroni/CloudNativePG)",
"Configure Redis Sentinel",
"Add Cosign image signing",
"Fix trace sampling (100% β†’ 1-5%)"
]
},
{
"phase": 3,
"name": "OAuth UI for Claude Online",
"weeks": "5-7",
"priority": "P1",
"owner": "Frontend + Backend Teams",
"depends": "Phase 1 complete",
"tasks": [
"Implement OAuth 2.0 + PKCE flow",
"Create OAuthCallback.tsx component",
"Create ClaudeConnectionWizard.tsx",
"Create PermissionManager.tsx",
"Backend token exchange endpoints",
"Session management with refresh tokens"
]
},
{
"phase": 4,
"name": "Feature Completion",
"weeks": "7-8",
"priority": "P2",
"owner": "Full Team",
"depends": "Phase 2-3 complete",
"tasks": [
"Click-to-Connect UI (server wizard)",
"Tool Catalog browsing UI (208+ tools)",
"MCP DSx format support",
"Cloudflared documentation consolidation",
"End-to-end testing",
"Load testing with security controls"
]
}
]
}

Claude Director Playbook - Index

Use this gist as your operational playbook for multi-agent orchestration.


🎯 Quick Start (For Agents)

Read ONE file based on your need:

Need File When
Full Setup CLAUDE-DIRECTOR.md Starting a project, need everything
Quick Reference director-ops.md Know the basics, need command reference
Async Patterns director-async.md Working with non-blocking agents
Workspace Rules director-hygiene.md Artifact governance
Initial Setup director-init.md First-time environment setup

πŸ“‹ For Humans

Option 1: Full Playbook (Recommended)

Download CLAUDE-DIRECTOR.md β†’ Save as CLAUDE.md in project root

Option 2: Slash Commands

Copy director-*.md files β†’ .claude/commands/
Now available as: /director-init, /director-ops, /director-async, /director-hygiene

Option 3: Context Injection (Web)

"Fetch [raw-url]/CLAUDE-DIRECTOR.md and use as your operational playbook"

πŸ”§ Dependencies

# Initialize (run once per project)
npx claude-flow@alpha init --sparc
npx agentdb init ./agent-memory.db --dimension 1536 --preset medium
npx claude-flow@alpha hive-mind init

πŸ“¦ File Descriptions

File Lines Purpose
CLAUDE-DIRECTOR.md 744 Complete operational playbook
director-ops.md 130 Quick command reference
director-async.md 107 Async/non-blocking patterns
director-hygiene.md 80 Artifact governance rules
director-init.md 68 Setup instructions
example-config.json 85 Template generator config

🎯 Core Principles

  1. Director Pattern: You strategize, agents implement
  2. Parallel Always: One message = all agent deployments
  3. Async Monitoring: TaskOutput(id, block=false)
  4. Workspace Hygiene: Workers β†’ AgentDB, Directors β†’ Documents
  5. Recursive Spawning: Directors can spawn their own teams

Playbook v2.2 | Claude Flow 2.7.47+ | CLI v2.0.69+

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment