
Ia Orchestrating Swarms
- 3 installs
- 28 repo stars
- Updated August 5, 2026
- iliaal/whetstone
Coordinates multi-agent swarms with teams, tasks, inboxes, and dependency graphs for parallel and pipeline workflows using subagents.
About
A skill for orchestrating multi-agent swarms, covering agent/team/task primitives, dispatch discipline, one-owner-per-file rules, and resilience patterns. A developer uses it when running parallel reviews, pipeline workflows, or divide-and-conquer subagent patterns.
- Subagent vs teammate spawn model with shared task lists
- Dispatch discipline, anti-sycophancy, and cascade-prevention patterns
Ia Orchestrating Swarms by the numbers
- 3 all-time installs (skills.sh)
- Ranked #13,677 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/iliaal/whetstone --skill ia-orchestrating-swarmsAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 3 |
|---|---|
| repo stars | ★ 28 |
| Last updated | August 5, 2026 |
| Repository | iliaal/whetstone ↗ |
What it does
Coordinates multi-agent swarms with teams, tasks, inboxes, and dependency graphs for parallel and pipeline workflows using subagents.
Files
Swarm orchestration
Primitives
Agents, teams, teammates, leaders, tasks, inboxes, messages, backends — see primitives.md for definitions and the file-system layout.
---
Two Ways to Spawn Agents
| Aspect | Task (subagent) | Task + team_name + name (teammate) |
|---|---|---|
| Lifespan | Until task complete | Until shutdown requested |
| Communication | Return value | Inbox messages |
| Task access | None | Shared task list |
| Team membership | No | Yes |
| Coordination | One-off | Ongoing |
| Best for | Searches, analysis, focused work | Parallel work, pipelines, collaboration |
Subagent (short-lived, returns result):
Task({ subagent_type: "Explore", description: "Find auth files", prompt: "..." })Teammate (persistent, communicates via inbox):
Teammate({ operation: "spawnTeam", team_name: "my-project" })
Task({ team_name: "my-project", name: "worker", subagent_type: "general-purpose",
prompt: "...", run_in_background: true })For detailed agent type descriptions, see agent-types.md.
Parallel Fan-Out (for independent work)
When dispatching multiple read-only or worktree-isolated agents whose work is independent, issue all Task calls in a SINGLE assistant message. Sequential dispatch across separate messages serializes what should run concurrently. Opus 4.7 does not parallelize by default -- state it explicitly.
// Correct: one message, multiple Task tool uses
Task({ subagent_type: "security-sentinel", ... })
Task({ subagent_type: "performance-oracle", ... })
Task({ subagent_type: "architecture-strategist", ... })Sequential dispatch (each Task in its own message, waiting on the previous to return) is a serialization bug, not a coordination pattern. If agents truly depend on each other's output, that is a pipeline -- see Coordination Models below.
Bounded parallelism when the harness caps active subagents. Single-message fan-out (above) tells Opus to dispatch in parallel; the harness then decides how many to run concurrently. When the harness accepts the dispatch but caps active execution, queue the overflow rather than failing. Dispatch as many as the harness accepts in the first batch, treat transient capacity-related spawn errors as backpressure (any retryable error indicating the limiter rejected the dispatch — exact wording varies across harness versions and platforms; do not pattern-match on a fixed string list), and re-dispatch queued agents as active ones complete. Record an agent as failed only after a successful dispatch times out or returns an error, or when dispatch fails for a non-capacity reason (bad tool name, malformed prompt, missing permission). The fan-out is still parallel — it is just rate-capped to whatever the harness can run concurrently.
---
Quick Reference
For copy-paste spawn/message/task/shutdown snippets, load quick-reference.md.
---
Dispatch Discipline
Rules for when and how to dispatch agents. Getting these wrong wastes tokens and creates hard-to-debug failures.
When to dispatch a team vs. do it yourself:
Assess 5 signals: file count, module span, dependency chain, risk surface, parallelism potential. If 3+ fall in the "complex" column, dispatch a team. Below 3, do it yourself. When in doubt, prefer the simple path -- team overhead is only justified when parallelism provides a real speedup.
Task description template (for every dispatched task):
Every task prompt must include these fields to prevent integration failures:
- Objective: what to accomplish (one sentence)
- Owned Files: files this agent creates or modifies (exclusive -- no file assigned to multiple agents)
- Interface Contracts: what to import from other agents' work, what to export for downstream agents
- Acceptance Criteria: how the agent knows the task is correct
- Out of Scope: what NOT to touch, even if it looks related
Cardinal rule: one owner per file. When files must be shared, designate a single owner; other agents send change requests, owner applies sequentially. If an upstream dependency isn't ready yet, write a stub/mock so downstream work can continue unblocked.
No parallel implementation agents (without worktrees):
Implementation agents share state via git by default, so parallel dispatch causes overwrites. Use isolation: "worktree" to give each agent its own copy. Without worktrees, dispatch implementation agents sequentially. Review, research, and analysis agents are always safe to parallelize (read-only).
Pre-dispatch file-intersection check -- operationalize the one-owner-per-file rule with a runnable safety gate before every parallel dispatch:
1. Collect each unit's declared Owned Files / Test Paths / Modify Paths from its task spec. 2. Build a {file → unit} map. If any file appears under more than one unit, the dispatch is unsafe. Quick check on Markdown task specs:
grep -h "^Owned Files:" -A 20 tasks/*.md | grep -v "^Owned Files:" | grep -v "^--$" | sort | uniq -dAny output is an overlapping file path that needs resolution. 3. On overlap: either downgrade to serial (log the overlap and the reason), or assign worktree isolation (isolation: "worktree" per agent), or rewrite unit boundaries so files become exclusive. 4. Even with no declared overlap, include this constraint verbatim in every parallel-dispatch prompt: "Do not run `git add`, `git commit`, or the project's test suite while other parallel agents are active -- you'd race on the git index or thrash the test cache. Stage changes for the orchestrator to commit after integration."
The intersection check catches silent conflicts the controller misses at plan time; the dispatch-prompt constraint catches them when a unit's file list was incomplete.
Preset team compositions: Start from a named preset before designing a custom team. See team-compositions.md for the full table (Review / Debug / Feature / Fullstack / Migration / Security / Research), the cardinal subagent_type rule (read-only agents cannot implement), and custom-team guidelines. Use the smallest preset that covers all required dimensions — overlap between reviewers is a sizing signal to redefine focus areas, not add more agents.
Model selection by task complexity:
| Task shape | Model |
|---|---|
| 1-2 files, clear spec, mechanical | model: "haiku" |
| Multi-file integration, standard complexity | Default model |
| Architecture decisions, ambiguous scope, review | model: "opus" |
Handoff protocol -- structured agent-to-agent transfers:
When passing work between agents (leader→implementer, implementer→reviewer, reviewer→leader), include: 1. Context: what was done, relevant files, constraints discovered 2. Deliverable: specific output expected from the receiving agent 3. Acceptance criteria: how the receiving agent knows the work is correct
The controller reads all tasks from the plan upfront and provides full task text directly to subagents. Never make subagents read plan files themselves -- they waste tokens navigating, may read different versions, and inherit unclear context. Paste the task content into the prompt. See handoff-templates.md for QA FAIL and Escalation Report formats.
Standardize implementer status signals:
Include the four statuses defined in ia-verification-before-completion (DONE, DONE_WITH_CONCERNS, BLOCKED, NEEDS_CONTEXT) in every teammate prompt so they know the reporting format. Expect teammates to report one. BLOCKED responses get further triage via the decision tree below.
BLOCKED triage decision tree -- when a teammate reports BLOCKED, classify the root cause before acting. Never retry the same prompt on the same model without changing a variable.
| Root cause | Signal | Response |
|---|---|---|
| Missing context | Agent asked for a file, spec, or decision it needed | Provide the missing context, re-dispatch same agent |
| Reasoning ceiling | Agent attempted, got stuck on a subtlety it cannot resolve | Escalate model (haiku → sonnet → opus) and re-dispatch |
| Task too large | Agent made partial progress but hit token/complexity limits | Split into smaller tasks with explicit interface contracts |
| Spec wrong | Agent surfaces a contradiction in the plan or a missing requirement | Escalate to the user -- do not re-dispatch |
Never ignore an escalation. Never force the same agent to retry without changing at least one variable (context, model, or task scope).
Two-stage review gate on subagent outputs:
Verify spec compliance first: does the output match what was requested? Only then evaluate quality. A beautifully written solution to the wrong problem is still wrong. Structure review as two explicit passes -- pass 1 rejects on spec mismatch without reading further, pass 2 assesses correctness and quality on spec-compliant outputs.
QA retry loop:
Max 3 attempts per task. After each QA failure, pass structured feedback to the implementer using the QA FAIL template. After 3 failures, mark the task as blocked, continue the pipeline (don't halt everything), and let final integration catch remaining issues. Counter resets when advancing to the next task.
---
Integration Rules
Post-integration verification -- after all agents return: check overlapping file edits, review for conflicting approaches, run full test suite.
Spawned-session behavior -- when a skill runs inside an orchestrated pipeline (as a subagent, not user-invoked), suppress interactive prompts: do not use AskUserQuestion, auto-choose the conservative/safe default, skip upgrade checks and telemetry. Focus on completing the task and reporting results via prose output. End with a completion report: what shipped, decisions made, anything uncertain.
Decision presentation -- never silently drop options. When the orchestrator surfaces a user-facing choice (team composition, an escalation path, a spec-wrong fork) via AskUserQuestion and the choice carries more than four viable options -- the tool's per-question cap -- split it into sequential rounds (D1.1, D1.2, ...) rather than truncating to the first four. Truncation hides viable choices the user never sees and silently narrows their decision space. Surface any cross-option dependency inline in the round that introduces it. (In spawned sessions, the rule above takes precedence: don't ask at all -- auto-pick the safe default.)
---
Context Carry-Forward
After each turn, five strategies exist for moving context forward: Continue, Rewind, /compact, Subagent, /clear+brief. Choose deliberately — the default "Continue" is rarely best, and Rewind is strictly better than "correcting in place" after a failed attempt. See context-carry-forward.md for the full decision table and rationale.
Coordination Models
Two approaches to multi-agent coordination exist. Choose based on the work pattern:
| Aspect | Stateless (copy-paste outputs) | Stateful (file ownership + dependencies) |
|---|---|---|
| How agents share state | Leader copies full outputs between prompts | Agents read/write shared task files, claim ownership |
| Best for | Short pipelines, 2-3 agents, sequential handoffs | Parallel work, 4+ agents, complex dependency graphs |
| Failure mode | Context grows linearly with agent count | Concurrent modification conflicts |
| Mitigation | Summarize before passing (keep essentials, drop navigation) | Use worktrees or exclusive file ownership per agent |
For most work, start with stateless handoffs. Graduate to stateful coordination only when parallelism provides a real speedup and you have worktree isolation to prevent file conflicts.
---
Dispatch Anti-Patterns
Before designing any multi-agent workflow, check it against the four named failure modes in dispatch-anti-patterns.md: router persona, persona calls persona, sequential paraphraser, deep persona trees. Rule of thumb: if the proposed swarm has more coordinator roles than worker roles, collapse it.
Anti-Sycophancy and Resilience
When dispatching judge panels, running parallel reviewers, or iterating on subjective evaluations, load anti-sycophancy.md — cold-start isolation, fresh instances per round, label randomization, convergence detection.
When designing multi-agent workflows that must survive partial failure, load resilience-patterns.md — cascade prevention (timeouts, circuit breakers, bulkheads), failure classification (retry vs reassign vs escalate), mid-pipeline compensation for irreversible side effects, post-failure synthesis of partial results.
Verify
- All tasks in terminal state (completed or blocked)
- No orphaned teammates (
git worktree listshows no stale entries) - Overlapping file edits reviewed and merged
- Full test suite passes post-integration
References
| Document | When to load | What it covers |
|---|---|---|
| team-compositions.md | Sizing a team or choosing a preset | 7 preset compositions, subagent_type cardinal rule, custom-team guidelines |
| agent-types.md | Choosing which agent to spawn | Built-in and plugin agent types with examples |
| teammate-operations.md | Using TeammateTool for persistent agents | All 13 operations (spawnTeam, write, broadcast, requestShutdown, etc.) |
| task-system.md | Managing work items and dependencies | TaskCreate, TaskList, TaskGet, TaskUpdate, file structure |
| message-formats.md | Sending structured messages between agents | All JSON message examples (regular, shutdown, idle, plan approval) |
| orchestration-patterns.md | Designing a multi-agent workflow | 6 patterns + 3 complete workflow examples |
| spawn-backends.md | Troubleshooting agent spawn issues | Backend comparison, auto-detection, in-process/tmux/iterm2 |
| environment-config.md | Configuring team environment | Environment variables and team config structure |
| handoff-templates.md | Passing work between agents | QA FAIL and Escalation Report formats |
| context-carry-forward.md | Long sessions with orchestrated subagents | Continue / Rewind / compact / Subagent / clear+brief decision table |
| anti-sycophancy.md | Judge panels, parallel reviewers, subjective evals | Cold-start isolation, fresh instances per round, label randomization, convergence detection |
| resilience-patterns.md | Designing workflows that survive partial failure | Cascade prevention, failure classification, mid-pipeline compensation, post-failure synthesis |
Agent Types
When to read: when picking which agent type to spawn for a swarm role and weighing built-in vs plugin-defined options.
Built-in Agent Types
These are always available without plugins:
Bash
Task({
subagent_type: "Bash",
description: "Run git commands",
prompt: "Check git status and show recent commits"
})- Tools: Bash only
- Model: Inherits from parent
- Best for: Git operations, command execution, system tasks
Explore
Task({
subagent_type: "Explore",
description: "Find API endpoints",
prompt: "Find all API endpoints in this codebase. Be very thorough.",
model: "haiku" // Fast and cheap
})- Tools: All read-only tools (no Edit, Write, NotebookEdit, Task)
- Model: Haiku (optimized for speed)
- Best for: Codebase exploration, file searches, code understanding
- Thoroughness levels: "quick", "medium", "very thorough"
Plan
Task({
subagent_type: "Plan",
description: "Design auth system",
prompt: "Create an implementation plan for adding OAuth2 authentication"
})- Tools: All read-only tools
- Model: Inherits from parent
- Best for: Architecture planning, implementation strategies
general-purpose
Task({
subagent_type: "general-purpose",
description: "Research and implement",
prompt: "Research React Query best practices and implement caching for the user API"
})- Tools: All tools (*)
- Model: Inherits from parent
- Best for: Multi-step tasks, research + action combinations
claude-code-guide
Task({
subagent_type: "claude-code-guide",
description: "Help with Claude Code",
prompt: "How do I configure MCP servers?"
})- Tools: Read-only + WebFetch + WebSearch
- Best for: Questions about Claude Code, Agent SDK, Anthropic API
statusline-setup
Task({
subagent_type: "statusline-setup",
description: "Configure status line",
prompt: "Set up a status line showing git branch and node version"
})- Tools: Read, Edit only
- Model: Sonnet
- Best for: Configuring Claude Code status line
---
Plugin Agent Types
From the whetstone plugin (examples):
Review Agents
// Security review
Task({
subagent_type: "whetstone:review:security-sentinel",
description: "Security audit",
prompt: "Audit this PR for security vulnerabilities"
})
// Performance review
Task({
subagent_type: "whetstone:review:performance-oracle",
description: "Performance check",
prompt: "Analyze this code for performance bottlenecks"
})
// Architecture review
Task({
subagent_type: "whetstone:review:architecture-strategist",
description: "Architecture review",
prompt: "Review the system architecture of the authentication module"
})
// Code simplicity
Task({
subagent_type: "whetstone:review:code-simplicity-reviewer",
description: "Simplicity check",
prompt: "Check if this implementation can be simplified"
})All review agents from whetstone:
ia-architecture-strategist- Architectural complianceia-code-simplicity-reviewer- YAGNI and minimalismia-database-guardian- Database safety and migration validationia-deployment-verification-agent- Pre-deploy checklistsia-kieran-reviewer- Python and TypeScript best practicesia-architecture-strategist- Architecture, design patterns, and anti-patternsia-performance-oracle- Performance analysisia-security-sentinel- Security vulnerabilities
Research Agents
// Best practices research
Task({
subagent_type: "whetstone:research:best-practices-researcher",
description: "Research auth best practices",
prompt: "Research current best practices for JWT authentication 2024-2026"
})
// Framework documentation (use best-practices-researcher -- covers docs + best practices)
Task({
subagent_type: "whetstone:research:best-practices-researcher",
description: "Research Active Storage",
prompt: "Gather comprehensive documentation about Active Storage file uploads"
})
// Git history analysis
Task({
subagent_type: "whetstone:research:git-history-analyzer",
description: "Analyze auth history",
prompt: "Analyze the git history of the authentication module to understand its evolution"
})All research agents:
ia-best-practices-researcher- Best practices, framework docs, and implementation patternsia-git-history-analyzer- Code archaeologyia-learnings-researcher- Search docs/solutions/ia-repo-research-analyst- Repository patterns
Design Agents
Task({
subagent_type: "whetstone:design:figma-design-sync",
description: "Sync with Figma",
prompt: "Compare implementation with Figma design at [URL]"
})Workflow Agents
Task({
subagent_type: "whetstone:workflow:bug-reproduction-validator",
description: "Validate bug",
prompt: "Reproduce and validate this reported bug: [description]"
})Anti-Sycophancy Patterns
Load this reference when dispatching judge panels, running parallel reviewers, or iterating on subjective evaluations. Multi-agent swarms can converge on wrong answers through groupthink — these patterns prevent agents from anchoring on each other's outputs.
Cold-start agent isolation
Each agent in a swarm receives only the task description and fresh context. No session history, no prior agent outputs until an explicit synthesis phase. When running parallel reviewers or evaluators, the orchestrator holds all outputs until every agent has submitted independently, then passes the collected results to a synthesis agent.
Fresh instances on every re-dispatch round
When re-running reviewers across iterations (QA retry loop, re-review after fixes, multi-round evaluation), spawn a completely fresh agent each round — never reuse the same instance. Reviewers carrying memory from a prior round anchor on their earlier verdicts and miss regressions introduced by the fix. A reviewer who said "this is fine" in round 1 will rationalize back toward that verdict in round 2 even when a bad change has landed. Cold-start applies to every round, not just the first.
Label randomization for judge panels
When multiple candidates are evaluated (e.g., parallel implementations, competing approaches), judges see randomized labels — X/Y/Z, not A/B or "original"/"improved." Re-shuffle labels each evaluation round. This prevents anchoring on position ("A is always the baseline") or naming ("the synthesis must be better").
Convergence detection
Track an incumbent (current best candidate). If the same candidate wins N consecutive evaluation rounds (default: 3), stop iterating — the swarm has converged. This prevents infinite iteration on subjective tasks where no clear winner emerges and additional rounds just burn tokens.
Context Carry-Forward Strategies
After each turn in an orchestrated session, five options exist for carrying context into the next step. The default "Continue" is rarely best — deliberately choose a strategy based on what just happened.
| Strategy | How | When to use |
|---|---|---|
| Continue | Do nothing; full prior context flows forward | Short sessions, when prior context is all directly relevant |
| Rewind | Esc Esc (double-escape); keeps the useful prefix, drops the tail | Recovering from a failed attempt. Drops the failure from context without losing the useful reads that came before it. Beats "correcting" in place because correction keeps the failed path visible. |
| /compact | Lossy summarization into a short digest | Long sessions where the earlier turns are no longer load-bearing but their conclusions are |
| Subagent | Spawn a subagent for the task; only the result returns to main context | Contained research, focused implementation, or anything that would balloon main-thread context |
| /clear + brief | Clear context; restart with a hand-written brief | Mode switch (different feature, different skill needed). Cleaner than compaction when you know what's still load-bearing. |
Why Rewind is underused
When a session goes sideways after a bad tool call or misinterpretation, Rewind is strictly better than telling the assistant "no, that's wrong, do it differently." The latter leaves the failed path in context as a negative anchor — the assistant continues referencing what it did wrong. Rewind excises that from the window entirely.
Subagent vs Continue — the orchestrator's default
For swarm orchestrators specifically: when a task would consume > 30% of remaining context if done in-thread, prefer Subagent. The tradeoff is serialization overhead (one message wait) vs protecting main-thread context for decisions that need it.
Why clear+brief beats compaction on mode switches
/compact preserves everything lossy; the assistant keeps low-relevance fragments of prior tasks. /clear + a fresh brief produces cleaner context for a new mode because you control exactly what the assistant knows, rather than what /compact chose to preserve.
Dispatch Anti-Patterns
Load this reference when designing a multi-agent workflow. Named failure modes to recognize before they ship — each one looks reasonable in isolation and each one produces worse outcomes than direct execution.
| Anti-pattern | What it looks like | Why it fails |
|---|---|---|
| Router persona | An agent whose job is "decide which other agent to spawn, then spawn it" | Adds a serialization point with no judgment value. The caller could make the same decision from the task description. Removes context that the downstream agent needs. |
| Persona calls persona | Agent A dispatches agent B mid-task, agent B dispatches agent C | Claude Code does not allow subagents to spawn subagents — the Task tool is not available inside subagent contexts. Designs that assume nested dispatch silently fall back to "agent A does the work of B and C itself," usually worse. |
| Sequential paraphraser | An orchestrator that runs agents serially and rewrites each output before passing it downstream | Introduces drift at every hop. If agents must be sequential, pass outputs verbatim — summarize only at the final synthesis step, not between stages. |
| Deep persona trees | 4+ levels of agent specialization for a single task ("architect → reviewer → security-sub-reviewer → XSS-specialist") | Each level adds coordination cost without adding discrimination. Two levels (orchestrator + specialists in parallel) handle almost all real work. |
Rule of thumb: if the proposed swarm has more coordinator roles than worker roles, collapse it.
Environment Variables & Team Config
When to read: when configuring teammate environment, scoping inheritance, or debugging missing env-var propagation across spawned instances.
Environment Variables
Spawned teammates automatically receive these:
CLAUDE_CODE_TEAM_NAME="my-project"
CLAUDE_CODE_AGENT_ID="worker-1@my-project"
CLAUDE_CODE_AGENT_NAME="worker-1"
CLAUDE_CODE_AGENT_TYPE="Explore"
CLAUDE_CODE_AGENT_COLOR="#4A90D9"
CLAUDE_CODE_PLAN_MODE_REQUIRED="false"
CLAUDE_CODE_PARENT_SESSION_ID="session-xyz"Using in prompts:
Task({
team_name: "my-project",
name: "worker",
subagent_type: "general-purpose",
prompt: "Your name is $CLAUDE_CODE_AGENT_NAME. Use it when sending messages to team-lead."
})Team Config Structure
~/.claude/teams/{team-name}/config.json:
{
"name": "my-project",
"description": "Working on feature X",
"leadAgentId": "team-lead@my-project",
"createdAt": 1706000000000,
"members": [
{
"agentId": "team-lead@my-project",
"name": "team-lead",
"agentType": "team-lead",
"color": "#4A90D9",
"joinedAt": 1706000000000,
"backendType": "in-process"
},
{
"agentId": "worker-1@my-project",
"name": "worker-1",
"agentType": "Explore",
"model": "haiku",
"prompt": "Analyze the codebase structure...",
"color": "#D94A4A",
"planModeRequired": false,
"joinedAt": 1706000001000,
"tmuxPaneId": "in-process",
"cwd": "<repo-root>",
"backendType": "in-process"
}
]
}Error Handling
Common Errors
| Error | Cause | Solution |
|---|---|---|
| "Cannot cleanup with active members" | Teammates still running | requestShutdown all teammates first, wait for approval |
| "Already leading a team" | Team already exists | cleanup first, or use different team name |
| "Agent not found" | Wrong teammate name | Check config.json for actual names |
| "Team does not exist" | No team created | Call spawnTeam first |
| "team_name is required" | Missing team context | Provide team_name parameter |
| "Agent type not found" | Invalid subagent_type | Check available agents with proper prefix |
Graceful Shutdown Sequence
Always follow this sequence:
// 1. Request shutdown for all teammates
Teammate({ operation: "requestShutdown", target_agent_id: "worker-1" })
Teammate({ operation: "requestShutdown", target_agent_id: "worker-2" })
// 2. Wait for shutdown approvals
// Check for {"type": "shutdown_approved", ...} messages
// 3. Verify no active members
// Read ~/.claude/teams/{team}/config.json
// 4. Only then cleanup
Teammate({ operation: "cleanup" })Handling Crashed Teammates
Teammates have a 5-minute heartbeat timeout. If a teammate crashes:
1. They'll be automatically marked as inactive after timeout 2. Their tasks remain in the task list 3. Another teammate can claim their tasks 4. Cleanup will work after timeout expires
Debugging
# Check team config
cat ~/.claude/teams/{team}/config.json | jq '.members[] | {name, agentType, backendType}'
# Check teammate inboxes
cat ~/.claude/teams/{team}/inboxes/{agent}.json | jq '.'
# List all teams
ls ~/.claude/teams/
# Check task states
cat ~/.claude/tasks/{team}/*.json | jq '{id, subject, status, owner, blockedBy}'
# Watch for new messages
tail -f ~/.claude/teams/{team}/inboxes/team-lead.jsonHandoff Templates
When to read: when one agent is handing work back or forward (QA fail, implementation complete, blocked, escalation) and you want a structured template instead of free-form prose.
QA FAIL
Use when returning failed QA results to an implementer agent.
**QA Result: FAIL** (Attempt N of 3)
**Expected:** [what the spec/test requires]
**Actual:** [what the implementation does]
**Evidence:** [screenshot, test output, or log excerpt]
**Fix instruction:** [specific change needed]
**File(s) to modify:** [exact paths]
Fix ONLY the issues listed. Do NOT introduce new features, refactor unrelated code, or restructure the implementation.Review Dispatch
Use when dispatching a review subagent after a task completes. Two sequential dispatches: spec compliance first, then code quality. Each gets fresh context (no session history from the implementer).
Stage 1: Spec Compliance
Review this implementation for spec compliance ONLY. Do not review code quality.
**Task spec:**
[paste the exact task description/requirements]
**Files changed:**
[paste the diff or list of changed files with relevant content]
**Check each requirement:**
1. Is every requirement implemented? List any gaps.
2. Is anything implemented that was NOT in the spec? List additions.
3. Does the implementation match the spec's intent, not just its letter?
**Return format:**
- PASS: all requirements met, no extras
- FAIL: [list gaps or unwanted additions]Stage 2: Code Quality
Only dispatch after Stage 1 passes.
Review this implementation for code quality. Spec compliance already verified.
**Files changed:**
[paste the diff or list of changed files with relevant content]
**Review for:**
- Correctness (edge cases, error handling, type safety)
- Security (input validation, auth, injection vectors)
- Performance (N+1 queries, unbounded collections, missing indexes)
- Maintainability (naming, complexity, duplication)
**Return format:**
- Strengths: [specific positive observations]
- Issues: [ranked by severity -- Critical/Important/Medium/Minor]
- Verdict: Ready / Needs fixesEscalation Report
Use after 3 failed attempts on the same task to escalate to the orchestrator.
**Escalation: Task [N] blocked after 3 attempts**
**Failure history:**
- Attempt 1: [what was tried, what failed]
- Attempt 2: [what was tried, what failed]
- Attempt 3: [what was tried, what failed]
**Root cause analysis:** [Why does this task keep failing? Systemic issue vs. one-off?]
**Resolution options:**
1. Reassign to a different agent (fresh context)
2. Decompose into smaller subtasks
3. Revise the approach entirely
4. Accept current state with known limitations
5. Defer to user for guidanceMessage Formats
When to read: when composing inter-agent messages and needing the canonical JSON shapes for regular messages, broadcasts, structured payloads, or QA handoffs.
Regular Message
{
"from": "team-lead",
"text": "Please prioritize the auth module",
"timestamp": "2026-01-25T23:38:32.588Z",
"read": false
}Structured Messages (JSON in text field)
Shutdown Request
{
"type": "shutdown_request",
"requestId": "shutdown-abc123@worker-1",
"from": "team-lead",
"reason": "All tasks complete",
"timestamp": "2026-01-25T23:38:32.588Z"
}Shutdown Approved
{
"type": "shutdown_approved",
"requestId": "shutdown-abc123@worker-1",
"from": "worker-1",
"paneId": "%5",
"backendType": "in-process",
"timestamp": "2026-01-25T23:39:00.000Z"
}Idle Notification (auto-sent when teammate stops)
{
"type": "idle_notification",
"from": "worker-1",
"timestamp": "2026-01-25T23:40:00.000Z",
"completedTaskId": "2",
"completedStatus": "completed"
}Task Completed
{
"type": "task_completed",
"from": "worker-1",
"taskId": "2",
"taskSubject": "Review authentication module",
"timestamp": "2026-01-25T23:40:00.000Z"
}Plan Approval Request
{
"type": "plan_approval_request",
"from": "architect",
"requestId": "plan-xyz789",
"planContent": "# Implementation Plan\n\n1. ...",
"timestamp": "2026-01-25T23:41:00.000Z"
}Join Request
{
"type": "join_request",
"proposedName": "helper",
"requestId": "join-abc123",
"capabilities": "Code review and testing",
"timestamp": "2026-01-25T23:42:00.000Z"
}Permission Request (for sandbox/tool permissions)
{
"type": "permission_request",
"requestId": "perm-123",
"workerId": "worker-1@my-project",
"workerName": "worker-1",
"workerColor": "#4A90D9",
"toolName": "Bash",
"toolUseId": "toolu_abc123",
"description": "Run npm install",
"input": {"command": "npm install"},
"permissionSuggestions": ["Bash(npm *)"],
"createdAt": 1706000000000
}Orchestration Patterns
When to read: when designing a multi-agent workflow shape — parallel specialists, sequential pipeline, hub-and-spoke, or hierarchical sub-teams.
Pattern 1: Parallel Specialists (Leader Pattern)
Multiple specialists review code simultaneously:
// 1. Create team
Teammate({ operation: "spawnTeam", team_name: "code-review" })
// 2. Spawn specialists in parallel (single message, multiple Task calls)
Task({
team_name: "code-review",
name: "security",
subagent_type: "whetstone:review:security-sentinel",
prompt: "Review the PR for security vulnerabilities. Focus on: SQL injection, XSS, auth bypass. Send findings to team-lead.",
run_in_background: true
})
Task({
team_name: "code-review",
name: "performance",
subagent_type: "whetstone:review:performance-oracle",
prompt: "Review the PR for performance issues. Focus on: N+1 queries, memory leaks, slow algorithms. Send findings to team-lead.",
run_in_background: true
})
Task({
team_name: "code-review",
name: "simplicity",
subagent_type: "whetstone:review:code-simplicity-reviewer",
prompt: "Review the PR for unnecessary complexity. Focus on: over-engineering, premature abstraction, YAGNI violations. Send findings to team-lead.",
run_in_background: true
})
// 3. Wait for results (check inbox)
// cat ~/.claude/teams/code-review/inboxes/team-lead.json
// 4. Synthesize findings and cleanup
Teammate({ operation: "requestShutdown", target_agent_id: "security" })
Teammate({ operation: "requestShutdown", target_agent_id: "performance" })
Teammate({ operation: "requestShutdown", target_agent_id: "simplicity" })
// Wait for approvals...
Teammate({ operation: "cleanup" })Pattern 2: Pipeline (Sequential Dependencies)
Each stage depends on the previous:
// 1. Create team and task pipeline
Teammate({ operation: "spawnTeam", team_name: "feature-pipeline" })
TaskCreate({ subject: "Research", description: "Research best practices for the feature", activeForm: "Researching..." })
TaskCreate({ subject: "Plan", description: "Create implementation plan based on research", activeForm: "Planning..." })
TaskCreate({ subject: "Implement", description: "Implement the feature according to plan", activeForm: "Implementing..." })
TaskCreate({ subject: "Test", description: "Write and run tests for the implementation", activeForm: "Testing..." })
TaskCreate({ subject: "Review", description: "Final code review before merge", activeForm: "Reviewing..." })
// Set up sequential dependencies
TaskUpdate({ taskId: "2", addBlockedBy: ["1"] })
TaskUpdate({ taskId: "3", addBlockedBy: ["2"] })
TaskUpdate({ taskId: "4", addBlockedBy: ["3"] })
TaskUpdate({ taskId: "5", addBlockedBy: ["4"] })
// 2. Spawn workers that claim and complete tasks
Task({
team_name: "feature-pipeline",
name: "researcher",
subagent_type: "whetstone:research:best-practices-researcher",
prompt: "Claim task #1, research best practices, complete it, send findings to team-lead. Then check for more work.",
run_in_background: true
})
Task({
team_name: "feature-pipeline",
name: "implementer",
subagent_type: "general-purpose",
prompt: "Poll TaskList every 30 seconds. When task #3 unblocks, claim it and implement. Then complete and notify team-lead.",
run_in_background: true
})
// Tasks auto-unblock as dependencies completePattern 3: Swarm (Self-Organizing)
Workers grab available tasks from a pool:
// 1. Create team and task pool
Teammate({ operation: "spawnTeam", team_name: "file-review-swarm" })
// Create many independent tasks (no dependencies)
for (const file of ["auth.ts", "user.ts", "apiController.ts", "payment.ts"]) {
TaskCreate({
subject: `Review ${file}`,
description: `Review ${file} for security and code quality issues`,
activeForm: `Reviewing ${file}...`
})
}
// 2. Spawn worker swarm
Task({
team_name: "file-review-swarm",
name: "worker-1",
subagent_type: "general-purpose",
prompt: `
You are a swarm worker. Your job:
1. Call TaskList to see available tasks
2. Find a task with status 'pending' and no owner
3. Claim it with TaskUpdate (set owner to your name)
4. Do the work
5. Mark it completed with TaskUpdate
6. Send findings to team-lead via Teammate write
7. Repeat until no tasks remain
`,
run_in_background: true
})
Task({
team_name: "file-review-swarm",
name: "worker-2",
subagent_type: "general-purpose",
prompt: `[Same prompt as worker-1]`,
run_in_background: true
})
Task({
team_name: "file-review-swarm",
name: "worker-3",
subagent_type: "general-purpose",
prompt: `[Same prompt as worker-1]`,
run_in_background: true
})
// Workers race to claim tasks, naturally load-balancePattern 4: Research + Implementation
Research first, then implement:
// 1. Research phase (synchronous, returns results)
const research = await Task({
subagent_type: "whetstone:research:best-practices-researcher",
description: "Research caching patterns",
prompt: "Research best practices for implementing API caching. Include: cache invalidation strategies, Redis vs Memcached, cache key design."
})
// 2. Use research to guide implementation
Task({
subagent_type: "general-purpose",
description: "Implement caching",
prompt: `
Implement API caching based on this research:
${research.content}
Focus on the usersController.ts endpoints.
`
})Pattern 5: Plan Approval Workflow
Require plan approval before implementation:
// 1. Create team
Teammate({ operation: "spawnTeam", team_name: "careful-work" })
// 2. Spawn architect with plan_mode_required
Task({
team_name: "careful-work",
name: "architect",
subagent_type: "Plan",
prompt: "Design an implementation plan for adding OAuth2 authentication",
mode: "plan", // Requires plan approval
run_in_background: true
})
// 3. Wait for plan approval request
// You'll receive: {"type": "plan_approval_request", "from": "architect", "requestId": "plan-xxx", ...}
// 4. Review and approve/reject
Teammate({
operation: "approvePlan",
target_agent_id: "architect",
request_id: "plan-xxx"
})
// OR
Teammate({
operation: "rejectPlan",
target_agent_id: "architect",
request_id: "plan-xxx",
feedback: "Please add rate limiting considerations"
})Pattern 6: Coordinated Multi-File Refactoring
// 1. Create team for coordinated refactoring
Teammate({ operation: "spawnTeam", team_name: "refactor-auth" })
// 2. Create tasks with clear file boundaries
TaskCreate({
subject: "Refactor User model",
description: "Extract authentication methods to AuthenticatableUser concern",
activeForm: "Refactoring User model..."
})
TaskCreate({
subject: "Refactor Session controller",
description: "Update to use new AuthenticatableUser concern",
activeForm: "Refactoring Sessions..."
})
TaskCreate({
subject: "Update specs",
description: "Update all authentication specs for new structure",
activeForm: "Updating specs..."
})
// Dependencies: specs depend on both refactors completing
TaskUpdate({ taskId: "3", addBlockedBy: ["1", "2"] })
// 3. Spawn workers for each task
Task({
team_name: "refactor-auth",
name: "model-worker",
subagent_type: "general-purpose",
prompt: "Claim task #1, refactor the User model, complete when done",
run_in_background: true
})
Task({
team_name: "refactor-auth",
name: "controller-worker",
subagent_type: "general-purpose",
prompt: "Claim task #2, refactor the Session controller, complete when done",
run_in_background: true
})
Task({
team_name: "refactor-auth",
name: "spec-worker",
subagent_type: "general-purpose",
prompt: "Wait for task #3 to unblock (when #1 and #2 complete), then update specs",
run_in_background: true
})---
Complete Workflows
Workflow 1: Full Code Review with Parallel Specialists
// === STEP 1: Setup ===
Teammate({ operation: "spawnTeam", team_name: "pr-review-123", description: "Reviewing PR #123" })
// === STEP 2: Spawn reviewers in parallel ===
// (Send all these in a single message for parallel execution)
Task({
team_name: "pr-review-123",
name: "security",
subagent_type: "whetstone:review:security-sentinel",
prompt: `Review PR #123 for security vulnerabilities.
Focus on:
- SQL injection
- XSS vulnerabilities
- Authentication/authorization bypass
- Sensitive data exposure
When done, send your findings to team-lead using:
Teammate({ operation: "write", target_agent_id: "team-lead", value: "Your findings here" })`,
run_in_background: true
})
Task({
team_name: "pr-review-123",
name: "perf",
subagent_type: "whetstone:review:performance-oracle",
prompt: `Review PR #123 for performance issues.
Focus on:
- N+1 queries
- Missing indexes
- Memory leaks
- Inefficient algorithms
Send findings to team-lead when done.`,
run_in_background: true
})
Task({
team_name: "pr-review-123",
name: "arch",
subagent_type: "whetstone:review:architecture-strategist",
prompt: `Review PR #123 for architectural concerns.
Focus on:
- Design pattern adherence
- SOLID principles
- Separation of concerns
- Testability
Send findings to team-lead when done.`,
run_in_background: true
})
// === STEP 3: Monitor and collect results ===
// Poll inbox or wait for idle notifications
// cat ~/.claude/teams/pr-review-123/inboxes/team-lead.json
// === STEP 4: Synthesize findings ===
// Combine all reviewer findings into a cohesive report
// === STEP 5: Cleanup ===
Teammate({ operation: "requestShutdown", target_agent_id: "security" })
Teammate({ operation: "requestShutdown", target_agent_id: "perf" })
Teammate({ operation: "requestShutdown", target_agent_id: "arch" })
// Wait for approvals...
Teammate({ operation: "cleanup" })Workflow 2: Research -> Plan -> Implement -> Test Pipeline
// === SETUP ===
Teammate({ operation: "spawnTeam", team_name: "feature-oauth" })
// === CREATE PIPELINE ===
TaskCreate({ subject: "Research OAuth providers", description: "Research OAuth2 best practices and compare providers (Google, GitHub, Auth0)", activeForm: "Researching OAuth..." })
TaskCreate({ subject: "Create implementation plan", description: "Design OAuth implementation based on research findings", activeForm: "Planning..." })
TaskCreate({ subject: "Implement OAuth", description: "Implement OAuth2 authentication according to plan", activeForm: "Implementing OAuth..." })
TaskCreate({ subject: "Write tests", description: "Write comprehensive tests for OAuth implementation", activeForm: "Writing tests..." })
TaskCreate({ subject: "Final review", description: "Review complete implementation for security and quality", activeForm: "Final review..." })
// Set dependencies
TaskUpdate({ taskId: "2", addBlockedBy: ["1"] })
TaskUpdate({ taskId: "3", addBlockedBy: ["2"] })
TaskUpdate({ taskId: "4", addBlockedBy: ["3"] })
TaskUpdate({ taskId: "5", addBlockedBy: ["4"] })
// === SPAWN SPECIALIZED WORKERS ===
Task({
team_name: "feature-oauth",
name: "researcher",
subagent_type: "whetstone:research:best-practices-researcher",
prompt: "Claim task #1. Research OAuth2 best practices, compare providers, document findings. Mark task complete and send summary to team-lead.",
run_in_background: true
})
Task({
team_name: "feature-oauth",
name: "planner",
subagent_type: "Plan",
prompt: "Wait for task #2 to unblock. Read research from task #1. Create detailed implementation plan. Mark complete and send plan to team-lead.",
run_in_background: true
})
Task({
team_name: "feature-oauth",
name: "implementer",
subagent_type: "general-purpose",
prompt: "Wait for task #3 to unblock. Read plan from task #2. Implement OAuth2 authentication. Mark complete when done.",
run_in_background: true
})
Task({
team_name: "feature-oauth",
name: "tester",
subagent_type: "general-purpose",
prompt: "Wait for task #4 to unblock. Write comprehensive tests for the OAuth implementation. Run tests. Mark complete with results.",
run_in_background: true
})
Task({
team_name: "feature-oauth",
name: "reviewer",
subagent_type: "whetstone:review:security-sentinel",
prompt: "Wait for task #5 to unblock. Review the complete OAuth implementation for security. Send final assessment to team-lead.",
run_in_background: true
})
// Pipeline auto-progresses as each stage completesWorkflow 3: Self-Organizing Code Review Swarm
// === SETUP ===
Teammate({ operation: "spawnTeam", team_name: "codebase-review" })
// === CREATE TASK POOL (all independent, no dependencies) ===
const filesToReview = [
"src/models/user.ts",
"src/models/payment.ts",
"src/controllers/api/v1/usersController.ts",
"src/controllers/api/v1/paymentsController.ts",
"src/services/paymentProcessor.ts",
"src/services/notificationService.ts",
"src/lib/encryptionHelper.ts"
]
for (const file of filesToReview) {
TaskCreate({
subject: `Review ${file}`,
description: `Review ${file} for security vulnerabilities, code quality, and performance issues`,
activeForm: `Reviewing ${file}...`
})
}
// === SPAWN WORKER SWARM ===
const swarmPrompt = `
You are a swarm worker. Your job is to continuously process available tasks.
LOOP:
1. Call TaskList() to see available tasks
2. Find a task that is:
- status: 'pending'
- no owner
- not blocked
3. If found:
- Claim it: TaskUpdate({ taskId: "X", owner: "YOUR_NAME" })
- Start it: TaskUpdate({ taskId: "X", status: "in_progress" })
- Do the review work
- Complete it: TaskUpdate({ taskId: "X", status: "completed" })
- Send findings to team-lead via Teammate write
- Go back to step 1
4. If no tasks available:
- Send idle notification to team-lead
- Wait 30 seconds
- Try again (up to 3 times)
- If still no tasks, exit
Replace YOUR_NAME with your actual agent name from $CLAUDE_CODE_AGENT_NAME.
`
// Spawn 3 workers
Task({ team_name: "codebase-review", name: "worker-1", subagent_type: "general-purpose", prompt: swarmPrompt, run_in_background: true })
Task({ team_name: "codebase-review", name: "worker-2", subagent_type: "general-purpose", prompt: swarmPrompt, run_in_background: true })
Task({ team_name: "codebase-review", name: "worker-3", subagent_type: "general-purpose", prompt: swarmPrompt, run_in_background: true })
// Workers self-organize: race to claim tasks, naturally load-balance
// Monitor progress with TaskList() or by reading inboxOrchestration Primitives
Glossary and file-structure reference. Load when onboarding to the team/teammate/task model or debugging paths.
Primitives
| Primitive | What It Is |
|---|---|
| Agent | A Claude instance that can use tools. You are an agent. Subagents are agents you spawn. |
| Team | A named group of agents working together. One leader, multiple teammates. Config: ~/.claude/teams/{name}/config.json |
| Teammate | An agent that joined a team. Has a name, color, inbox. Spawned via Task with team_name + name. |
| Leader | The agent that created the team. Receives teammate messages, approves plans/shutdowns. |
| Task | A work item with subject, description, status, owner, and dependencies. Stored: ~/.claude/tasks/{team}/N.json |
| Inbox | JSON file where an agent receives messages from teammates. Path: ~/.claude/teams/{name}/inboxes/{agent}.json |
| Message | A JSON object sent between agents. Can be text or structured (shutdown_request, idle_notification, etc). |
| Backend | How teammates run. Auto-detected: in-process, tmux, or iterm2. See spawn-backends.md. |
Core File Layout
~/.claude/teams/{team-name}/
├── config.json # Team metadata and member list
└── inboxes/
├── team-lead.json # Leader's inbox
└── worker-1.json # Worker inbox
~/.claude/tasks/{team-name}/
├── 1.json # Task #1
└── 2.json # Task #2Orchestrating Swarms — Quick Reference
Code snippets for the common spawn/message/task/shutdown operations. Load when setting up a specific coordination pattern — the decision logic lives in the main SKILL.md.
Spawn Team + Teammate
Teammate({ operation: "spawnTeam", team_name: "my-team" })
Task({ team_name: "my-team", name: "worker", subagent_type: "general-purpose",
prompt: "...", run_in_background: true })Message a Teammate
Teammate({ operation: "write", target_agent_id: "worker-1", value: "..." })Create Task Pipeline
TaskCreate({ subject: "Step 1", description: "...", activeForm: "Working..." })
TaskCreate({ subject: "Step 2", description: "...", activeForm: "Working..." })
TaskUpdate({ taskId: "2", addBlockedBy: ["1"] }) // #2 waits for #1Claim and Complete Tasks (as teammate)
TaskUpdate({ taskId: "1", owner: "my-name", status: "in_progress" })
// ... do work ...
TaskUpdate({ taskId: "1", status: "completed" })Shutdown Team
Teammate({ operation: "requestShutdown", target_agent_id: "worker-1" })
// Wait for shutdown_approved message...
Teammate({ operation: "cleanup" })Swarm Resilience Patterns
Load this reference when designing a multi-agent workflow that must survive partial failure. Swarm failures are inevitable — contain blast radius and recover partial value rather than discarding everything.
Cascade prevention
Set timeout boundaries per agent. If one agent fails or hangs, do not let it cascade into abandoning the entire swarm's work. The orchestrator treats each agent as independently failable — other agents continue their work unaffected. Terminate unresponsive agents after the timeout rather than waiting indefinitely.
Apply circuit-breaker logic to agent types: after N consecutive failures from the same agent type, stop dispatching to it and route to an alternative (different model, different decomposition). Apply bulkhead isolation: a failing agent type cannot exhaust the shared task queue or block other agent types from proceeding.
Recovery strategy
When an agent fails, classify the failure before acting:
- Retry — transient errors (network timeout, rate limit). Re-dispatch the same task.
- Reassign — agent-specific issue (context pollution, wrong model for task complexity). Dispatch a fresh agent, optionally with a different model.
- Escalate — systemic problem (bad spec, missing dependency, impossible constraint). Surface to the orchestrator or user with an Escalation Report.
For agent-reported BLOCKED status specifically (as opposed to crashes or timeouts), use the BLOCKED triage decision tree in the main skill under "Dispatch Discipline" — it maps the four BLOCKED root causes (missing context / reasoning ceiling / task too large / spec wrong) to concrete responses.
Never retry blindly. Repeating the same prompt in the same conditions produces the same failure.
Mid-pipeline compensation
When an agent fails mid-pipeline after earlier agents have already written files or made changes, classify whether those earlier effects are reversible before deciding the recovery path. If reversible (file writes, uncommitted changes), revert and retry the pipeline segment. If irreversible (committed code, external API calls, database writes), compensate rather than retry — apply a corrective action that accounts for the partial state. Never retry blindly when earlier stages have produced side effects.
Post-failure synthesis
Even partial results from a failed swarm run have value. When some agents succeed and others fail, collect and present the successful outputs rather than discarding everything. Mark failed tasks as incomplete in the synthesis so downstream consumers know which areas lack coverage.
Spawn Backends
When to read: when picking or debugging the spawn backend (TeammateTool / Task / subprocess), checking compatibility, or reasoning about where teammates actually execute.
A backend determines how teammate Claude instances actually run. Claude Code supports three backends, and auto-detects the best one based on your environment.
Backend Comparison
| Backend | How It Works | Visibility | Persistence | Speed |
|---|---|---|---|---|
| in-process | Same Node.js process as leader | Hidden (background) | Dies with leader | Fastest |
| tmux | Separate terminal in tmux session | Visible in tmux | Survives leader exit | Medium |
| iterm2 | Split panes in iTerm2 window | Visible side-by-side | Dies with window | Medium |
Auto-Detection Logic
Detection checks (in order): 1. $TMUX environment variable set -> inside tmux -> use tmux backend 2. $TERM_PROGRAM === "iTerm.app" or $ITERM_SESSION_ID set -> in iTerm2
it2CLI installed -> use iterm2 backendit2not installed, tmux available -> use tmux (prompt to install it2)- Neither -> error: install tmux or it2
3. which tmux succeeds -> tmux available -> use tmux (external session) 4. Nothing available -> use in-process
in-process (Default for non-tmux)
Teammates run as async tasks within the same Node.js process.
+-------------------------------------+
| Node.js Process |
| +---------+ +---------+ +-----+ |
| | Leader | |Worker 1 | |W 2 | |
| | (main) | | (async) | |(as) | |
| +---------+ +---------+ +-----+ |
+-------------------------------------+Pros: Fastest startup, lowest overhead, works everywhere. Cons: Can't see teammate output, all die if leader dies, harder to debug.
// in-process is automatic when not in tmux
Task({
team_name: "my-project",
name: "worker",
subagent_type: "general-purpose",
prompt: "...",
run_in_background: true
})
// Force in-process explicitly
// export CLAUDE_CODE_SPAWN_BACKEND=in-processtmux
Teammates run as separate Claude instances in tmux panes/windows.
Inside tmux (native): Splits your current window. Outside tmux (external session): Creates a new tmux session called claude-swarm. View with tmux attach -t claude-swarm.
Pros: See teammate output in real-time, teammates survive leader exit, works in CI/headless. Cons: Slower startup, requires tmux installed, more resource usage.
# Start tmux session first
tmux new-session -s claude
# Or force tmux backend
export CLAUDE_CODE_SPAWN_BACKEND=tmuxUseful tmux commands:
tmux list-panes # List all panes in current window
tmux select-pane -t 1 # Switch to pane by number
tmux kill-pane -t %5 # Kill a specific pane
tmux attach -t claude-swarm # View swarm session (if external)
tmux select-layout tiled # Rebalance pane layoutiterm2 (macOS only)
Teammates run as split panes within your iTerm2 window using iTerm2's Python API via it2 CLI.
Pros: Visual debugging, native macOS experience, automatic pane management. Cons: macOS + iTerm2 only, requires setup, panes die with window.
Setup:
# 1. Install it2 CLI
uv tool install it2
# OR: pipx install it2
# OR: pip install --user it2
# 2. Enable Python API in iTerm2
# iTerm2 -> Settings -> General -> Magic -> Enable Python API
# 3. Restart iTerm2
# 4. Verify
it2 --version
it2 session listIf setup fails, Claude Code will prompt you to set up it2 when you first spawn a teammate. You can choose to install it2 now, use tmux instead, or cancel.
Forcing a Backend
# Force in-process (fastest, no visibility)
export CLAUDE_CODE_SPAWN_BACKEND=in-process
# Force tmux (visible panes, persistent)
export CLAUDE_CODE_SPAWN_BACKEND=tmux
# Auto-detect (default)
unset CLAUDE_CODE_SPAWN_BACKENDBackend in Team Config
The backend type is recorded per-teammate in config.json:
{
"members": [
{
"name": "worker-1",
"backendType": "in-process",
"tmuxPaneId": "in-process"
},
{
"name": "worker-2",
"backendType": "tmux",
"tmuxPaneId": "%5"
}
]
}Troubleshooting
| Issue | Cause | Solution |
|---|---|---|
| "No pane backend available" | Neither tmux nor iTerm2 available | Install tmux: brew install tmux |
| "it2 CLI not installed" | In iTerm2 but missing it2 | Run uv tool install it2 |
| "Python API not enabled" | it2 can't communicate with iTerm2 | Enable in iTerm2 Settings -> General -> Magic |
| Workers not visible | Using in-process backend | Start inside tmux or iTerm2 |
| Workers dying unexpectedly | Outside tmux, leader exited | Use tmux for persistence |
Checking Current Backend
# See what backend was detected
cat ~/.claude/teams/{team}/config.json | jq '.members[].backendType'
# Check if inside tmux
echo $TMUX
# Check if in iTerm2
echo $TERM_PROGRAM
# Check tmux availability
which tmux
# Check it2 availability
which it2Task System Integration
When to read: when integrating TaskCreate / TaskUpdate / TaskList into a swarm and needing the exact tool call shapes for work-item dispatch.
TaskCreate - Create Work Items
TaskCreate({
subject: "Review authentication module",
description: "Review all files in app/services/auth/ for security vulnerabilities",
activeForm: "Reviewing auth module..." // Shown in spinner when in_progress
})TaskList - See All Tasks
TaskList()Returns:
#1 [completed] Analyze codebase structure
#2 [in_progress] Review authentication module (owner: security-reviewer)
#3 [pending] Generate summary report [blocked by #2]TaskGet - Get Task Details
TaskGet({ taskId: "2" })Returns full task with description, status, blockedBy, etc.
TaskUpdate - Update Task Status
// Claim a task
TaskUpdate({ taskId: "2", owner: "security-reviewer" })
// Start working
TaskUpdate({ taskId: "2", status: "in_progress" })
// Mark complete
TaskUpdate({ taskId: "2", status: "completed" })
// Set up dependencies
TaskUpdate({ taskId: "3", addBlockedBy: ["1", "2"] })Task Dependencies
When a blocking task is completed, blocked tasks are automatically unblocked:
// Create pipeline
TaskCreate({ subject: "Step 1: Research" }) // #1
TaskCreate({ subject: "Step 2: Implement" }) // #2
TaskCreate({ subject: "Step 3: Test" }) // #3
TaskCreate({ subject: "Step 4: Deploy" }) // #4
// Set up dependencies
TaskUpdate({ taskId: "2", addBlockedBy: ["1"] }) // #2 waits for #1
TaskUpdate({ taskId: "3", addBlockedBy: ["2"] }) // #3 waits for #2
TaskUpdate({ taskId: "4", addBlockedBy: ["3"] }) // #4 waits for #3
// When #1 completes, #2 auto-unblocks
// When #2 completes, #3 auto-unblocks
// etc.Task File Structure
~/.claude/tasks/{team-name}/1.json:
{
"id": "1",
"subject": "Review authentication module",
"description": "Review all files in app/services/auth/...",
"status": "in_progress",
"owner": "security-reviewer",
"activeForm": "Reviewing auth module...",
"blockedBy": [],
"blocks": ["3"],
"createdAt": 1706000000000,
"updatedAt": 1706000001000
}Preset Team Compositions
Start here before designing a custom team. Each preset is a proven shape for a specific work pattern — use the smallest preset that covers all required dimensions. Adding teammates beyond what the work needs adds coordination overhead without speedup.
| Preset | Size | Agents | Use when |
|---|---|---|---|
| Review Team | 3 | 3x reviewers on distinct dimensions (security, performance, architecture) | Code changes need multi-dimensional quality assessment |
| Debug Team | 3 | 3x investigators, one per competing hypothesis | Bug has multiple plausible root causes |
| Feature Team | 3 | 1x lead + 2x implementers with exclusive file ownership | Feature decomposes into parallel work streams |
| Fullstack Team | 4 | 1x lead + frontend impl + backend impl + test impl | Feature spans frontend, backend, and test layers |
| Migration Team | 4 | 1x lead + 2x implementers + 1x reviewer | Large codebase migration needing parallel work with correctness verification |
| Security Team | 4 | 4x reviewers on OWASP / auth / dependencies / secrets | Comprehensive security audit across multiple attack surfaces |
| Research Team | 3 | 3x read-only researchers (Explore or general-purpose), each on a distinct question | Codebase exploration, library comparisons, parallel research |
Sizing discipline
Two reviewers flagging the same issues means the dimensions overlap. Redefine each focus area instead of adding more agents. Four agents doing six independent tasks are usually worse than three agents covering two tasks each — coordination overhead scales non-linearly.
Cardinal subagent_type rule
Read-only agent types (Explore, Plan) cannot modify files. Never assign implementation tasks to read-only agents — the spawn will silently succeed while writes fail. For any task that creates or edits files, use general-purpose or a specialized writable agent type.
| subagent_type | Tools | Use for |
|---|---|---|
general-purpose | All tools (Read, Write, Edit, Bash, ...) | Implementation, debugging, anything that modifies files |
Explore | Read-only (Read, Grep, Glob) | Research, codebase search, analysis — NEVER implementation |
Plan | Read-only | Architecture planning, task decomposition — NEVER implementation |
Custom team guidelines
When building a team that doesn't match a preset:
1. Every team needs a coordinator — either designate a lead or have the orchestrator coordinate directly 2. Match roles to writable agent types — read-only types cannot implement 3. Avoid duplicate roles — two agents doing the same thing wastes resources 4. Define file ownership upfront — each teammate needs exclusive write ownership of specific files 5. Keep it small — 2-4 teammates is the sweet spot; 5+ requires significant coordination overhead
TeammateTool Operations
When to read: when working with the TeammateTool orchestration backend and needing the spawnTeam, sendMessage, broadcast, or shutdown call signatures.1. spawnTeam - Create a Team
Teammate({
operation: "spawnTeam",
team_name: "feature-auth",
description: "Implementing OAuth2 authentication"
})Creates:
~/.claude/teams/feature-auth/config.json~/.claude/tasks/feature-auth/directory- You become the team leader
2. discoverTeams - List Available Teams
Teammate({ operation: "discoverTeams" })Returns: List of teams you can join (not already a member of)
3. requestJoin - Request to Join Team
Teammate({
operation: "requestJoin",
team_name: "feature-auth",
proposed_name: "helper",
capabilities: "I can help with code review and testing"
})4. approveJoin - Accept Join Request (Leader Only)
When you receive a join_request message:
{"type": "join_request", "proposedName": "helper", "requestId": "join-123", ...}Approve it:
Teammate({
operation: "approveJoin",
target_agent_id: "helper",
request_id: "join-123"
})5. rejectJoin - Decline Join Request (Leader Only)
Teammate({
operation: "rejectJoin",
target_agent_id: "helper",
request_id: "join-123",
reason: "Team is at capacity"
})6. write - Message One Teammate
Teammate({
operation: "write",
target_agent_id: "security-reviewer",
value: "Please prioritize the authentication module. The deadline is tomorrow."
})Important for teammates: Your text output is NOT visible to the team. You MUST use write to communicate.
7. broadcast - Message ALL Teammates
Teammate({
operation: "broadcast",
name: "team-lead", // Your name
value: "Status check: Please report your progress"
})WARNING: Broadcasting is expensive - sends N separate messages for N teammates. Prefer write to specific teammates.
When to broadcast:
- Critical issues requiring immediate attention
- Major announcements affecting everyone
When NOT to broadcast:
- Responding to one teammate
- Normal back-and-forth
- Information relevant to only some teammates
8. requestShutdown - Ask Teammate to Exit (Leader Only)
Teammate({
operation: "requestShutdown",
target_agent_id: "security-reviewer",
reason: "All tasks complete, wrapping up"
})9. approveShutdown - Accept Shutdown (Teammate Only)
When you receive a shutdown_request message:
{"type": "shutdown_request", "requestId": "shutdown-123", "from": "team-lead", "reason": "Done"}MUST call:
Teammate({
operation: "approveShutdown",
request_id: "shutdown-123"
})This sends confirmation and terminates your process.
10. rejectShutdown - Decline Shutdown (Teammate Only)
Teammate({
operation: "rejectShutdown",
request_id: "shutdown-123",
reason: "Still working on task #3, need 5 more minutes"
})11. approvePlan - Approve Teammate's Plan (Leader Only)
When teammate with plan_mode_required sends a plan:
{"type": "plan_approval_request", "from": "architect", "requestId": "plan-456", ...}Approve:
Teammate({
operation: "approvePlan",
target_agent_id: "architect",
request_id: "plan-456"
})12. rejectPlan - Reject Plan with Feedback (Leader Only)
Teammate({
operation: "rejectPlan",
target_agent_id: "architect",
request_id: "plan-456",
feedback: "Please add error handling for the API calls and consider rate limiting"
})13. cleanup - Remove Team Resources
Teammate({ operation: "cleanup" })Removes:
~/.claude/teams/{team-name}/directory~/.claude/tasks/{team-name}/directory
IMPORTANT: Will fail if teammates are still active. Use requestShutdown first.
ia-orchestrating-swarms Specification
Intent
ia-orchestrating-swarms is a workflow-class skill (a multi-step process producing concrete artifacts). Coordinate multi-agent swarms for parallel and pipeline workflows. Use when coordinating multiple agents, running parallel reviews, building pipeline workflows, or implementing divide-and-conquer patterns with subagents.
Scope
In scope:
- Behaviors described in
SKILL.mdand routed via the should_trigger phrasings indistillery/tests/fixtures/triggers/ia-orchestrating-swarms.jsonl. - Updates to runtime behavior, structure, trigger precision, references, and validation.
Out of scope:
- Acting as the runtime instructions themselves (those live in
SKILL.md). - Trigger phrasings already covered by adjacent
ia-*skills (validate-pluginflags >70% description overlap as DUPLICATE_TRIGGER). - <!-- to fill in: domain-specific exclusions when the skill drifts -->
Trigger Context
- Class:
workflow - Hook regex:
plugins/whetstone/hooks/skill-patterns.sh->SKILL_PATTERNS[ia-orchestrating-swarms] - Common requests (from fixture should_trigger):
- "run a multi-agent review of the entire codebase"
- "use parallel agents to analyze each module independently"
- "prevent agents from echoing each other in the multi-agent review"
- Should not trigger for (from fixture should_not_trigger):
- "write a cron job for nightly backups"
- "add validation to the registration form"
- "write a unit test for one helper function"
Source And Evidence Model
Authoritative sources:
SKILL.md-- runtime instructions and reference routing.references/*.md-- bundled supplementary content (15 file(s)).distillery/tests/fixtures/triggers/ia-orchestrating-swarms.jsonl-- positive and negative trigger phrasings under regression test.plugins/whetstone/hooks/skill-patterns.sh-- regex pattern that fires this skill.distillery/.eval-data/ia-orchestrating-swarms/-- harvested session examples (when present).
Data that must not be stored in this skill or its references:
- Secrets, credentials, tokens.
- Machine-specific filesystem paths (
/home/...,/Users/...,~/ai/...). The validator (MACHINE_PATH_LEAK) flags these as HIGH. - Private URLs, customer data, or unredacted personal information.
Coverage matrix
| Dimension | Status | Evidence |
|---|---|---|
| Trigger fixtures | complete | distillery/tests/fixtures/triggers/ia-orchestrating-swarms.jsonl (>=5 should_trigger, >=5 should_not_trigger) |
| Hook regex pattern | complete | plugins/whetstone/hooks/skill-patterns.sh (SKILL_PATTERNS[ia-orchestrating-swarms]) |
| Reference architecture | complete | 15 file(s) under references/ |
| Real-usage signal | <!-- populated by harvest-sessions when sessions exist --> | distillery/.eval-data/ia-orchestrating-swarms/ (created by harvest-sessions) |
Evaluation
Lightweight (run on every change):
python3 distillery/scripts/distiller.py validate-plugin --component ia-orchestrating-swarms
python3 distillery/scripts/distiller.py test-triggers --skill ia-orchestrating-swarmsDeeper (when behavior risk warrants):
python3 distillery/scripts/distiller.py dspy-eval ia-orchestrating-swarms
python3 distillery/scripts/distiller.py diagnose-negatives ia-orchestrating-swarmsAcceptance gates:
validate-plugin --component ia-orchestrating-swarmsreturns 0 HIGH findings.test-triggers --skill ia-orchestrating-swarmsreturns F1 = 1.0 with floors of 5 should_trigger and 5 should_not_trigger.- For dspy-eval, the composite score does not regress against the most recent saved baseline (see
distillery/.eval-data/ia-orchestrating-swarms/history.json).
Known Limitations
<!-- to fill in over time as drift surfaces. Default rule: any time diagnose-negatives surfaces a recurring failure pattern, document it here so future maintainers understand the trade-off the current implementation accepts. -->
Maintenance Notes
- Update
SKILL.mdwhen the runtime workflow, branch conditions, or output contract changes. - Update this
SPEC.mdwhen intent, scope, evidence model, evaluation gates, or maintenance expectations change. - Update the trigger fixture when adding new positive phrasings, removing stale ones, or expanding scope (the 5/5 floor is a hard validator gate).
- Update the hook regex in
skill-patterns.shwhenever fixture positives expose a missed phrasing; verify F1 = 1.0 witheval-triggersbefore committing. - Run the full release pipeline via
/release-- never bump versions or update CHANGELOG.md from a per-skill edit.