
swarm-loop
Orchestrated multi-agent loops with profile-based modes. Default: persistent Teams for complex implementation. Deepplan: multi-agent planning with explore/synthesize/critique/deliver. Async: background agent orchestration for independent parallel tasks. Decomposes complex tasks into parallel subtasks, spawns agent teams, tracks progress via native TaskCreate/TaskList, and dynamically re-plans each iteration until verified completion.
- GitHub stars
- 8
Install
/plugin install swarm-loop@claude-litterRun it inside Claude Code after adding the marketplace with /plugin marketplace add Und3rf10w/claude-litter.
Contents
Discovered from sourceSkills 7
Async Swarm Command
Execute the setup script with async mode:
mkdir -p .claude
# Write arguments to a PID-unique file using a quoted heredoc to prevent shell
# expansion of special chars ($, backticks, braces, parens) in user prompts.
_prompt_file=".claude/swarm-loop.local.prompt.$$.md"
cat <<'__SWARM_PROMPT_EOF__' > "$_prompt_file"
$ARGUMENTS
__SWARM_PROMPT_EOF__
"${CLAUDE_PLUGIN_ROOT}/scripts/setup-swarm-loop.sh" --mode async --prompt-file "$_prompt_file"
You are now the ASYNC SWARM ORCHESTRATOR. Follow the instructions output by the setup script exactly.
Async mode uses background agents instead of Teams:
- Agents spawn with run_in_background: true
- No TeamCreate, TeamDelete, or SendMessage
- You get notified when each agent completes
- Each agent is fully independent — no inter-agent coordination
Do NOT call TeamCreate or SendMessage in async mode.
Cancel Swarm Loop
Check for active swarm loop instances and cancel the selected one:
- Use Glob to find all active instances:
Glob: .claude/swarm-loop/*/state.json
-
If no files are found, report that no swarm loop is running and stop.
-
Read each state file to extract:
session_id,goal,iteration,mode,team_name. -
If exactly one instance exists, proceed to cancel it. If multiple instances exist, show a summary table:
| Instance ID | Goal | Iteration | Mode |
|---|---|---|---|
<id> | <goal> | <n> | <mode> |
Then use AskUserQuestion to ask the user which instance to cancel (by ID or number).
-
Once the target instance is selected, note its directory path:
.claude/swarm-loop/<id>/ -
Read
.claude/swarm-loop/<id>/state.jsonto get the current iteration, team_name, goal, and mode. Then callTaskListto get current task status. -
If the state file has a non-null
team_namefield:- Send a shutdown_request to all teammates via SendMessage (broadcast to
"*") - Call TeamDelete to clean up the team and all associated task records
- Note: This is the ONLY place TeamDelete is called. Normal loop completion shuts down teammates but does NOT call TeamDelete.
- If TeamDelete fails (team already gone), continue anyway.
- Send a shutdown_request to all teammates via SendMessage (broadcast to
-
Remove swarm loop files for the selected instance (preserve log.md for reference):
rm .claude/swarm-loop/<id>/state.json
rm -f .claude/swarm-loop/<id>/verify.sh
rm -f .claude/swarm-loop/<id>/next-iteration
rm -f .claude/swarm-loop/<id>/heartbeat.json
rm -f .claude/swarm-loop/<id>/deepplan.*
rm -f .claude/swarm-loop/<id>/progress.jsonl
rm -f .claude/swarm-loop/<id>/.idle-retry.*
- Check if any other instances remain:
ls .claude/swarm-loop/*/state.json 2>/dev/null
- Restore settings from backup ONLY if no other instances remain:
- If
.claude/settings.local.json.swarm-backupexists, restore it: move.claude/settings.local.json.swarm-backupto.claude/settings.local.json - If no backup exists, fall back to selectively removing only swarm-generated content from
settings.local.json:- Remove entries containing "swarm-loop" from
permissions.allow - Remove only hook matcher objects tagged with
"_swarm": truefrom each event key — preserve any user-defined hooks - If a hook event array becomes empty after filtering, remove the event key; if
.hooksis empty, remove it entirely - Use jq:
jq '.permissions.allow = ([.permissions.allow[]? | select(test("swarm-loop|deepplan") | not)] | unique) | if .hooks then .hooks |= with_entries(.value = [.value[]? | select(._swarm != true)] | select(.value | length > 0)) | if (.hooks | length) == 0 then del(.hooks) else . end else . end' .claude/settings.local.json
- Remove entries containing "swarm-loop" from
- If other instances remain, skip the settings restore — the running loops still need the hooks.
- Report to the user:
- The goal that was being worked on
- The mode (profile) in use at the time of cancellation
- Current iteration number at the time of cancellation
- Task status summary from
TaskList(how many completed, in-progress, pending) - Confirm all files were cleaned up
- Note that
.claude/swarm-loop/<id>/log.mdis preserved for reference
Do NOT delete the instance log file — it contains valuable history the user may want to review.
Note: If teammates were using worktree isolation, Claude Code normally cleans up worktrees when agents finish. If cancellation kills teammates mid-work, orphaned worktrees may remain at .claude/worktrees/. These can be cleaned up manually with git worktree list and git worktree remove.
Deepplan Command
Execute the setup script with deepplan mode:
mkdir -p .claude
# Write arguments to a PID-unique file using a quoted heredoc to prevent shell
# expansion of special chars ($, backticks, braces, parens) in user prompts.
_prompt_file=".claude/swarm-loop.local.prompt.$$.md"
cat <<'__SWARM_PROMPT_EOF__' > "$_prompt_file"
$ARGUMENTS
__SWARM_PROMPT_EOF__
"${CLAUDE_PLUGIN_ROOT}/scripts/setup-swarm-loop.sh" --mode deepplan --prompt-file "$_prompt_file"
You are now the DEEPPLAN ORCHESTRATOR. Follow the instructions output by the setup script exactly.
Deepplan mode uses a persistent team with diverse-perspective teammates:
- Phase 1: 3 scout teammates (architect, pathfinder, adversary) explore in parallel
- Phase 2: Orchestrator synthesizes findings into structured plan
- Phase 3: 2 critique teammates (pragmatist, strategist) review the draft from opposing angles; orchestrator revises based on their feedback
- Phase 4: Deliver revised plan via ExitPlanMode for user approval
Do not skip the exploration and critique phases. Do not implement — plan only.
Swarm Loop Help
Swarm Loop (v2.0) is an orchestrated multi-agent iterative development system. It uses a persistent agent team, hook-based safety controls, and a sentinel-file mechanism to drive autonomous loops until a user-defined completion promise is fulfilled.
How It Works
- You start with
/swarm-loop GOAL --completion-promise 'TEXT' - Setup creates an instance directory under
.claude/swarm-loop/<id>/and generates safety hooks insettings.local.json - The orchestrator creates a persistent team once — the same team is reused for the entire loop (no teardown between iterations)
- Each iteration runs through these phases:
- ASSESS — review state, log, and prior results
- PLAN — decompose outstanding work into parallel subtasks
- EXECUTE — delegate subtasks to teammates; teammates report back via SendMessage
- MONITOR — receive teammate completion messages; persist results immediately to state and log (microcompact may clear old messages)
- VERIFY — check whether the completion promise is genuinely fulfilled
- PERSIST — write iteration summary to narrative log and update heartbeat
- SIGNAL — write the instance sentinel file (Write tool, empty content); end turn
- The Stop hook detects the sentinel file and re-injects the orchestrator prompt to begin the next iteration
- If auto-compaction is triggered, the SessionStart hook re-injects context so the loop resumes cleanly
- The loop continues until the completion promise is genuinely true (and the optional
--verifycommand passes)
Commands
/swarm-loop GOAL --completion-promise 'TEXT'
Start a new loop. The --completion-promise is required — it is the only exit mechanism.
Options:
--completion-promise 'TEXT'(required) — Statement that must be true for the loop to end--mode NAME— Execution profile:default,leanswarm,deepplan, orasync(default:default)--soft-budget N— Iteration count for a progress checkpoint (default: 10, not a hard limit)--min-iterations N— Hard minimum — promise suppressed until N iterations complete (default: 0, disabled)--max-iterations N— Hard ceiling — force-stops loop after N iterations (default: 0, unlimited)--verify 'CMD'— Shell command that must also pass before the loop exits (e.g.,npm test)--safe-mode true|false— Enable/disable autonomous safe mode (default: true)
Examples:
/swarm-loop Build a REST API with auth and tests --completion-promise 'All endpoints work and tests pass'
/swarm-loop Refactor auth to JWT --completion-promise 'JWT auth working' --verify 'npm test'
/swarm-loop Migrate to TypeScript --completion-promise 'All files converted' --soft-budget 20
/swarm-loop Thorough refactor --completion-promise 'All refactored' --min-iterations 3 --max-iterations 10
/swarm-status
View the current progress dashboard: iteration count, phase, mode, task status, team roster, and recent log entries.
/cancel-swarm
Stop the loop, shut down the active team (TeamDelete is called here and only here), and clean up the sentinel file and state file. The instance log file (.claude/swarm-loop/<id>/log.md) is preserved for reference.
/swarm-help
Show this help text.
/swarm-settings
Configure safety controls, teammate count, compact mode, and notification preferences. Changes take effect on the next /swarm-loop start.
/deepplan
Alias for /swarm-loop with --mode deepplan. Runs multi-agent planning with explore/synthesize/critique/deliver phases.
/async-swarm
Alias for /swarm-loop with --mode async. Runs background agent orchestration for independent parallel tasks.
Profiles
Select an execution profile with --mode NAME:
default— Persistent Teams with TaskCreate coordination. Best for complex multi-file implementation.leanswarm— Lean 4-concern orchestration (WORK/MONITOR/VERIFY/SIGNAL). Same Teams coordination as default with less prescriptive scaffolding. Best for capable models on complex tasks.deepplan— Multi-agent planning with explore/synthesize/critique/deliver phases. Best for codebase analysis and structured plans. Alias:/deepplanasync— Background agent orchestration with run_in_background. Best for independent parallel tasks. Alias:/async-swarm
Key Concepts
- Completion Promise — The primary exit mechanism. The orchestrator outputs
<promise>TEXT</promise>when the statement is genuinely true. The loop will not exit on a soft budget alone. - Iteration Bounds —
--min-iterations Nforces at least N iterations (promise suppressed until then).--max-iterations Nforce-stops the loop after N iterations regardless of promise. Both are optional and independent of--soft-budget. - Persistent Team — Created once at loop start and reused across all iterations. TeamDelete is never called between iterations; only
/cancel-swarmtears the team down. - Native Tasks — TaskCreate/TaskUpdate/TaskList is the primary progress tracker. The state file mirrors this for external visibility.
- Sentinel File — The instance sentinel file signals that the current iteration is complete. The Stop hook consumes this file and re-injects the orchestrator prompt.
- Hook-Based Safety — Dynamic hooks installed in
settings.local.json: PermissionRequest (auto-approve safe operations), PreToolUse (classifier blocks dangerous operations), SubagentStart (injects context into each teammate). Additionally, three team coordination hooks enforce task discipline:- TeammateIdle gate (static,
hooks.json) — forces teammates to complete tasks + send results before going idle (up to 3 retries) - TaskCompleted gate (dynamic) — append-only progress tracking via
progress.jsonl+ deepplan artifact verification via task metadata - TaskCreated gate (dynamic) — max task cap enforcement + deepplan scope classifier (blocks implementation tasks)
- SubagentStop cleanup (dynamic) — logs teammate crash recovery when teammates stop with in_progress tasks; captures last_assistant_message for debugging
- StopFailure observability (dynamic) — logs API errors (rate limit, billing, server), sets autonomy_health to degraded, updates heartbeat with error status
- PreCompact context injection (static,
hooks.json) — injects swarm orchestrator context (goal, iteration, team, task status) into compaction so post-compact model retains orchestrator identity
- TeammateIdle gate (static,
- Safe Mode — When enabled (default), hooks allow autonomous file edits within the project but block force pushes, external code execution, and credential access. Disable with
--safe-mode falsefor supervised sessions. - Compact Mode — The orchestrator may optionally run
/compactat the end of an iteration to manage context growth. Enabled viaswarm-loop.local.mdconfig (compact_on_iteration: true). - Heartbeat — The instance
heartbeat.jsonfile is updated after each iteration for external monitoring and health checks. - Narrative Log — The instance
log.mdfile is the orchestrator's memory across iterations. Failed approaches must be documented here so they are not retried.
Options for /swarm-loop
| Option | Description | Default |
|---|---|---|
--completion-promise 'TEXT' | Exit condition (required) | — |
--mode NAME | Execution profile: default, leanswarm, deepplan, async | default |
--soft-budget N | Reflection checkpoint at N iterations | 10 |
--min-iterations N | Hard minimum — promise suppressed until N | 0 (disabled) |
--max-iterations N | Hard ceiling — force-stop after N iterations | 0 (unlimited) |
--verify 'CMD' | Shell command that must pass for exit | none |
--safe-mode true|false | Enable autonomous safety hooks | true |
Files
| Path | Purpose |
|---|---|
.claude/swarm-loop/<id>/state.json | Structured state: goal, iteration, phase, team name, autonomy health |
.claude/swarm-loop/<id>/log.md | Narrative history — all iterations, decisions, and failed approaches |
.claude/swarm-loop/<id>/progress.jsonl | Append-only progress: one JSON line per task completion (written by TaskCompleted gate) |
.claude/swarm-loop/<id>/heartbeat.json | Timestamp and iteration count for external monitoring |
.claude/swarm-loop/<id>/next-iteration | Sentinel file written by orchestrator; consumed by Stop hook |
.claude/swarm-loop.local.md | Per-project config: teammate count, model overrides, compact mode (shared across all instances) |
.claude/swarm-loop.local.lock | Concurrent setup guard: prevents two /swarm-loop invocations from racing during initialization |
Multi-Instance Support
Each /swarm-loop invocation creates an isolated instance directory under .claude/swarm-loop/<id>/ where <id> is derived from the session. This allows multiple loops to run concurrently in the same repo from different terminal sessions.
Use /swarm-status to see all active instances. Use /cancel-swarm to select and stop a specific instance.
Requirements
- Agent teams: The TeamCreate tool must be available (experimental agent teams feature)
- jq: Required for state file manipulation in hooks
- perl: Required for completion promise extraction in the Stop hook
- Git repository: Required only when
teammates.isolationis set toworktreevia/swarm-settings. Not needed for the default shared-checkout mode.
Swarm Loop Command
Execute the setup script to initialize the swarm loop:
mkdir -p .claude
# Write arguments to a PID-unique file using a quoted heredoc to prevent shell
# expansion of special chars ($, backticks, braces, parens) in user prompts.
# The setup script's --prompt-file flag reads the goal from this file and parses flags from it.
_prompt_file=".claude/swarm-loop.local.prompt.$$.md"
cat <<'__SWARM_PROMPT_EOF__' > "$_prompt_file"
$ARGUMENTS
__SWARM_PROMPT_EOF__
"${CLAUDE_PLUGIN_ROOT}/scripts/setup-swarm-loop.sh" --prompt-file "$_prompt_file"
You are now the SWARM LOOP ORCHESTRATOR. Follow the instructions output by the setup script exactly.
Use --mode deepplan for multi-agent planning or --mode async for background-agent orchestration. See /swarm-help for details.
Key things to remember:
- Read the instance state file (path shown in setup output) and the instance log file at the start of each iteration
- The team is persistent — call TeamCreate ONCE at loop start (team_name is in the instance state file), do NOT recreate it between iterations
- Use native TaskCreate/TaskUpdate/TaskList for ALL task tracking — there is no tasks[] array in the state file
- Check
teammates_isolationin state: if "worktree", useisolation: "worktree"on every Agent call; if "shared" (default), partition file ownership carefully - Check
teammates_max_countin state: do not spawn more than this many teammates at once - Use TaskCreate with blockedBy dependencies to model the work graph; spawn teammates via Agent tool into the persistent team
- Each iteration follows the 7-step cycle: ASSESS → PLAN → EXECUTE → MONITOR → VERIFY → PERSIST → SIGNAL
- In MONITOR: persist each teammate's result to the instance log file and update last_updated in state IMMEDIATELY on receipt — do not defer to PERSIST (microcompact risk). Progress tracking to progress.jsonl is handled automatically by the TaskCompleted gate hook.
- In SIGNAL: if compact_on_iteration is enabled, run /compact BEFORE writing the sentinel
- Write the instance sentinel file (empty content) to signal the stop hook to start the next iteration
- Do NOT call TeamDelete — only /cancel-swarm calls TeamDelete; normal loop completion shuts down teammates but leaves the team intact
- Configure loop settings (compact mode, classifier, notifications, etc.) via /swarm-settings
CRITICAL: If a completion promise is set, you may ONLY output it when the statement is completely and unequivocally TRUE. Do not output false promises to escape the loop.
NOTE: Safe mode (default: true) enables auto-approval for file edits and injects safety context into teammates. Use --safe-mode false for supervised sessions where you want manual approval for all operations.
Swarm Settings
Configure the swarm loop behavior. Settings are stored in .claude/swarm-loop.local.md and read by the setup script when a new loop starts.
-
Read
.claude/swarm-loop.local.mdif it exists. If not, use defaults. -
Display current settings as a formatted table:
| Setting | Current Value | Description |
|---|---|---|
| compact_on_iteration | false | Run /compact at end of each iteration |
| clear_on_iteration | false | True transcript clearing each iteration via TTY-injected /clear. Requires supported terminal (tmux/kitty/wezterm/screen/zellij/iTerm2/Terminal.app). Supersedes compact_on_iteration. |
| min_iterations | 0 | Minimum iterations before completion promise is honored (0 = disabled) |
| max_iterations | 0 | Hard iteration ceiling, force-stops loop (0 = unlimited) |
| sentinel_timeout | 600 | Seconds before force re-inject if orchestrator stuck |
| classifier.enabled | true | Enable safety classifier for Bash commands |
| classifier.model | sonnet | Model for classifier (haiku, sonnet, opus) |
| classifier.effort | auto | Effort level (low, medium, high, max, auto) |
| classifier.checks.pre-tool-use | true | Classify Bash commands before execution |
| classifier.checks.task-completed | false | Verify task completion with agent hook |
| teammates.isolation | worktree | Teammate isolation (shared, worktree) |
| teammates.max-count | 8 | Max simultaneous teammates |
| notifications.enabled | false | Enable external notifications |
| notifications.channel | null | Webhook URL for notifications |
-
Ask the user which settings they want to change using AskUserQuestion.
-
Write the updated config back to
.claude/swarm-loop.local.mdin YAML frontmatter format:
---
compact_on_iteration: false
clear_on_iteration: false
min_iterations: 0
max_iterations: 0
sentinel_timeout: 600
classifier:
enabled: true
model: sonnet
effort: auto
checks:
pre-tool-use: true
task-completed: false
teammates:
isolation: worktree
max-count: 8
notifications:
enabled: false
channel: null
---
-
Note: Changes take effect on the NEXT
/swarm-loopstart, not the current running loop. To change settings for a running loop, edit the instance state file (.claude/swarm-loop/<id>/state.json) directly.Mutex:
clear_on_iterationandcompact_on_iterationare mutually exclusive (clear discards prior context; compact summarizes it — clear is a strict superset). If the user enablesclear_on_iteration, setcompact_on_iteration: falsein the same write and note the change in your reply. If the user enablescompact_on_iterationwhileclear_on_iterationis already true, refuse the compact change and instruct them to disableclear_on_iterationfirst. -
If classifier.effort is set to a specific level (low/medium/high/max — not auto), the PreToolUse hook uses
claude -p --bare --effort <level>(command hook) instead of a native prompt hook. Valid effort levels:low,medium,high,max(opus only),auto.
Swarm Status
Display the current status of all active swarm loop instances.
- Use Glob to find all active instances:
Glob: .claude/swarm-loop/*/state.json
If no files are found, report that no swarm loop is currently active and stop.
- Read each state file found. For each instance, display a brief summary row:
| Instance ID | Goal | Iteration | Phase | Mode |
|---|---|---|---|---|
<id> | <goal> | <n> | <phase> | <mode> |
-
For the current session's instance (match state field
session_idagainst$CLAUDE_CODE_SESSION_IDif available, or show all if the env var is unavailable), display detailed status:- Goal: The objective being worked on
- Iteration: Current iteration number
- Phase: Current phase (initial, working, delivering, refining, rejected, complete)
- Autonomy Health:
autonomy_healthfield value - Permission Failures: Count of entries in
permission_failuresarray - Mode:
<mode>(profile) - Compact Mode: Whether
compact_on_iterationis enabled - Min Iterations:
min_iterationsvalue (0 = disabled) - Max Iterations:
max_iterationsvalue (0 = unlimited) - Sentinel Timeout:
sentinel_timeoutvalue in seconds
-
Call
TaskListto get live task status. Display tasks grouped by status (in_progress, pending, completed) with their owners and any blocked-by dependencies. -
If
.claude/swarm-loop/<id>/heartbeat.jsonexists for the selected instance, read it and display:- Last Heartbeat: timestamp of last heartbeat
- Team Active:
team_activestatus from the heartbeat file
-
Read the last 50 lines of
.claude/swarm-loop/<id>/log.mdand display as Recent Activity. -
If
.claude/swarm-loop.local.mdexists, read it and display the active configuration settings under Config.
Format all of this as a clean, readable dashboard.
Hooks 3
Sponsors
Details
- Marketplace
- Und3rf10w/claude-litter
- Source
- plugins/swarm-loop
- Author
- Und3rf10w
- Category
- Automation
- Keywords
- ralph, ralph wiggum, ralph-loop, swarm, team, orchestration, deepplan, async, profiles, planning