Claude Swarm Skill
SkillProductivityOrchestrate parallel Claude Code worker swarms with protocol-based behavioral governance. Use for complex features, large refactors, or multi-step tasks. Supports behavioral constraints, parallel workers, and persistent state across context compactions.
Available today. Use it from your connected AI after setup.
No other account needed.
Connect ahel once, and every AI you use reads what you have installed.
Then ask your AI: use the Claude Swarm Skill skill
What this skill tells your AI
The instructions your AI receives, as published by cj-vana/claude-swarm in skill/SKILL.md and read by ahel’s review.
This skill enables autonomous, multi-hour coding sessions using the claude-swarm MCP server with protocol-based behavioral governance.
Overview
The orchestrator pattern separates concerns:
- Orchestrator (you): Plans work, monitors progress, handles decisions
- Workers: Focused Claude Code sessions that implement individual features
- Protocols: Behavioral constraints that govern what workers can/cannot do
Complete Workflow (Step-by-Step)
Follow these phases in order for every swarm session:
Phase 0: Repository Readiness Check
Before starting any feature work, ensure the repository is ready:
1. ENSURE GITIGNORE (CRITICAL - always do this first):
Check if .gitignore contains swarm state files. If not, add them:
Required entries:
.claude/
claude-progress.txt
init.sh
Run this to add missing entries:
grep -q "^\.claude/" .gitignore 2>/dev/null || echo ".claude/" >> .gitignore
grep -q "^claude-progress.txt" .gitignore 2>/dev/null || echo "claude-progress.txt" >> .gitignore
grep -q "^init.sh" .gitignore 2>/dev/null || echo "init.sh" >> .gitignore
**Why:** Swarm state files must NEVER be committed. They contain session-specific
data, absolute paths, worker logs, and will cause merge conflicts.
2. ANALYZE the repository:
→ setup_analyze(projectDir)
3. IF freshness score >= 50 (missing configurations):
→ setup_init(projectDir)
→ Monitor: setup_status(projectDir)
→ Wait for all setup workers to complete
4. IF freshness score < 50:
→ Proceed to Phase 1 (repo already configured)
Why: Ensures repos have CLAUDE.md, CI, and other essentials before feature work begins.
Phase 0.5: Session Recovery Check
Before starting a new session, check if a previous session crashed:
1. CHECK for crashed session:
→ resume_session(projectDir)
- If crash detected: auto-recovers from checkpoint
- If paused: resumes with pending features listed
- If no session: proceed to Phase 1
2. IF recovered:
→ orchestrator_status(projectDir)
→ Decide: continue existing session or orchestrator_reset to start fresh
Phase 1: Session Setup
1. DECOMPOSE the task into 15-60 minute features
- Each feature should be independently testable
- Order by dependency (foundations first)
2. INITIALIZE the session:
→ orchestrator_init(projectDir, taskDescription, existingFeatures)
3. ANALYZE COMPLEXITY for all features (mandatory):
→ FOR EACH feature:
get_feature_complexity(featureId)
- Records complexity score and recommendation for each feature
- Features with score >= 60 are flagged for competitive planning
- Use these results to inform Phase 3 execution strategy
4. PLAN MODE DECISION:
Ask user: "Enable worker plan mode? Workers will analyze the codebase
and produce a plan before implementing. Orchestrator auto-approves plans."
- If yes: → configure_plan_mode(projectDir, { enabled: true, complexityThreshold: 30 })
- If no: skip (workers implement directly, current behavior)
5. EXECUTION MODE DECISION:
Ask user: "Enable Ralph Loop for long-running autonomy? Workers get fresh
context each iteration and persist progress to files. Best for hours/days-long sessions."
- If yes: → configure_ralph_loop(projectDir, { enabled: true })
- If no: Workers use standard single-run execution
6. OPTIONAL - Set up behavioral constraints:
→ protocol_register(protocol JSON)
→ protocol_activate(protocolId)
7. OPTIONAL - Configure pre-completion verification:
→ configure_verification(commands: ["npm test", "tsc --noEmit"])
8. OPTIONAL - Set feature dependencies:
→ set_dependencies(featureId, dependsOn: ["feature-1", "feature-2"])
Phase 2: Pre-Work Preparation (Per Feature)
Before starting each feature, prepare as needed based on Phase 1 complexity analysis:
1. IF feature complexity >= 60 (from Phase 1 analysis):
→ start_competitive_planning(featureId)
→ sleep 300 (wait 5 minutes for planners)
REVIEW PLANS (recommended for critical features):
→ check_worker(plannerSessionA) # View Planner A's output
→ check_worker(plannerSessionB) # View Planner B's output
EVALUATE AND SELECT:
→ evaluate_plans(featureId) # Automatic selection based on scoring
OR for manual override:
→ evaluate_plans(featureId, manualSelection: "A", selectionReason: "...")
2. OPTIONAL - Enrich with context:
Option A: Automatic discovery
→ enrich_feature(featureId) # Auto-finds relevant docs/code
Option B: Manual/precise context
→ set_feature_context(featureId, documentation: [...])
3. OPTIONAL - Validate against protocols:
→ validate_feature_protocols(featureId)
When to enrich: Use for complex features touching unfamiliar code areas. Skip for simple, isolated changes.
Phase 3: Execution
Choose your execution strategy:
OPTION A: Manual Orchestration (Default)
FOR INDEPENDENT FEATURES (can run simultaneously):
→ validate_workers(featureIds) # Check for conflicts
→ start_parallel_workers(featureIds) # Up to 10 workers
FOR DEPENDENT/SEQUENTIAL FEATURES:
→ start_worker(featureId)
FOR LONG-RUNNING FEATURES (Ralph Loop enabled):
→ start_ralph_loop(featureId) # Fresh context per iteration
---
OPTION B: Hands-Free Orchestration
For fully autonomous execution until completion:
→ auto_orchestrate(projectDir, strategy: "adaptive", maxConcurrent: 5)
Strategies:
- breadth-first: Parallelize independent features first
- depth-first: Focus on unblocking dependent features
- adaptive: Let the system decide based on dependencies
When plan mode is enabled, auto_orchestrate automatically:
- Runs plan phase for features with complexity >= threshold
- Auto-approves plans that score >= 50
- Re-plans up to 2x if rejected, then falls back to direct implementation
When Ralph Loop is enabled, auto_orchestrate automatically:
- Uses fresh-context iteration for each worker
- Tracks progress via filesystem (no context rot)
- Creates periodic checkpoints for crash recovery
Note: auto_orchestrate handles Phases 3-5 automatically, returning when all features complete.
Phase 4: Monitoring Loop
IMPORTANT: Workers take 5-10 minutes. Do NOT check immediately.
1. WAIT before first check:
→ sleep 180 (3 minutes)
2. CHECK status (lightweight):
→ check_worker(featureId, heartbeat: true)
OR
→ check_all_workers(heartbeat: true)
3. IF worker seems stuck (low confidence):
→ get_worker_confidence(featureId)
→ send_worker_message(featureId, "guidance here")
4. IF still running:
→ sleep 120 (wait 2 more minutes)
→ Repeat from step 2
5. IF completed:
→ Proceed to Phase 5
Phase 5: Completion (Per Feature)
1. VERIFY the work:
→ run_verification(command: "npm test")
2. MARK completion:
→ mark_complete(featureId, success: true/false)
- If failed: auto-retry enabled (3 attempts by default)
- If retries exhausted: retry_feature(featureId) to reset
3. CHECKPOINT (on success):
→ commit_progress("feat: description of work")
4. REPEAT Phases 2-5 for next pending feature
Phase 6: Post-Completion Reviews
After ALL features complete, reviews run automatically:
1. MONITOR review progress:
→ check_reviews()
2. GET findings when complete:
→ get_review_results()
3. OPTIONAL - Create follow-up features from issues:
→ implement_review_suggestions(autoSelect: true, minSeverity: "warning")
4. IF new features added:
→ Repeat from Phase 2
Recovery Points
LOST CONTEXT (after compaction)?
→ orchestrator_status(projectDir) # Restores full state
NEED TO PAUSE?
→ pause_session() # Stops all workers
→ resume_session() # Continue later
NEED TO SHUT DOWN (laptop closing, end of day)?
→ shutdown_session(projectDir) # Checkpoints + graceful stop
→ resume_session(projectDir) # Recover next time (auto-detects crash)
SESSION CRASHED (machine sleep, tmux died)?
→ resume_session(projectDir) # Auto-detects crash, recovers from checkpoint
→ resume_session(projectDir, fromCheckpoint: "latest") # Explicit checkpoint recovery
NEED TO ABORT?
→ orchestrator_reset(confirm: true) # Nuclear option
FEATURE FAILED REPEATEDLY?
→ retry_feature(featureId) # Reset attempt counter and try again
FEATURE FAILED AND NEEDS ROLLBACK?
→ check_rollback_conflicts(featureId) # Check for conflicts with parallel workers
→ rollback_feature(featureId) # Restore files to pre-worker state
→ retry_feature(featureId) # Reset attempt counter
Rollback Warning: In parallel environments, rolling back can affect files modified by other concurrent workers. Always run check_rollback_conflicts first to see which files would be affected.
Quick Reference Flowchart
┌─────────────────────────────────────────────────────────────────┐
│ SESSION START │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Phase 0: Ensure .gitignore has swarm files (.claude/, etc.) │
│ → setup_analyze → IF score >= 50: setup_init │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Phase 1: orchestrator_init + get_feature_complexity (all) │
│ └─ Optional: protocols, verification, dependencies │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Phase 2: IF complexity >= 60: competitive_planning → evaluate │
│ └─ Optional: enrich_feature, validate_feature_protocols│
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Phase 3: start_worker OR start_parallel_workers │
│ └─ OR: auto_orchestrate (hands-free execution) │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Phase 4: sleep 180 → check_worker → (loop until complete) │
│ └─ IF stuck: get_worker_confidence, send_worker_message│
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Phase 5: run_verification → mark_complete → commit_progress │
│ └─ Repeat Phase 2-5 for remaining features │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Phase 6: check_reviews → get_review_results │
│ └─ Optional: implement_review_suggestions │
└─────────────────────────────────────────────────────────────────┘
│
▼
SESSION END
Protocol-Based Governance
Protocols define behavioral constraints that govern worker actions. This enables safe autonomous operation with clear boundaries.
Constraint Types
| Type | Description | Example |
|---|---|---|
tool_restriction | Allow/deny specific tools | Only allow Read, Glob, Grep |
file_access | Control file system access | Block access to .env files |
output_format | Require specific output patterns | Must include test coverage |
behavioral | High-level behavior rules | Require confirmation before destructive actions |
temporal | Time-based constraints | Max 30 minutes per feature |
resource | Resource usage limits | Max 100 file operations |
side_effect | Control external effects | No network requests, no git push |
Using Protocols
1. protocol_register - Register a new protocol (JSON definition)
2. protocol_activate - Activate for enforcement
3. start_worker - Workers are validated against active protocols
4. get_violations - Review any constraint violations
5. protocol_deactivate - Deactivate when done
Example Protocol
{
"id": "safe-refactoring-v1",
"name": "Safe Refactoring Protocol",
"version": "1.0.0",
"priority": 100,
"constraints": [
{
"id": "no-secrets",
"type": "file_access",
"rule": {
"type": "file_access",
"deniedPaths": ["**/.env", "**/secrets.*"]
},
"severity": "error",
"message": "Cannot access files that may contain secrets"
}
],
"enforcement": {
"mode": "strict",
"preExecution": true,
"postExecution": true,
"onViolation": "block"
}
}
LLM-Generated Protocols
Workers can propose new protocols validated against immutable base constraints:
1. get_base_constraints - View immutable security rules
2. propose_protocol - Worker submits proposal
3. review_proposals - See pending proposals with risk scores
4. approve_protocol / reject_protocol - Human review for high-risk
Sharing Protocols Across Projects
Protocols can be exported, shared, and synchronized across MCP instances:
EXPORT protocols from current project:
→ export_protocols(projectDir, protocolIds: [...])
- Creates a shareable bundle file
- Optionally sign for integrity verification
IMPORT protocols from bundle:
→ import_protocols(projectDir, bundlePath: "path/to/bundle.json")
- Validates against base constraints
- Conflict strategies: skip, replace, rename, merge
SYNC with peer instances:
→ discover_protocols(projectDir) # Find available peers
→ sync_protocols(projectDir, direction: "pull") # Get protocols from peers
Best Practices
Feature Decomposition
- Each feature should be completable in 15-60 minutes
- Features should be independently testable
- Order features by dependency (foundations first)
- Use
set_dependenciesto enforce ordering when needed
Parallel Execution
- Identify features that can run in parallel (no shared dependencies)
- Use
start_parallel_workersto launch up to 10 workers at once - Monitor all workers with
check_all_workers - Independent features complete faster when parallelized
Monitoring Workers
- Wait 2-3 minutes after starting before first check
- Use
sleep 120orsleep 180between starting and checking - Workers typically complete features in 5-10 minutes
- If stuck after 10+ minutes, review output carefully
- Use
send_worker_messageto provide guidance without restarting
Efficient Monitoring with Heartbeat Mode
Use check_worker with heartbeat: true for lightweight status checks:
check_worker(featureId, heartbeat: true)
-> Returns: status, lastToolUsed, lastFile, lastActivity, runningFor
Competitive Planning for Complex Features
For complex features (score >= 60), use competitive planning:
1. get_feature_complexity(featureId) - Analyze complexity
2. start_competitive_planning(featureId) - Spawn 2 planners
3. Wait for planners to complete (3-5 minutes)
4. evaluate_plans(featureId) - Compare and pick winner
5. start_worker with the winning plan as context
Evaluating Competing Plans (Detailed Guide)
After planners complete, use evaluate_plans to compare their approaches. Understanding the evaluation helps you decide when to accept automatic selection vs. override manually.
Step 1: Review Planner Outputs
Before evaluation, review what each planner produced:
# Quick status check
check_worker(featureId, heartbeat: true)
# Full output review (recommended for critical features)
check_worker(plannerSessionA) # View full Planner A output
check_worker(plannerSessionB) # View full Planner B output
Planners have different approaches by design:
- Planner A: Focuses on incremental, low-risk changes using established patterns
- Planner B: Explores alternative or more elegant approaches, looking for architectural improvements
Step 2: Understand the Scoring System
The automatic evaluation scores plans against five criteria (100 points total):
| Criterion | Points | What It Measures |
|---|---|---|
| Completeness | 25 | Steps defined (3+ ideal), feature keywords addressed, test strategy present |
| Feasibility | 25 | Files to modify exist, reasonable step count (2-10), specific files listed |
| Risk Awareness | 20 | Risks identified, mitigation strategies (prevent, handle, fallback, rollback) |
| Clarity | 15 | Step descriptions >10 chars, validation criteria included, summary 50-500 chars |
| Efficiency | 15 | Optimal step count (2-5 ideal), focused file scope (1-5 files ideal) |
Step 3: Interpret the Results
The evaluation output shows scores and a winner recommendation:
Winner: Plan A
Margin: 12 points
Reason: Plan A selected with moderate advantage. Key strength: Includes risk mitigation strategies
--- Plan A (78/100) ---
Completeness: 22/25
Feasibility: 20/25
Risk Awareness: 18/20
Clarity: 10/15
Efficiency: 8/15
Strengths: Well-structured multi-step approach; Identifies 3 potential risks
Concerns: Large number of files may indicate scope creep
--- Plan B (66/100) ---
...
Margin of Victory Interpretation:
| Margin | Meaning | Recommended Action |
|---|---|---|
| < 5 points | Plans nearly equal | Review both manually; consider domain factors |
| 5-15 points | Moderate advantage | Accept winner unless you have specific concerns |
| >= 15 points | Clear superiority | Accept winner with confidence |
Step 4: When to Use Manual Override
Override automatic selection when:
- Domain knowledge trumps metrics: You know codebase constraints the evaluator cannot detect
- Security-critical features: One plan has better security considerations despite lower score
- Team conventions: One plan follows your team's established patterns better
- Risk tolerance: Your project needs the conservative approach even if it scores slightly lower
- Close margins with red flags: Plans nearly equal but one has concerning "Concerns" in output
Step 5: Making Manual Selections
To override, provide both the selection and reasoning:
evaluate_plans(
featureId,
manualSelection: "B",
selectionReason: "Plan B's approach aligns with our event-driven architecture migration"
)
Good selection reasons include:
- Alignment with architectural direction
- Better handling of specific edge cases
- Consistency with recent team decisions
- Risk considerations for production systems
Example Override Scenarios:
| Scenario | Override To | Example Reason |
|---|---|---|
| Security feature | Conservative plan | "Plan A's incremental approach allows security review at each step" |
| Performance critical | Elegant plan | "Plan B's approach reduces database queries by 60%" |
| Legacy integration | Established patterns | "Plan A uses the same patterns as our existing adapters" |
| Tight deadline | Simpler plan | "Plan A has fewer moving parts, reducing implementation risk" |
Confidence-Based Monitoring
Track worker confidence to detect issues early:
1. set_confidence_threshold(35) - Configure alert threshold
2. get_worker_confidence(featureId) - Get detailed breakdown
Confidence levels:
- High (80-100): On track
- Medium (50-79): Normal operation
- Low (25-49): May need guidance
- Critical (0-24): Immediate attention
Post-Completion Reviews
After all workers complete, automated reviews run automatically:
1. All workers complete -> session transitions to "reviewing" status
2. Code review worker analyzes: bugs, security, style, test coverage
3. Architecture review worker analyzes: coupling, patterns, scalability
4. Findings aggregated into progress log
5. Use get_review_results for detailed findings
6. Use implement_review_suggestions to convert findings into new features
Review configuration:
configure_reviews(enabled: false)- Disable automatic reviewsrun_review(reviewTypes: ["code"])- Manually run specific reviews
Acting on Review Findings
Convert review issues into actionable features:
# View available issues from reviews
implement_review_suggestions(projectDir)
# Create features from specific issues by index
implement_review_suggestions(projectDir, issueIndices: [0, 2, 5])
# Auto-select warnings and errors
implement_review_suggestions(projectDir, autoSelect: true, minSeverity: "warning")
Error Recovery
- Auto-retry is enabled by default (3 attempts) via
mark_complete - Use
retry_featureto manually reset after fixing issues - Use
add_featureif you discover missing work
Session Management
- Use
pause_sessionto gracefully stop work - Use
resume_sessionto continue where you left off - Use
get_session_statsfor success rates and timing
Git Checkpoints
- Commit after each successful feature with
commit_progress - Use descriptive commit messages
- Enables easy rollback if needed
When to Use Protocol Governance
Protocol governance adds behavioral constraints to workers. Use it when you need:
Security Enforcement:
- Restrict dangerous file operations during bulk refactoring
- Prevent accidental production data modification
- Block execution of certain shell commands
Team Policies:
- Enforce code style checking before file writes
- Limit iteration counts on long-running tasks
- Rate limit API calls in multi-worker scenarios
Compliance & Audit:
- Track constraint violations for compliance reports
- Enforce approval workflows for sensitive changes
When NOT to Use:
- Single-feature tasks (overhead not justified)
- Rapid experimentation (approval slows iteration)
- When base constraints are already sufficient
How Workers Can Propose Protocols
Workers can dynamically propose new protocols, validated against immutable base constraints before human review.
Step 1: Check Base Constraints
Before proposing, understand what cannot be overridden:
get_base_constraints(projectDir)
Base constraints include:
- Prohibited tools: rm -rf, sudo, chmod 777, etc.
- Protected paths: ~/.ssh, .env.production, /etc/passwd
- Required enforcement: Pre/post validation always enabled, 30-day audit retention
Step 2: Design the Protocol
propose_protocol(
projectDir,
protocol: {
id: "my-protocol-v1",
version: "1.0.0",
name: "My Protocol Name",
description: "What this protocol does",
constraints: [
{
id: "constraint-1",
type: "file_access", // or: tool_restriction, behavioral, temporal, etc.
severity: "error", // or: warning, info
message: "Human-readable explanation",
rule: {
type: "file_access",
deniedPaths: [".env.production", "config/prod/**"]
}
}
],
enforcement: {
mode: "strict", // or: permissive, audit, learning
preExecutionValidation: true, // REQUIRED by base constraints
postExecutionValidation: true,// REQUIRED by base constraints
onViolation: "block", // or: warn, log, notify
logLevel: "standard"
}
},
description: "Why this protocol is needed",
rationale: "Design decisions and tradeoffs"
)
Step 3: Review Validation Results
Shortened here. Read the whole file on GitHub.
Signals
- GitHub stars
- 111
- Forks
- 10
- Last commit
- Feb 2026
Advanced
- Catalog kind
- skill
- Gateway key
swarm-cj-vana- Source
- github.com/cj-vana/claude-swarm