Claude Code Agent Teams & tmux Swarm Guide
The definitive guide to running multi-agent Claude Code sessions — from basic tmux setup to full swarm orchestration.
Table of Contents
- Overview: What Are Agent Teams?
- Prerequisites & Setup
- Complete JSON Configuration (settings.json)
- Custom Agent Definitions (.claude/agents/)
- tmux Fundamentals for Claude Code
- Enabling Agent Teams
- Display Modes: How Agents Appear
- Agent Team Architecture & Primitives
- Spawning & Managing Teams
- Prompting Strategies for Multi-Agent Work
- Swarm Patterns (What Works)
- Anti-Patterns (What Doesn't Work)
- Real-World Examples
- Boris Cherny's Parallel Workflow
- Git Worktrees for Isolation
- Cost Management
- Notification Hooks
- Troubleshooting
- Quick Reference Cheatsheet
- Sources
1. Overview: What Are Agent Teams?
Agent Teams is an experimental Claude Code feature that enables multiple Claude instances to work together as a coordinated team. Instead of one Claude doing everything sequentially, you can spawn specialized agents that:
- Share a task list — All agents see the same backlog
- Send messages — Agents communicate via direct messages and broadcasts
- Work in parallel — Multiple agents execute simultaneously in separate panes
- Have specialized roles — Each agent can have different tools, models, and instructions
When to Use Agent Teams vs. Solo Claude
| Scenario | Approach |
|---|---|
| Single feature, one file area | Solo Claude |
| Large refactor across many files | Agent Team |
| Research + Implementation in parallel | Agent Team |
| Quick bug fix | Solo Claude |
| Cross-layer feature (API + UI + tests) | Agent Team |
| Code review while implementing | Agent Team |
Key Limitation
Agent Teams is experimental. Anthropic notes it works best for tasks that are naturally parallelizable and where agents don't need to frequently coordinate on the same files.
2. Prerequisites & Setup
Required Software
# Claude Code (latest)
claude --version
# tmux (for split-pane display)
brew install tmux # macOS
sudo apt install tmux # Linux
# Verify both
which claude && which tmux
Minimum Requirements
- Claude Code CLI (latest version)
- Claude Max or API plan with sufficient tokens
- tmux 3.0+ (for proper pane management)
- A terminal that supports tmux (iTerm2, Ghostty, Alacritty, Kitty, standard Terminal.app)
Optional but Recommended
- iTerm2 (macOS) — Native tmux integration with
tmux -CCcontrol mode - Ghostty — Boris Cherny's terminal of choice, supports color-coded tabs
- Git — For worktree-based isolation
3. Complete JSON Configuration (settings.json)
This is the most important section — exactly what JSON files to create and where to put them to activate agent teams.
Settings File Locations & Precedence
| Priority | File | Scope | Purpose |
|---|---|---|---|
| 1 (highest) | System-level managed-settings.json |
Organization | Admin-enforced policies (cannot be overridden) |
| 2 | CLI arguments (--teammate-mode, etc.) |
Current session | Temporary overrides |
| 3 | .claude/settings.local.json |
Current project (gitignored) | Personal project overrides |
| 4 | .claude/settings.json |
Current project (committed) | Team-shared settings |
| 5 (lowest) | ~/.claude/settings.json |
All projects | Global personal settings |
System paths for managed settings:
- macOS:
/Library/Application Support/ClaudeCode/ - Linux/WSL:
/etc/claude-code/
Step-by-Step: Minimum Configuration to Activate Agent Teams
Step 1: Edit your global settings file
# Open or create the global settings file
nano ~/.claude/settings.json
Step 2: Add the minimum required configuration
{
"env": {
"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
}
}
That's it. That single env entry is the minimum to unlock agent teams.
Step 3 (Recommended): Add display mode and permissions
{
"env": {
"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
},
"teammateMode": "auto"
}
teammateMode options:
| Value | Behavior |
|---|---|
"auto" |
(Default) Uses split panes if inside tmux, otherwise in-process |
"in-process" |
All agents in main terminal, cycle with Shift+Down |
"tmux" |
Forces split-pane mode, auto-detects tmux vs iTerm2 |
Complete Production-Ready settings.json
Here's a fully-loaded configuration with every agent-team-related option:
{
"$schema": "https://json.schemastore.org/claude-code-settings.json",
"env": {
"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
},
"teammateMode": "auto",
"permissions": {
"allow": [
"Bash(npm run test)",
"Bash(npm run lint)",
"Bash(npm run build)",
"Bash(git status)",
"Bash(git diff *)",
"Bash(git log *)"
],
"deny": [
"Bash(rm -rf *)",
"Bash(git push --force *)"
]
},
"hooks": {
"TeammateIdle": [
{
"hooks": [
{
"type": "command",
"command": "echo 'Teammate went idle' && afplay /System/Library/Sounds/Glass.aiff",
"timeout": 10
}
]
}
],
"TaskCompleted": [
{
"hooks": [
{
"type": "command",
"command": "npm test 2>&1 || (echo 'Tests must pass before task completion' >&2 && exit 2)",
"timeout": 120,
"statusMessage": "Running tests before task completion..."
}
]
}
],
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "osascript -e 'display notification \"Claude finished a task\" with title \"Claude Code\"'"
}
]
}
]
}
}
Settings File for a Specific Project
For project-level settings, create .claude/settings.json in your project root:
mkdir -p .claude
nano .claude/settings.json
{
"$schema": "https://json.schemastore.org/claude-code-settings.json",
"env": {
"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
},
"teammateMode": "tmux",
"permissions": {
"allow": [
"Bash(npm run *)",
"Bash(npx jest *)",
"Bash(git *)"
]
},
"hooks": {
"TaskCompleted": [
{
"hooks": [
{
"type": "command",
"command": "./scripts/validate-task.sh",
"timeout": 60
}
]
}
]
}
}
Personal Project Overrides (Not Committed to Git)
For settings you don't want in version control, use .claude/settings.local.json:
{
"teammateMode": "in-process",
"env": {
"DEBUG": "true"
}
}
All Agent-Team-Related Environment Variables
| Variable | Purpose | Set In |
|---|---|---|
CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS |
Required — Enables agent teams | env in settings.json or shell |
CLAUDE_CODE_TEAM_NAME |
Auto-set when team is created | Auto (don't set manually) |
CLAUDE_CODE_PLAN_MODE_REQUIRED |
Auto-set when plan approval required | Auto (don't set manually) |
CLAUDE_CODE_SUBAGENT_MODEL |
Override model for all subagents | env in settings.json or shell |
CLAUDE_CODE_DISABLE_BACKGROUND_TASKS |
Disable background task functionality | env in settings.json or shell |
CLAUDE_AUTOCOMPACT_PCT_OVERRIDE |
Trigger compaction earlier (e.g. 50) |
env in settings.json or shell |
BASH_MAX_TIMEOUT_MS |
Max time for Bash commands | env in settings.json or shell |
Agent Team Hooks Reference
Agent teams have two special hooks beyond the standard ones:
TeammateIdle Hook
Fires when a teammate is about to go idle. Use exit code 2 to block idling and send feedback.
Input (JSON via stdin):
{
"session_id": "abc123",
"transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",
"cwd": "/Users/your-project",
"permission_mode": "default",
"hook_event_name": "TeammateIdle",
"teammate_name": "researcher",
"team_name": "my-project"
}
Example hook script:
#!/bin/bash
INPUT=$(cat)
TEAMMATE=$(echo "$INPUT" | jq -r '.teammate_name')
# Check if the teammate actually finished their work
if [ ! -f "./output/${TEAMMATE}-done.txt" ]; then
echo "You haven't completed your task yet. Check the task list." >&2
exit 2 # Exit code 2 = block idle, send stderr as feedback
fi
exit 0 # Allow idle
TaskCompleted Hook
Fires when a task is being marked complete. Use exit code 2 to block completion.
Input (JSON via stdin):
{
"session_id": "abc123",
"transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",
"cwd": "/Users/your-project",
"permission_mode": "default",
"hook_event_name": "TaskCompleted",
"task_id": "task-001",
"task_subject": "Implement authentication",
"task_description": "Add login/signup endpoints",
"teammate_name": "backend-dev",
"team_name": "my-project"
}
Example hook script:
#!/bin/bash
INPUT=$(cat)
TASK=$(echo "$INPUT" | jq -r '.task_subject')
# Require tests to pass before marking complete
if ! npm test 2>&1; then
echo "Tests must pass before completing: $TASK" >&2
exit 2 # Block completion, send feedback
fi
exit 0 # Allow completion
Where Teams & Tasks Are Stored
When Claude creates a team, these directories are auto-created:
~/.claude/
teams/
my-team/
config.json # Team membership & metadata
tasks/
my-team/
1.json # Task 1
2.json # Task 2
3.json # Task 3
.lock # File-locking for race conditions
Team config.json structure:
{
"name": "my-team",
"leadAgentId": "lead-abc123",
"leadSessionId": "session-xyz789",
"createdAt": "2026-02-20T10:00:00Z",
"members": [
{
"name": "researcher",
"agentId": "agent-def456",
"agentType": "general-purpose"
},
{
"name": "implementer",
"agentId": "agent-ghi789",
"agentType": "general-purpose"
}
]
}
Individual task JSON structure:
{
"id": "1",
"subject": "Research API requirements",
"description": "Investigate third-party APIs needed for integration",
"status": "pending",
"owner": "researcher",
"dependencies": [],
"createdAt": "2026-02-20T10:00:00Z",
"completedAt": null
}
JSON Schema Validation
Add the $schema key to get autocomplete and validation in VS Code, Cursor, etc.:
{
"$schema": "https://json.schemastore.org/claude-code-settings.json"
}
4. Custom Agent Definitions (.claude/agents/)
Custom agents are Markdown files with YAML frontmatter that define specialized teammates.
File Locations
| Location | Scope | Priority |
|---|---|---|
--agents CLI flag (JSON) |
Current session only | 1 (highest) |
.claude/agents/ |
Current project | 2 |
~/.claude/agents/ |
All projects | 3 |
Plugin's agents/ directory |
Where plugin enabled | 4 (lowest) |
Creating Agents
Method 1: Interactive (Recommended)
# Inside Claude Code, run:
/agents
# Then select: Create new agent → User-level or Project-level
# Option to "Generate with Claude" or write manually
Method 2: Manual File Creation
Create a .md file in the agents directory:
# For all projects
mkdir -p ~/.claude/agents
nano ~/.claude/agents/security-reviewer.md
# For current project only
mkdir -p .claude/agents
nano .claude/agents/security-reviewer.md
Complete Agent File Format
---
name: security-reviewer
description: Expert at security code review. Use proactively after any code changes to auth, API, or data handling modules.
tools: Read, Grep, Glob, Bash
disallowedTools: Write, Edit
model: sonnet
permissionMode: default
maxTurns: 30
skills:
- api-conventions
- security-checklist
mcpServers:
- github
memory: user
background: false
isolation: worktree
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-readonly.sh"
PostToolUse:
- matcher: "Edit|Write"
hooks:
- type: command
command: "./scripts/run-linter.sh"
---
You are a senior security engineer specializing in identifying vulnerabilities.
When reviewing code, check for:
- SQL injection risks
- Authentication bypass potential
- Data exposure vulnerabilities
- Missing input validation
- Insecure token/session handling
- Exposed secrets or API keys
Format findings as:
- **CRITICAL**: Must fix before merge
- **WARNING**: Should fix soon
- **INFO**: Consider improving
Include specific remediation steps for each finding.
All Frontmatter Fields Reference
| Field | Required | Type | Description |
|---|---|---|---|
name |
Yes | string | Unique ID, lowercase with hyphens (e.g., code-reviewer) |
description |
Yes | string | When Claude should use this agent. Include "proactively" to auto-trigger |
tools |
No | comma-separated | Tools allowed. Inherits all if omitted. Options: Read, Write, Edit, Bash, Grep, Glob, Task, Task(specific-agent), plus MCP tools |
disallowedTools |
No | comma-separated | Tools to deny (removed from inherited/specified list) |
model |
No | string | sonnet, opus, haiku, or inherit (default: inherit) |
permissionMode |
No | string | default, acceptEdits, dontAsk, bypassPermissions, plan |
maxTurns |
No | number | Max agentic turns before stopping |
skills |
No | list | Skills to preload into agent context |
mcpServers |
No | list | MCP servers to enable (by name or inline definition) |
hooks |
No | object | Lifecycle hooks scoped to this agent |
memory |
No | string | user, project, or local — enables persistent cross-session memory |
background |
No | boolean | true to always run as background task (default: false) |
isolation |
No | string | worktree for git worktree isolation |
Memory Scopes
| Scope | Storage Location | Use When |
|---|---|---|
user |
~/.claude/agent-memory/<agent-name>/ |
Knowledge applies across all projects |
project |
.claude/agent-memory/<agent-name>/ |
Knowledge is project-specific, shareable via git |
local |
.claude/agent-memory-local/<agent-name>/ |
Project-specific, NOT in version control |
When memory is enabled, the agent gets:
- Read/Write/Edit tools automatically enabled
- Instructions to maintain a
MEMORY.mdfile in its memory directory - First 200 lines of
MEMORY.mdinjected into context at startup
CLI-Defined Agents (Temporary)
For quick testing or automation, pass agents as JSON:
claude --agents '{
"code-reviewer": {
"description": "Expert code reviewer. Use proactively after code changes.",
"prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
"tools": ["Read", "Grep", "Glob", "Bash"],
"model": "sonnet"
},
"test-runner": {
"description": "Runs and validates test suites.",
"prompt": "You run tests and report results. Fix failing tests when possible.",
"tools": ["Read", "Edit", "Bash", "Grep", "Glob"],
"model": "haiku"
}
}'
Example Agent Files
Code Simplifier (Boris Cherny style)
---
name: code-simplifier
description: Simplifies and refines code for clarity, consistency, and maintainability while preserving all functionality. Use after implementation is complete.
tools: Read, Edit, Write, Grep, Glob
model: sonnet
---
You simplify code. Focus on recently modified files unless instructed otherwise.
Simplification rules:
- Remove dead code and unused imports
- Simplify complex conditionals
- Extract repeated patterns into functions
- Improve naming for clarity
- Reduce nesting depth
- Keep all functionality intact
Verify App (Boris Cherny style)
---
name: verify-app
description: Runs full verification suite — linting, type checking, tests, and build. Use before committing or creating PRs.
tools: Bash, Read, Grep
model: haiku
---
Run the full verification pipeline:
1. Lint: `npm run lint`
2. Type check: `npx tsc --noEmit`
3. Tests: `npm test`
4. Build: `npm run build`
Report results as:
- ✅ PASS or ❌ FAIL for each step
- Full error output for any failures
- Summary of what needs fixing
Database Reader (with hook validation)
---
name: db-reader
description: Execute read-only database queries for analysis and reporting.
tools: Bash
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-readonly-query.sh"
---
You are a database analyst with read-only access.
Execute SELECT queries only. If asked to modify data, explain you only have read access.
Disabling Specific Agents
In settings.json:
{
"permissions": {
"deny": ["Task(Explore)", "Task(my-custom-agent)"]
}
}
Or via CLI:
claude --disallowedTools "Task(Explore)"
5. tmux Fundamentals for Claude Code
What is tmux?
tmux is a terminal multiplexer — it lets you split your terminal into multiple panes, each running its own process. For Claude Code, this means each agent gets its own visible pane.
Install & Basic Setup
# Install
brew install tmux
# Start a new session
tmux new -s claude-swarm
# Verify it's running
tmux ls
Essential tmux Keybindings
All tmux commands start with the prefix key: Ctrl+b (press Ctrl+b, release, then the command key)
| Action | Keys | Description |
|---|---|---|
| Split horizontal | Ctrl+b " |
New pane below |
| Split vertical | Ctrl+b % |
New pane to the right |
| Navigate panes | Ctrl+b Arrow |
Move between panes |
| Resize pane | Ctrl+b Ctrl+Arrow |
Grow/shrink current pane |
| Zoom pane | Ctrl+b z |
Toggle fullscreen for current pane |
| Kill pane | Ctrl+b x |
Close current pane |
| Detach session | Ctrl+b d |
Leave session running in background |
| List sessions | tmux ls |
Show all sessions |
| Reattach | tmux attach -t claude-swarm |
Reconnect to session |
| Scroll mode | Ctrl+b [ |
Enter scroll mode (q to exit) |
Recommended tmux Configuration
Create or edit ~/.tmux.conf:
# Better prefix (Ctrl+a instead of Ctrl+b)
unbind C-b
set -g prefix C-a
bind C-a send-prefix
# Mouse support (click to select panes, scroll)
set -g mouse on
# Easier splits (| and - instead of % and ")
bind | split-window -h
bind - split-window -v
# Start window numbering at 1
set -g base-index 1
setw -g pane-base-index 1
# Larger scrollback buffer
set -g history-limit 50000
# Status bar with session info
set -g status-style 'bg=#333333 fg=#5eacd3'
set -g status-left '#[fg=green]Session: #S '
set -g status-right '#[fg=yellow]Panes: #{window_panes} '
# Pane border colors for visibility
set -g pane-border-style fg=colour240
set -g pane-active-border-style fg=green
# Don't rename windows automatically
set -g allow-rename off
# Reload config
bind r source-file ~/.tmux.conf \; display "Config reloaded!"
After editing, reload with:
tmux source-file ~/.tmux.conf
iTerm2 Control Mode
If using iTerm2, you can use tmux's control mode for native tab/pane integration:
tmux -CC new -s claude-swarm
This makes tmux panes appear as native iTerm2 split panes with full mouse support, native scrollback, and normal copy/paste.
Manual Multi-Pane Layout
For manually running parallel Claude instances (without the agent teams feature):
# Create a 4-pane layout
tmux new-session -s dev -d
tmux split-window -h
tmux split-window -v
tmux select-pane -t 0
tmux split-window -v
tmux attach -t dev
# Then in each pane, launch Claude with different tasks:
# Pane 0: claude "Implement the API endpoints for user auth"
# Pane 1: claude "Write unit tests for the auth module"
# Pane 2: claude "Update the README with API documentation"
# Pane 3: claude "Review and fix any linting issues"
6. Enabling Agent Teams
Set the Environment Variable
Agent Teams requires an experimental flag:
# For current session
export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1
# Permanent (add to ~/.zshrc or ~/.bashrc)
echo 'export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1' >> ~/.zshrc
source ~/.zshrc
Verify It's Enabled
# Start Claude and ask it to create a team
claude
> Create a team called "test-team" and verify agent teams are working
If agent teams aren't enabled, Claude won't have access to TeamCreate, SendMessage, or the other team primitives.
Configuration in Settings
You can also configure the display mode in .claude/settings.json:
{
"agentTeams": {
"displayMode": "tmux"
}
}
7. Display Modes: How Agents Appear
When Claude spawns teammate agents, they need somewhere to run. There are several display modes:
In-Process Mode (Default)
agentTeams.displayMode: "in-process"
- Teammates run as background processes
- Press
Shift+Down Arrowto cycle through agents and view their output - Simplest setup — no tmux required
- Best for: Quick tasks, testing, or when you don't need to watch agents work
tmux Mode
agentTeams.displayMode: "tmux"
- Each teammate gets its own tmux pane
- You can see all agents working simultaneously
- Requires tmux to be installed and Claude launched inside a tmux session
- Best for: Watching agents work in real-time, debugging coordination issues
How tmux Mode Works
- Start tmux:
tmux new -s swarm - Launch Claude inside tmux
- When Claude spawns teammates, each one appears in a new tmux split pane
- You can navigate between panes with
Ctrl+b Arrow - Each pane shows that agent's full output in real-time
Cycling Through Agents (In-Process Mode)
When using in-process mode:
Shift+Down Arrow— Show the next agent's output- The status line shows which agent you're viewing
- Agents continue working in the background regardless of which one you're viewing
8. Agent Team Architecture & Primitives
The 7 Core Primitives
Agent teams are built on seven fundamental tools:
1. TeamCreate
Creates a team with a shared task list.
TeamCreate({
team_name: "my-feature",
description: "Implementing user authentication"
})
- Creates
~/.claude/teams/my-feature/config.json - Creates
~/.claude/tasks/my-feature/directory
2. TaskCreate
Adds tasks to the team's shared backlog.
TaskCreate({
title: "Implement login API endpoint",
description: "Create POST /api/auth/login with JWT tokens",
priority: "high"
})
3. TaskUpdate
Updates task status, assigns owners, marks completion.
TaskUpdate({
task_id: "task-1",
status: "completed",
owner: "backend-dev"
})
4. TaskList
Views all tasks and their current status.
TaskList() // Returns all tasks with status, owner, etc.
5. Task (with team_name)
Spawns a new teammate agent.
Task({
prompt: "Implement the REST API for user authentication",
subagent_type: "general-purpose",
team_name: "my-feature",
name: "backend-dev"
})
6. SendMessage
Enables inter-agent communication.
SendMessage({
type: "message",
recipient: "backend-dev",
content: "The API schema has changed, please update endpoints",
summary: "API schema update notification"
})
Types:
message— Direct message to one agentbroadcast— Message to all agents (use sparingly, expensive)shutdown_request— Ask an agent to gracefully stopshutdown_response— Agent responds to shutdown request
7. TeamDelete
Cleans up team resources when work is complete.
TeamDelete() // Removes team config and task directories
Agent Lifecycle
1. TeamCreate → Creates team + task list
2. TaskCreate → Define work items
3. Task (spawn) → Create specialized agents
4. TaskUpdate → Assign tasks to agents
5. Agents work → Read/write code, run tests, etc.
6. SendMessage → Coordinate between agents
7. TaskUpdate → Mark tasks complete
8. SendMessage (shutdown_request) → Wind down agents
9. TeamDelete → Clean up
Team Config File
The team config lives at ~/.claude/teams/{team-name}/config.json:
{
"members": [
{
"name": "team-lead",
"agentId": "uuid-1",
"agentType": "general-purpose"
},
{
"name": "backend-dev",
"agentId": "uuid-2",
"agentType": "general-purpose"
},
{
"name": "tester",
"agentId": "uuid-3",
"agentType": "general-purpose"
}
]
}
9. Spawning & Managing Teams
Basic Team Spawn Pattern
Create a team called "auth-feature" with the following agents:
1. "architect" - Plans the implementation and reviews code
2. "backend-dev" - Implements API endpoints and database models
3. "frontend-dev" - Implements UI components and state management
4. "tester" - Writes and runs tests
Tasks:
1. Design auth system architecture (architect)
2. Implement JWT token service (backend-dev)
3. Create login/signup UI (frontend-dev)
4. Write integration tests (tester)
Available Agent Types for Teammates
| Agent Type | Tools Available | Best For |
|---|---|---|
general-purpose |
All tools (read, write, edit, bash, etc.) | Implementation work |
Explore |
Read-only (glob, grep, read) | Research, code exploration |
Plan |
Read-only | Architecture planning |
Bash |
Bash commands only | Running tests, builds |
Custom agents in .claude/agents/ |
As configured | Specialized roles |
Spawning with the Task Tool
// Spawn a backend developer
Task({
prompt: "Implement REST API endpoints for user authentication. Use Express.js with JWT tokens. Follow the patterns in src/routes/.",
subagent_type: "general-purpose",
team_name: "auth-feature",
name: "backend-dev",
mode: "bypassPermissions" // Optional: skip permission prompts
})
Important Agent Management Rules
- Agents go idle between turns — This is normal! Idle just means waiting for input.
- Send messages to wake idle agents — They'll resume processing.
- Always use agent names (not UUIDs) for messaging and task assignment.
- One task in_progress per agent at a time.
- Shut down gracefully — Use
shutdown_request, don't just kill processes. - Agents can't hear you unless you SendMessage — Your text output isn't visible to them.
The Orchestrator Pattern
The most effective pattern is having a team lead (usually the main Claude instance) that:
- Creates the team and task list
- Spawns specialized agents
- Assigns tasks
- Monitors progress
- Resolves conflicts
- Coordinates handoffs
- Shuts down agents when done
10. Prompting Strategies for Multi-Agent Work
The Golden Rule: Plan First, Parallelize Second
The #1 mistake is jumping straight into spawning agents. Instead:
- Plan the work in Plan Mode first — Understand what needs to be done
- Identify truly parallel tasks — Tasks that don't depend on each other
- Define clear boundaries — Each agent should own distinct files/directories
- Then spawn agents — With specific, detailed prompts
Writing Effective Agent Prompts
Bad Prompt:
"Work on the frontend"
Good Prompt:
"Implement the login form component at src/components/auth/LoginForm.tsx.
Requirements:
- Email and password fields with validation
- Submit button that calls POST /api/auth/login
- Error message display for invalid credentials
- Redirect to /dashboard on success
- Use the existing Button and Input components from src/components/ui/
- Follow the styling patterns in src/styles/auth.css
- Do NOT modify any files outside of src/components/auth/
When done, run: npm test -- --testPathPattern=auth"
Key Prompting Principles
- Be specific about file ownership — Tell each agent exactly which files/directories they own
- Include verification steps — "When done, run these tests..."
- Set boundaries — "Do NOT modify files outside of..."
- Provide context — Reference existing patterns, styles, conventions
- Define done — What does completion look like?
The RALF Loop (for Autonomous Execution)
For longer-running agent work, use the RALF pattern:
Read the prd.json file.
Implement the user stories one by one.
After each story:
1. Run the test suite
2. Fix any failures
3. Mark the story complete
4. Move to the next story
Always set max_iterations to prevent runaway execution.
Shared Context via CLAUDE.md
All agents in a team share the same CLAUDE.md files. Use this to:
# CLAUDE.md (project root)
## Team Conventions
- All API endpoints follow RESTful patterns
- Use TypeScript strict mode
- Tests go in __tests__/ directories next to source files
- Branch naming: feature/TICKET-description
- Commit messages: type(scope): description
## Current Sprint Context
- Working on: User Authentication (Sprint 14)
- API base URL: /api/v2
- Database: PostgreSQL with Prisma ORM
Context Isolation Strategy
For complex multi-agent work, store context in individual files rather than trying to maintain it across long conversations:
project/
.claude/
context/
architecture-decisions.md
api-schema.md
ui-components.md
test-strategy.md
Each agent reads only the context files relevant to their work, preventing "context rot" (degraded output quality as conversations grow long).
11. Swarm Patterns (What Works)
Pattern 1: Cross-Layer Feature Implementation
Use when: Building a feature that spans multiple layers (API, UI, tests, docs)
Team: "user-auth"
Agents:
- backend-dev: Implements API endpoints and DB models
- frontend-dev: Builds UI components and state management
- test-writer: Creates unit and integration tests
- doc-writer: Updates API docs and README
Task Dependencies:
1. backend-dev: Create API endpoints (no dependencies)
2. frontend-dev: Build login UI (depends on API schema, not implementation)
3. test-writer: Write tests (starts after backend, tests as code lands)
4. doc-writer: Update docs (starts after API design is stable)
Pattern 2: Competing Hypotheses (Bug Investigation)
Use when: A bug could have multiple causes and you want to investigate all of them simultaneously.
Team: "bug-hunt"
Agents:
- investigator-1: "Check if the issue is in the auth middleware"
- investigator-2: "Check if the issue is in the database query layer"
- investigator-3: "Check if the issue is in the frontend state management"
Each agent investigates independently and reports findings.
The team lead synthesizes results and identifies the root cause.
Pattern 3: Parallel Code Review
Use when: Reviewing a large codebase or many files at once.
Team: "code-review"
Agents:
- security-reviewer: Focus on auth, input validation, data exposure
- perf-reviewer: Focus on N+1 queries, memory leaks, bundle size
- style-reviewer: Focus on naming, patterns, consistency
- test-reviewer: Focus on test coverage, edge cases, flaky tests
Pattern 4: Migration / Large Refactor
Use when: Changing a pattern across many files.
Team: "migrate-to-v2"
Agents:
- migrator-1: Handle files in src/components/
- migrator-2: Handle files in src/pages/
- migrator-3: Handle files in src/utils/
- verifier: Run tests after each batch of changes
Key: Each agent owns a distinct directory — no file conflicts.
Pattern 5: Research + Implement
Use when: You need to research before implementing, but can parallelize both.
Team: "new-feature"
Agents:
- researcher (Explore type): Research existing patterns, find relevant code
- architect (Plan type): Design the implementation based on research
- implementer (general-purpose): Build once the plan is approved
- tester (general-purpose): Write tests based on the design
Pattern 6: Content Analysis Swarm
Use when: Analyzing large amounts of content (from perrotta.dev's real example).
Real-world example: 4 agents analyzed a 1,041-post blog in 5 minutes 17 seconds using ~239k tokens:
- Agent 1: Writing style analysis
- Agent 2: Topic categorization
- Agent 3: Engagement pattern analysis
- Agent 4: Content evolution over time
12. Anti-Patterns (What Doesn't Work)
Anti-Pattern 1: Too Many Agents
Problem: Spawning 10+ agents for a simple task. Why it fails: Coordination overhead exceeds parallelism benefits. More agents = more token cost. Rule of thumb: 2-5 agents is the sweet spot. Start with fewer and add more if needed.
Anti-Pattern 2: Agents Editing Same Files
Problem: Multiple agents modifying the same file simultaneously. Why it fails: Merge conflicts, lost changes, inconsistent state. Solution: Assign clear file ownership. Use git worktrees for true isolation.
Anti-Pattern 3: Vague Task Descriptions
Problem: "Work on the backend" or "Fix bugs" Why it fails: Agents don't know where to start, overlap with each other, or miss requirements. Solution: Specific files, specific requirements, specific verification steps.
Anti-Pattern 4: No Verification Step
Problem: Agents mark tasks "done" without running tests. Why it fails: Broken code accumulates, integration failures compound. Solution: Every task prompt should end with "verify by running..."
Anti-Pattern 5: Broadcasting Everything
Problem: Using broadcast messages for all communication.
Why it fails: Each broadcast sends N messages (one per agent). Expensive and noisy.
Solution: Use direct message to specific agents. Reserve broadcast for critical team-wide updates.
Anti-Pattern 6: No Central Coordinator
Problem: Spawning agents and letting them figure things out. Why it fails: No one resolves conflicts, manages dependencies, or handles integration. Solution: Always have a team lead that orchestrates the work.
Anti-Pattern 7: Skipping the Planning Phase
Problem: Immediately spawning agents without understanding the codebase. Why it fails: Agents work on the wrong things, create incompatible implementations. Solution: Plan Mode first. Understand the codebase. Define tasks. Then parallelize.
13. Real-World Examples
Example 1: Blog Analysis Swarm (from perrotta.dev)
Task: Analyze 1,041 blog posts for patterns, style, and insights.
Setup:
Team: "blog-analysis"
4 agents, each analyzing a different dimension:
- style-analyst: Writing style, tone, sentence structure
- topic-analyst: Subject categorization, theme evolution
- engagement-analyst: Reader engagement patterns
- evolution-analyst: How content changed over time
Results:
- Runtime: 5 minutes 17 seconds
- Token usage: ~239,000 tokens
- Each agent produced a focused report
- Team lead synthesized into comprehensive analysis
Example 2: Kieran Klaassen's Orchestration Skill
Kieran created a reusable orchestration skill (.claude/skills/swarm-orchestration/SKILL.md) that provides a template for agent team management:
Key Elements:
- Spawn methods:
Tasktool withteam_nameandname - 3 built-in agent types:
Explore(read-only),Plan(read-only),general-purpose(full access) - Custom agents from
.claude/agents/directory - Messaging via
SendMessagewithmessage,broadcast,shutdown_requesttypes - Task management via
TaskCreate,TaskUpdate,TaskList - Full lifecycle: TeamCreate -> spawn -> assign -> work -> shutdown -> TeamDelete
Example 3: Cross-Layer Feature (from Addy Osmani)
Task: Add user notifications feature across the full stack.
Team: "notifications"
- api-dev: POST/GET /notifications endpoints, WebSocket setup
- ui-dev: NotificationBell component, notification drawer
- db-dev: Notifications table, migration, indexes
- test-dev: E2E tests, unit tests, load tests
Coordination:
- api-dev and db-dev start in parallel (API uses mock data initially)
- ui-dev starts with API schema (not implementation)
- test-dev writes tests based on specs, fills in real calls as code lands
- Team lead integrates and runs full test suite
14. Boris Cherny's Parallel Workflow
Boris Cherny (Engineer at Anthropic who works on Claude Code) runs one of the most productive parallel Claude workflows publicly documented.
His Setup
- Terminal: Ghostty (fast, minimal, color-coded tabs)
- Instances: 5 parallel Claude Code terminal sessions + 5-10 web Claude.ai sessions
- Model: Opus 4.5 with extended thinking for everything
- Voice Input: macOS dictation (Fn Fn) for faster prompting
Key Practices
Color-coded terminal tabs — Each Claude instance gets a different tab color so he can quickly identify which is which at a glance
Shared CLAUDE.md — All instances share the same project CLAUDE.md, so they follow the same conventions
Slash commands for repetitive tasks:
/commit-push-pr — Commits, pushes, and creates a PR in one stepCustom sub-agents:
code-simplifier— Simplifies code after implementationverify-app— Runs the full verification suite
/permissionspattern — He uses/permissionsto set Bash(execute:*) so Claude can run any command without asking for permission each timePlan Mode for PRs — Goes back and forth with Claude in Plan Mode until the plan is solid, then switches to implementation
No amending commits — Prefers clean sequential commits over amending, making it easy to review changes
His Workflow Loop
1. Start 5 Claude terminals (color-coded)
2. Open Plan Mode in each with a different task
3. Review and approve each plan
4. Let all 5 implement in parallel
5. Review PRs as they come in
6. Use code-simplifier sub-agent for cleanup
7. Run verify-app before merging
Adapting Boris's Workflow Without Agent Teams
You don't need the experimental agent teams feature to run parallel Claudes. Boris's approach works with plain tmux:
# Create a 5-pane layout
tmux new-session -s work -d
tmux split-window -h
tmux split-window -v
tmux select-pane -t 0
tmux split-window -v
tmux select-pane -t 2
tmux split-window -v
tmux attach -t work
# In each pane, start Claude with a specific task
# The panes are independent — no shared task list or messaging
# You manually coordinate by reading each pane's output
15. Git Worktrees for Isolation
The Problem
Multiple Claude agents editing the same git working directory can cause:
- Merge conflicts
- Inconsistent file states
- Lost changes when agents overwrite each other
The Solution: Git Worktrees
Git worktrees let you have multiple working directories sharing the same repository history:
# Claude Code has built-in worktree support
claude -w feature-auth # Creates worktree and starts Claude in it
claude -w feature-tests # Another isolated worktree
claude -w feature-docs # Yet another
How It Works
my-project/ (main worktree)
my-project-feature-auth/ (worktree for auth work)
my-project-feature-tests/(worktree for test work)
my-project-feature-docs/ (worktree for docs)
Each worktree:
- Has its own branch
- Has its own working directory
- Shares the same
.githistory - Can be modified independently without conflicts
Combining Worktrees with tmux
# Terminal 1 (tmux pane 1)
claude -w auth-api "Implement the authentication API"
# Terminal 2 (tmux pane 2)
claude -w auth-ui "Build the login/signup UI"
# Terminal 3 (tmux pane 3)
claude -w auth-tests "Write comprehensive auth tests"
# When all done, merge worktree branches into main
Worktree Cleanup
# When done with a worktree
cd my-project
git worktree remove my-project-feature-auth
git branch -d feature-auth # if branch was merged
16. Cost Management
Understanding the Cost Multiplication
Running N agents means roughly N times the token cost:
| Agents | Approximate Cost Multiplier | Notes |
|---|---|---|
| 1 (solo) | 1x | Baseline |
| 2 | 2-2.5x | Coordination overhead |
| 3 | 3-4x | More coordination messages |
| 5 | 5-8x | Significant overhead |
Real Cost Data (from alexop.dev)
A 5-person team experiment showed:
- ~800,000 tokens consumed (vs ~200,000 for solo)
- 4x cost for roughly 2-3x speed improvement
- Coordination tokens are "overhead" that don't directly produce code
Cost Optimization Strategies
Use cheaper models for simple agents
Task({ model: "haiku", // Use Haiku for simple tasks subagent_type: "general-purpose", prompt: "Update all copyright headers to 2026" })Use Explore/Plan agents for research — They're read-only and produce fewer tokens than general-purpose agents
Minimize broadcasts — Each broadcast sends N messages. Use direct messages instead.
Set max_turns on agents — Prevent runaway execution:
Task({ max_turns: 20, // Stop after 20 turns prompt: "..." })Kill idle agents — Don't leave agents running if they're not needed
Start small — Begin with 2 agents and scale up only if there's clear parallelism benefit
When the Cost is Worth It
- Time-critical features with clear parallelism
- Large migrations that would take hours sequentially
- Multi-layer features where agents never touch the same files
- Research tasks where multiple hypotheses should be explored simultaneously
17. Notification Hooks
Get Notified When Agents Finish
Set up hooks in .claude/settings.json to get notifications:
{
"hooks": {
"Stop": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "osascript -e 'display notification \"Claude finished a task\" with title \"Claude Code\"'"
}
]
}
]
}
}
Terminal Bell Notification
{
"hooks": {
"Stop": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "echo -e '\\a'"
}
]
}
]
}
}
Custom Sound Notification
{
"hooks": {
"Stop": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "afplay /System/Library/Sounds/Glass.aiff"
}
]
}
]
}
}
Combining with tmux Alerts
tmux can also notify you when output changes in a pane:
# In tmux, set monitoring for a pane
# Ctrl+b : (enter command mode)
setw monitor-activity on
set -g visual-activity on
This will highlight the pane in your status bar when new output appears — useful for knowing when an agent has completed its work.
18. Troubleshooting
"Agent teams not available"
- Fix: Set the environment variable:
export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 - Make sure you're on the latest Claude Code version
Agents can't see each other's changes
- Cause: Agents are editing the same file simultaneously
- Fix: Assign distinct files/directories to each agent, or use git worktrees
tmux panes not appearing
- Fix: Make sure Claude was launched inside a tmux session
- Fix: Set display mode to tmux:
{ "agentTeams": { "displayMode": "tmux" } }
Agent stuck / not responding
- Fix: The agent might be idle (normal). Send it a message:
SendMessage({ type: "message", recipient: "agent-name", content: "Status update?", summary: "Checking status" })
High token usage
- Fix: Reduce number of agents, use
haikumodel for simple tasks - Fix: Set
max_turnsto limit agent execution - Fix: Replace
broadcastwith directmessage
Agents conflicting on same files
- Fix: Use git worktrees (
claude -w <name>) - Fix: Assign clear file ownership in prompts
- Fix: Use a coordinator agent to manage merge conflicts
Team resources not cleaning up
- Fix: Always call TeamDelete when done
- Manual cleanup:
rm -rf ~/.claude/teams/<team-name> rm -rf ~/.claude/tasks/<team-name>
19. Quick Reference Cheatsheet
Environment Setup
# Enable agent teams
export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1
# Start tmux
tmux new -s swarm
# Start Claude in worktree
claude -w feature-name
# Start Claude with auto-accept
claude --dangerously-skip-permissions
tmux Essential Commands
Ctrl+b " — Split horizontal
Ctrl+b % — Split vertical
Ctrl+b Arrow — Navigate panes
Ctrl+b z — Zoom/unzoom pane
Ctrl+b d — Detach (keeps running)
tmux a -t s — Reattach to session 's'
Agent Team Lifecycle
1. TeamCreate("my-team")
2. TaskCreate(title, description)
3. Task(prompt, team_name, name) — Spawn agent
4. TaskUpdate(task_id, owner) — Assign work
5. SendMessage(recipient, content) — Coordinate
6. TaskUpdate(task_id, "completed") — Mark done
7. SendMessage(shutdown_request) — Wind down
8. TeamDelete() — Clean up
Display Mode Toggle
In-Process: Shift+Down Arrow to cycle agents
tmux: Each agent gets its own pane
Prompting Template for Agents
Role: [What this agent does]
Files owned: [Specific files/directories]
Requirements:
1. [Specific requirement]
2. [Specific requirement]
3. [Specific requirement]
Boundaries: Do NOT modify [files outside scope]
Verification: When done, run [specific test command]
Cost Rules of Thumb
2-3 agents: Sweet spot for most tasks
4-5 agents: Only for clearly parallel work
6+ agents: Rarely worth the coordination cost
Use haiku for simple agents
Set max_turns to prevent runaway execution
Direct message > broadcast (always)
20. Sources
Official Documentation
- Claude Code Agent Teams — Official experimental feature docs
- Claude Code Common Workflows — Git worktrees, parallel sessions
- Claude Code Best Practices — Planning, prompting, verification
- Claude Code Sub-Agents — Creating specialized agents
- Claude Code Hooks — Notification and automation hooks
- Claude Code MCP — Model Context Protocol integration
Community Guides & Blog Posts
- Addy Osmani: Claude Code Swarms — Swarm patterns and anti-patterns
- Kieran Klaassen: Swarm Orchestration Skill — Reusable orchestration skill template
- Alex Op: From Tasks to Swarms — Cost analysis and practical tips
- Perrotta.dev: Claude Code Swarm Mode — Real-world 4-agent blog analysis example
- How Boris Uses Claude Code — Boris Cherny's full workflow
- Simon Scrapes: 7 Levels of Claude Code — Comprehensive framework video
Tools & Terminals
- tmux — Terminal multiplexer
- iTerm2 — macOS terminal with native tmux integration
- Ghostty — Fast terminal (Boris Cherny's choice)
- yt-dlp — YouTube caption extraction
Last Updated: 2026-02-20 Compiled from official Anthropic documentation and community best practices