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-litter

Run it inside Claude Code after adding the marketplace with /plugin marketplace add Und3rf10w/claude-litter.

Contents

Discovered from source

Skills 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:

  1. Use Glob to find all active instances:
Glob: .claude/swarm-loop/*/state.json
  1. If no files are found, report that no swarm loop is running and stop.

  2. Read each state file to extract: session_id, goal, iteration, mode, team_name.

  3. If exactly one instance exists, proceed to cancel it. If multiple instances exist, show a summary table:

Instance IDGoalIterationMode
<id><goal><n><mode>

Then use AskUserQuestion to ask the user which instance to cancel (by ID or number).

  1. Once the target instance is selected, note its directory path: .claude/swarm-loop/<id>/

  2. Read .claude/swarm-loop/<id>/state.json to get the current iteration, team_name, goal, and mode. Then call TaskList to get current task status.

  3. If the state file has a non-null team_name field:

    • 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.
  4. 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.*
  1. Check if any other instances remain:
ls .claude/swarm-loop/*/state.json 2>/dev/null
  1. Restore settings from backup ONLY if no other instances remain:
  • If .claude/settings.local.json.swarm-backup exists, restore it: move .claude/settings.local.json.swarm-backup to .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": true from each event key — preserve any user-defined hooks
    • If a hook event array becomes empty after filtering, remove the event key; if .hooks is 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
  • If other instances remain, skip the settings restore — the running loops still need the hooks.
  1. 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.md is 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

  1. You start with /swarm-loop GOAL --completion-promise 'TEXT'
  2. Setup creates an instance directory under .claude/swarm-loop/<id>/ and generates safety hooks in settings.local.json
  3. The orchestrator creates a persistent team once — the same team is reused for the entire loop (no teardown between iterations)
  4. 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
  5. The Stop hook detects the sentinel file and re-injects the orchestrator prompt to begin the next iteration
  6. If auto-compaction is triggered, the SessionStart hook re-injects context so the loop resumes cleanly
  7. The loop continues until the completion promise is genuinely true (and the optional --verify command 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, or async (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: /deepplan
  • async — 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 N forces at least N iterations (promise suppressed until then). --max-iterations N force-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-swarm tears 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
  • 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 false for supervised sessions.
  • Compact Mode — The orchestrator may optionally run /compact at the end of an iteration to manage context growth. Enabled via swarm-loop.local.md config (compact_on_iteration: true).
  • Heartbeat — The instance heartbeat.json file is updated after each iteration for external monitoring and health checks.
  • Narrative Log — The instance log.md file is the orchestrator's memory across iterations. Failed approaches must be documented here so they are not retried.

Options for /swarm-loop

OptionDescriptionDefault
--completion-promise 'TEXT'Exit condition (required)—
--mode NAMEExecution profile: default, leanswarm, deepplan, asyncdefault
--soft-budget NReflection checkpoint at N iterations10
--min-iterations NHard minimum — promise suppressed until N0 (disabled)
--max-iterations NHard ceiling — force-stop after N iterations0 (unlimited)
--verify 'CMD'Shell command that must pass for exitnone
--safe-mode true|falseEnable autonomous safety hookstrue

Files

PathPurpose
.claude/swarm-loop/<id>/state.jsonStructured state: goal, iteration, phase, team name, autonomy health
.claude/swarm-loop/<id>/log.mdNarrative history — all iterations, decisions, and failed approaches
.claude/swarm-loop/<id>/progress.jsonlAppend-only progress: one JSON line per task completion (written by TaskCompleted gate)
.claude/swarm-loop/<id>/heartbeat.jsonTimestamp and iteration count for external monitoring
.claude/swarm-loop/<id>/next-iterationSentinel file written by orchestrator; consumed by Stop hook
.claude/swarm-loop.local.mdPer-project config: teammate count, model overrides, compact mode (shared across all instances)
.claude/swarm-loop.local.lockConcurrent 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.isolation is set to worktree via /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_isolation in state: if "worktree", use isolation: "worktree" on every Agent call; if "shared" (default), partition file ownership carefully
  • Check teammates_max_count in 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.

  1. Read .claude/swarm-loop.local.md if it exists. If not, use defaults.

  2. Display current settings as a formatted table:

SettingCurrent ValueDescription
compact_on_iterationfalseRun /compact at end of each iteration
clear_on_iterationfalseTrue transcript clearing each iteration via TTY-injected /clear. Requires supported terminal (tmux/kitty/wezterm/screen/zellij/iTerm2/Terminal.app). Supersedes compact_on_iteration.
min_iterations0Minimum iterations before completion promise is honored (0 = disabled)
max_iterations0Hard iteration ceiling, force-stops loop (0 = unlimited)
sentinel_timeout600Seconds before force re-inject if orchestrator stuck
classifier.enabledtrueEnable safety classifier for Bash commands
classifier.modelsonnetModel for classifier (haiku, sonnet, opus)
classifier.effortautoEffort level (low, medium, high, max, auto)
classifier.checks.pre-tool-usetrueClassify Bash commands before execution
classifier.checks.task-completedfalseVerify task completion with agent hook
teammates.isolationworktreeTeammate isolation (shared, worktree)
teammates.max-count8Max simultaneous teammates
notifications.enabledfalseEnable external notifications
notifications.channelnullWebhook URL for notifications
  1. Ask the user which settings they want to change using AskUserQuestion.

  2. Write the updated config back to .claude/swarm-loop.local.md in 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
---
  1. Note: Changes take effect on the NEXT /swarm-loop start, 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_iteration and compact_on_iteration are mutually exclusive (clear discards prior context; compact summarizes it — clear is a strict superset). If the user enables clear_on_iteration, set compact_on_iteration: false in the same write and note the change in your reply. If the user enables compact_on_iteration while clear_on_iteration is already true, refuse the compact change and instruct them to disable clear_on_iteration first.

  2. 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.

  1. 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.

  1. Read each state file found. For each instance, display a brief summary row:
Instance IDGoalIterationPhaseMode
<id><goal><n><phase><mode>
  1. For the current session's instance (match state field session_id against $CLAUDE_CODE_SESSION_ID if 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_health field value
    • Permission Failures: Count of entries in permission_failures array
    • Mode: <mode> (profile)
    • Compact Mode: Whether compact_on_iteration is enabled
    • Min Iterations: min_iterations value (0 = disabled)
    • Max Iterations: max_iterations value (0 = unlimited)
    • Sentinel Timeout: sentinel_timeout value in seconds
  2. Call TaskList to get live task status. Display tasks grouped by status (in_progress, pending, completed) with their owners and any blocked-by dependencies.

  3. If .claude/swarm-loop/<id>/heartbeat.json exists for the selected instance, read it and display:

    • Last Heartbeat: timestamp of last heartbeat
    • Team Active: team_active status from the heartbeat file
  4. Read the last 50 lines of .claude/swarm-loop/<id>/log.md and display as Recent Activity.

  5. If .claude/swarm-loop.local.md exists, read it and display the active configuration settings under Config.

Format all of this as a clean, readable dashboard.

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

More from Und3rf10w/claude-litter

All 3