architecture

Agent Swarms: Architecture Breakdown

How multi-agent swarms coordinate work in Claude Code. Roles, handoffs, locks, and the tracking layer that keeps a 6-mode pipeline coherent.

12 min read·
// agent orchestration

One prompt. N agents. Done in parallel.

Stop running tasks one by one. Spawn a swarm of agents, each tackling a piece of the problem simultaneously. Orchestrate, fan out, collect results. This is how you scale intelligence without scaling effort.

6
Swarm Patterns
10x
Throughput
0
Manual Coordination

The Problem They Solve

Single-agent Claude Code is sequential by default: one task finishes before the next begins. That's fine for a 3-step pipeline, but catastrophic when you have 50 files to migrate, 12 client reports to write, or 8 competitors to research. The wall-clock time scales linearly with the number of tasks.

Agent swarms break that constraint. An orchestrator fans work out to N independent worker agents that run in parallel. Token cost stays the same (you pay per task either way), but wall-clock time collapses from items × duration to max(duration).

Subagent
1:1 delegation
  • Reports to 1 parent agent
  • Isolated context per task
  • Sequential or parallel execution
  • Parent controls scope and prompt
  • Best for: discrete, bounded tasks
Swarm
1:N fan-out
  • N workers spawned simultaneously
  • Orchestrator coordinates all
  • Fan-out pattern with result collection
  • Workers are independent, no peer comms
  • Best for: parallel bulk work
Agent Team
N:N collaboration
  • Full sessions per agent
  • Peer-to-peer communication
  • Shared or partitioned context
  • Experimental, harder to control
  • Best for: complex multi-step projects
Section 02

The 6 Swarm Patterns

Click each pattern to expand. Every pattern includes a description, flow, example, and runnable bash code.

Section 03

The /batch Skill

A custom Claude Code skill for swarm orchestration. One command decomposes, plans, spawns, and manages parallel agents for you. No bash scripting required. (This is an AY-authored skill, not a native Claude Code built-in.)

/batch migrate all React class components to functional in src/
01
Decompose
Automatically scans the codebase and identifies all units of work (files, components, modules)
02
Plan
Presents the full plan for your approval: which files, what changes, estimated scope per unit
03
Spawn
One agent per unit, each in its own git worktree. No conflicts, no merge issues, full isolation
04
Execute
All agents run in parallel. Each makes its changes, runs tests, validates output independently
05
Deliver
Each agent opens a PR. 20 PRs in parallel, clean diffs, ready for your review. You just approve.
# What /batch does under the hood:

# 1. Scan and decompose
files=$(find src/ -name "*.tsx" -exec grep -l "extends React.Component" {} \;)

# 2. Present plan (you approve)
# "Found 20 class components. Migrate each to functional + hooks."
# [approve / modify / cancel]

# 3. Spawn agents in isolated worktrees
for f in $files; do
  # Each agent gets its own git worktree
  git worktree add "/tmp/batch-$(basename $f)" -b "batch/migrate-$(basename $f)"

  claude --worktree "/tmp/batch-$(basename $f)" \
    "Convert $f from class component to functional.
    Replace lifecycle methods with hooks.
    Run tests. Open PR when done." &
done

wait
# Result: 20 PRs ready for review

Handoff Patterns & Locks

A multi-agent pipeline needs a coordination layer; otherwise agents stomp on each other's work. In Claude Code's 6-mode pipeline (PLAN → BUILD → REVIEW → QA → SHIP → RETRO), each mode hands off to the next via a shared tracking file and an exclusive lock.

HANDOFFS.md

A machine-readable file at the repo root that records the current pipeline mode, the active task ID, and the agent that holds the lock. Every mode transition writes an entry. If an agent crashes, the next agent reads the last entry and knows exactly where to resume.

.lock / flock

Before writing to a shared output (HANDOFFS.md, a results file), an agent acquires an exclusive lock via flock -x .agent.lock. Only one agent can hold the lock at a time. After writing, the lock is released. This prevents race conditions in fan-out patterns.

The 6-Mode Pipeline
PLAN
BUILD
REVIEW
QA
SHIP
RETRO
PLANOrchestrator decomposes the task, locks HANDOFFS.md, writes task list
BUILDWorker agents fan out, one per task unit, each in an isolated worktree
REVIEWFresh-eyes critic agent reads all diffs and outputs a structured review JSON
QATest runner agent executes the suite, reports failures back to BUILD if needed
SHIPMerge agent combines worktrees, runs final checks, opens PRs or deploys
RETROSummary agent reads HANDOFFS.md end-to-end and writes a session learning

Concrete Example: 12 Client Reports in 2 Minutes

You manage 12 active clients. Every Friday you need a status report per client: blockers, wins, next actions, and a health score. Sequentially that's 12 × ~2 min = 24 minutes of waiting. With a fan-out swarm it takes 2 minutes regardless of how many clients you have.

#!/bin/bash
# Weekly client reports - fan-out swarm

clients=$(ls 01_Projects/Clients/Active/)
count=0

for client in $clients; do
  claude -p "Read all files in 01_Projects/Clients/Active/$client/.
  Generate a Friday status report:
    - Health score (1-10)
    - Top 3 blockers
    - Wins this week
    - Next 3 actions
  Return as JSON: {client, health, blockers:[], wins:[], actions:[]}" > "reports/${client}.json" &

  count=$((count + 1))
done

wait  # all 12 agents finish in parallel
echo "Generated $count client reports"

# Reduce: executive summary
claude "Read all reports/*.json.
Create an executive summary:
- Flag any client with health < 7
- List all blockers that need my attention
- Suggest my top 3 priorities for next week
Save to WEEKLY-SUMMARY.md"
Section 05

Real Use Cases

Patterns deployed in production. Real numbers, real workflows.

Mass JS → TS Migration

200 JavaScript files converted to TypeScript with full type annotations. One agent per file, all running in parallel. Types inferred from usage patterns, imports rewritten, tests updated.

fan-out200 files20 min total
Competitive Analysis

One agent per competitor. Each researches pricing, features, positioning, reviews, tech stack. All results merged into a single comparison matrix with scoring and recommendations.

mapreduce8 competitorsmerged report
Multi-Language Translation

Marketing copy translated into 10 languages simultaneously. Each agent is prompted with language-specific cultural context and terminology. Native-quality output, not machine translation.

fan-out10 languagesparallel
Client Weekly Reports

One agent per client reads their project folder, communication log, and progress file. Generates a formatted weekly report with blockers, wins, and next actions. 12 reports at once.

fan-out12 clients12 reports

Common Pitfalls

!
Shared mutable state

Agents that write to the same file simultaneously will clobber each other. Either give each agent its own output path and merge in a reduce step, or serialise writes with a lock file.

!
Unbounded concurrency

Spawning 200 agents at once will hit API rate limits and exhaust memory. Always add a MAX_PARALLEL guard and wait every N jobs.

!
No stopping condition in loops

Writer + Critic loops can run forever if the critic keeps finding issues. Set MAX_ITERATIONS and break on APPROVED. Without this, your swarm becomes an infinite bill.

!
Using a swarm when a pipeline is enough

If your tasks are inherently sequential, each depending on the previous, fan-out adds zero speed. Use the Pipeline pattern instead.

!
Missing the reduce step

Raw agent outputs (20 JSON files) are not useful on their own. Always include a reduce agent that merges, scores, and surfaces the insight from all parallel work.

When NOT to Use a Swarm

Swarms add orchestration overhead and complexity. They are the right tool only when tasks are genuinely parallelisable and numerous enough to justify the setup. Skip swarms when:

  • ×Tasks that depend on each other's output (use Pipeline instead)
  • ×Fewer than 3 items; sequential is simpler and easier to debug
  • ×Tasks that require real-time peer communication between agents
  • ×When you need deterministic, reproducible output on every run
  • ×Tightly rate-limited APIs where parallel calls will be throttled anyway

Want to build production agent swarms for your team? See our AI agent development service or read the best multi-agent frameworks guide for a wider comparison. For how hooks coordinate agent handoffs, see Advanced Hooks.

TL;DR

Fan-Out: same prompt, different inputs, parallel. Best for bulk generation.

MapReduce: map agent per item, reduce into a single report. Best for analysis at scale.

Pipeline: specialist agents in sequence, output feeds next. Best for multi-stage workflows.

Competing Hypotheses: multiple agents, different assumptions, best evidence wins. Best for hard debugging.

Writer + Critic: iterative improvement loop with a fresh-eyes reviewer. Best for quality-sensitive output.

Bash Loop Swarm: brute force fan-out via & and wait. Best for mass file operations.

Want this running in your stack?

AY Automate builds agent systems, RAG pipelines, and Claude Code setups for production teams.