spacehub

surshar / claude-code

Claude Code is an agentic coding tool that lives in your terminal, understands your codebase, and helps you code faster by executing routine tasks, explaining complex code, and handling git workflows - all through natural language commands.

Built by Anthropic · github.com/anthropics

feat: Add swarm-coordination plugin for multi-agent conflict preventionBrowse files
Implements three complementary patterns for coordinating multi-agent swarms:

1. Status Polling (Fix 1): Orchestrator periodically spawns status-checker
   agents to monitor swarm health, detect stuck agents, and identify
   conflicts early.

2. File Claiming (Fix 2): Agents claim file ownership before editing via
   a claims registry (.claude/file-claims.md). Prevents multiple agents
   from editing the same file simultaneously.

3. Checkpoint-Based Orchestration (Fix 5): Separates swarm execution into
   phases - planning (read-only), conflict detection, resolution, then
   implementation with monitoring.

Plugin contents:
- /swarm command for full orchestrated workflow
- status-checker agent (haiku, lightweight polling)
- conflict-detector agent (analyzes plans for overlaps)
- plan-reviewer agent (validates individual plans)
- swarm-patterns skill with comprehensive documentation
Claude authored on Dec 12, 2025 parent 2192c86 · commit 2a0197e654e5
11 changed files+1771 -0compared with 2192c86
Aplugins/swarm-coordination/.claude-plugin/plugin.json
Aplugins/swarm-coordination/README.md
Aplugins/swarm-coordination/agents/conflict-detector.md
Aplugins/swarm-coordination/agents/plan-reviewer.md
Aplugins/swarm-coordination/agents/status-checker.md
Aplugins/swarm-coordination/commands/swarm.md
Aplugins/swarm-coordination/skills/swarm-patterns/SKILL.md
Aplugins/swarm-coordination/skills/swarm-patterns/examples/simple-swarm.md
Aplugins/swarm-coordination/skills/swarm-patterns/references/checkpoint-flow.md
Aplugins/swarm-coordination/skills/swarm-patterns/references/file-claiming.md
Aplugins/swarm-coordination/skills/swarm-patterns/references/status-polling.md
@@ -1,0 +1,7 @@
1+{
2+ "name": "swarm-coordination",
3+ "version": "1.0.0",
4+ "description": "Coordinates multi-agent swarms with status polling, file claiming, and checkpoint-based orchestration to prevent conflicts and enable proactive monitoring",
5+ "author": "Anthropic",
6+ "keywords": ["swarm", "multi-agent", "coordination", "orchestration", "parallel"]
7+}
@@ -1,0 +1,152 @@
1+# Swarm Coordination Plugin
2+
3+Coordinate multi-agent swarms with conflict prevention, status polling, and checkpoint-based orchestration.
4+
5+## The Problem
6+
7+When multiple agents work in parallel on the same codebase, they can:
8+- Edit the same files simultaneously, creating conflicts
9+- Make changes that overwrite each other
10+- Get stuck in endless loops trying to "fix" each other's code
11+- Waste effort with duplicate work
12+
13+## The Solution
14+
15+This plugin implements three complementary coordination patterns:
16+
17+### 1. Status Polling (Proactive Monitoring)
18+
19+The orchestrator periodically spawns lightweight status-checker agents to monitor swarm health:
20+- Detect stuck or failed agents early
21+- Identify file conflicts as they emerge
22+- Enable dynamic load balancing
23+- Provide real-time progress visibility
24+
25+### 2. File Claiming (Ownership Convention)
26+
27+Agents claim file ownership before editing:
28+- Prevents multiple agents from editing the same file
29+- Clear ownership registry in `.claude/file-claims.md`
30+- Agents skip files claimed by others
31+- Claims released after completion
32+
33+### 3. Checkpoint-Based Orchestration (Phased Execution)
34+
35+Separate swarm execution into controlled phases:
36+1. **Planning** - Agents analyze and plan (read-only, parallel)
37+2. **Review** - Detect conflicts before implementation
38+3. **Resolution** - Resolve conflicts with user input
39+4. **Implementation** - Execute with monitoring
40+5. **Verification** - Validate results
41+
42+## Quick Start
43+
44+### Using the `/swarm` Command
45+
46+```
47+/swarm Implement user authentication with JWT tokens and session management
48+```
49+
50+The command will guide you through:
51+1. Initializing coordination files
52+2. Launching planning agents
53+3. Reviewing and resolving conflicts
54+4. Executing implementation with monitoring
55+5. Verifying completion
56+
57+### Manual Coordination
58+
59+For custom workflows, use the individual components:
60+
61+1. Create coordination files:
62+ - `.claude/swarm-status.json`
63+ - `.claude/file-claims.md`
64+ - `.claude/swarm-plans/`
65+
66+2. Include file claiming instructions in agent prompts
67+
68+3. Launch status-checker periodically during execution
69+
70+## Plugin Contents
71+
72+### Commands
73+- `/swarm [task]` - Full orchestrated swarm workflow
74+
75+### Agents
76+- `status-checker` - Monitors swarm health (haiku, fast)
77+- `conflict-detector` - Analyzes plans for conflicts
78+- `plan-reviewer` - Validates individual agent plans
79+
80+### Skills
81+- `swarm-patterns` - Documentation and examples
82+
83+## Coordination Files
84+
85+### `.claude/swarm-status.json`
86+```json
87+{
88+ "swarm_id": "feature-impl-001",
89+ "task": "Implement new feature",
90+ "phase": "implementing",
91+ "agents": {
92+ "agent-1": {"status": "working"},
93+ "agent-2": {"status": "completed"}
94+ }
95+}
96+```
97+
98+### `.claude/file-claims.md`
99+```markdown
100+| Agent ID | File Path | Claimed At | Status |
101+|----------|-----------|------------|--------|
102+| agent-1 | src/api/handler.ts | 2025-01-15T10:00:00Z | claimed |
103+| agent-2 | src/db/schema.ts | 2025-01-15T10:00:00Z | released |
104+```
105+
106+## Best Practices
107+
108+1. **Always use planning phase** - Never skip to implementation
109+2. **Resolve all conflicts** - Don't proceed with overlapping claims
110+3. **Poll regularly** - Every 30-60 seconds during execution
111+4. **Use haiku for status checks** - Fast and cheap
112+5. **Release claims promptly** - Don't hold after completion
113+
114+## When to Use
115+
116+Use this plugin when:
117+- Multiple agents need to work on the same codebase
118+- Tasks require parallel execution for speed
119+- You've experienced agent conflicts before
120+- You need visibility into swarm progress
121+
122+## When NOT to Use
123+
124+Skip this plugin when:
125+- Single agent is sufficient
126+- Agents work on completely separate codebases
127+- Tasks are purely read-only (no file modifications)
128+
129+## Troubleshooting
130+
131+### Agents Still Conflict
132+- Ensure all agents include file claiming instructions
133+- Verify conflict detection ran before implementation
134+- Check that claims registry is being read
135+
136+### Status Checker Shows Stuck Agents
137+- Check agent logs for errors
138+- Consider increasing timeout
139+- May need to reassign work
140+
141+### Claims Not Releasing
142+- Verify agent completion is being tracked
143+- Manually update claims if needed
144+- Check for orchestrator errors
145+
146+## Learn More
147+
148+See the `swarm-patterns` skill for detailed documentation:
149+- `references/status-polling.md` - Polling patterns
150+- `references/file-claiming.md` - Claiming conventions
151+- `references/checkpoint-flow.md` - Phased orchestration
152+- `examples/simple-swarm.md` - Complete example
@@ -1,0 +1,108 @@
1+---
2+name: conflict-detector
3+description: Analyzes agent implementation plans to detect file conflicts before execution. Used in checkpoint-based orchestration to review plans and identify overlapping file edits.
4+tools: Read, Glob, Grep
5+model: sonnet
6+color: orange
7+---
8+
9+You are an expert conflict analyst specializing in detecting potential file conflicts between multiple agent implementation plans.
10+
11+## Core Mission
12+
13+Review planned changes from multiple agents and identify any files that would be modified by more than one agent, enabling conflict resolution BEFORE implementation begins.
14+
15+## Analysis Process
16+
17+**1. Gather Plans**
18+- Read `.claude/swarm-plans/` directory for all agent plans
19+- Parse each plan to extract:
20+ - Files to be created
21+ - Files to be modified
22+ - Files to be deleted
23+ - Dependencies on other files
24+
25+**2. Build File Map**
26+Create a mapping of file → agents planning to touch it:
27+```
28+src/api/handler.ts → [agent-1 (modify), agent-3 (modify)]
29+src/utils/helper.ts → [agent-2 (create)]
30+src/types/index.ts → [agent-1 (modify), agent-2 (modify), agent-3 (modify)]
31+```
32+
33+**3. Identify Conflicts**
34+- **Direct conflicts**: Multiple agents modifying same file
35+- **Creation conflicts**: Multiple agents creating same file
36+- **Dependency conflicts**: Agent B depends on file Agent A will modify
37+- **Deletion conflicts**: Agent modifying file another will delete
38+
39+**4. Assess Severity**
40+- **Critical**: Same function/class being modified differently
41+- **Major**: Same file, different sections
42+- **Minor**: Related files that might have import issues
43+- **Info**: Same directory but different files
44+
45+**5. Generate Resolution Strategies**
46+For each conflict, suggest:
47+- Which agent should handle the file
48+- How to sequence the work
49+- Alternative approaches to avoid conflict
50+
51+## Output Format
52+
53+```markdown
54+## Conflict Analysis Report
55+
56+### Summary
57+- Total files planned for modification: [N]
58+- Files with conflicts: [N]
59+- Critical conflicts: [N]
60+- Agents analyzed: [list]
61+
62+### Critical Conflicts (Must Resolve)
63+
64+#### Conflict 1: `src/api/handler.ts`
65+**Agents involved**: agent-1, agent-3
66+**Nature**: Both agents plan to modify the `handleRequest` function
67+**Agent-1 plan**: Add authentication check
68+**Agent-3 plan**: Add rate limiting wrapper
69+
70+**Resolution options**:
71+1. **Sequence**: Have agent-1 complete first, then agent-3 builds on top
72+2. **Merge**: Combine both changes into a single agent's scope
73+3. **Split**: Agent-1 handles auth in middleware, agent-3 handles rate limiting in handler
74+
75+**Recommended**: Option 1 - Sequential execution
76+
77+---
78+
79+### Major Conflicts (Should Review)
80+[Similar format]
81+
82+### Minor Conflicts (Informational)
83+[Similar format]
84+
85+### Conflict-Free Assignments
86+These agents can proceed in parallel without issues:
87+- agent-2: Only touches `src/utils/` (no overlap)
88+- agent-4: Only touches `tests/` (no overlap)
89+
90+### Recommended Execution Order
91+1. **Parallel batch 1**: agent-2, agent-4 (no conflicts)
92+2. **Sequential**: agent-1 (depends on nothing, blocks agent-3)
93+3. **Sequential**: agent-3 (depends on agent-1 completion)
94+```
95+
96+## Quality Standards
97+
98+- Every conflict includes specific file paths
99+- Resolution options are actionable
100+- Recommended execution order is provided
101+- False positives minimized (understand semantic conflicts, not just file overlap)
102+
103+## Edge Cases
104+
105+- **No plans found**: Report "No agent plans to analyze"
106+- **No conflicts**: Report "All agents have non-overlapping scopes"
107+- **Circular dependencies**: Flag as critical, require manual resolution
108+- **Unclear plan scope**: Flag for clarification rather than assuming
@@ -1,0 +1,124 @@
1+---
2+name: plan-reviewer
3+description: Reviews an individual agent's implementation plan for completeness, feasibility, and clarity. Used during the planning phase of checkpoint-based orchestration.
4+tools: Read, Glob, Grep
5+model: sonnet
6+color: blue
7+---
8+
9+You are an expert plan reviewer specializing in validating implementation plans for autonomous agents.
10+
11+## Core Mission
12+
13+Review an agent's implementation plan to ensure it is complete, feasible, and specific enough to execute without ambiguity. Flag issues before the agent begins implementation.
14+
15+## Review Process
16+
17+**1. Parse Plan Structure**
18+- Verify plan follows expected format
19+- Check all required sections are present
20+- Ensure file lists are explicit
21+
22+**2. Validate Scope**
23+- Files to modify are clearly listed with full paths
24+- Changes are described with enough detail
25+- No vague statements like "update as needed"
26+
27+**3. Check Feasibility**
28+- Files mentioned actually exist (or creation is explicit)
29+- Dependencies are identified
30+- No impossible or conflicting requirements
31+
32+**4. Assess Risk**
33+- High-risk changes flagged (deleting files, changing interfaces)
34+- Breaking changes identified
35+- Rollback complexity noted
36+
37+**5. Verify Completeness**
38+- All aspects of the task are addressed
39+- Edge cases considered
40+- Testing approach included (if applicable)
41+
42+## Plan Format Expected
43+
44+```markdown
45+## Agent Plan: [agent-id]
46+
47+### Task Summary
48+[What this agent will accomplish]
49+
50+### Files to Modify
51+- `path/to/file1.ts`: [Description of changes]
52+- `path/to/file2.ts`: [Description of changes]
53+
54+### Files to Create
55+- `path/to/new-file.ts`: [Purpose and contents summary]
56+
57+### Files to Delete
58+- `path/to/old-file.ts`: [Reason for deletion]
59+
60+### Dependencies
61+- Requires: [files/features this depends on]
62+- Blocks: [what cannot proceed until this completes]
63+
64+### Implementation Steps
65+1. [Step 1]
66+2. [Step 2]
67+...
68+
69+### Risks and Mitigations
70+- [Risk]: [Mitigation]
71+```
72+
73+## Output Format
74+
75+```markdown
76+## Plan Review: [agent-id]
77+
78+### Overall Assessment: [APPROVED|NEEDS_REVISION|REJECTED]
79+
80+### Checklist
81+- [x] Clear task summary
82+- [x] Explicit file list
83+- [ ] Missing: dependency identification
84+- [x] Feasible changes
85+- [ ] Issue: vague step description
86+
87+### Issues Found
88+
89+#### Critical (Must Fix)
90+1. **Vague file reference**: "update the handler" - which handler? Specify full path.
91+2. **Missing dependency**: Plan modifies `types/index.ts` but doesn't list it
92+
93+#### Warnings (Should Address)
94+1. **High-risk change**: Deleting `utils/legacy.ts` - confirm no other imports
95+2. **Missing test plan**: No testing approach specified
96+
97+#### Suggestions (Optional)
98+1. Consider breaking step 3 into smaller sub-steps
99+2. Add rollback strategy for interface changes
100+
101+### Required Changes for Approval
102+1. Specify exact file path for "handler"
103+2. Add `types/index.ts` to files list
104+3. Confirm deletion safety for legacy file
105+
106+### Approved File Claims
107+If approved, agent may claim:
108+- `src/api/auth.ts`
109+- `src/middleware/validate.ts`
110+```
111+
112+## Quality Standards
113+
114+- Review is thorough but fast (plans should be concise)
115+- Issues are specific with suggested fixes
116+- Approval status is clear and actionable
117+- File claims are explicit for coordination
118+
119+## Edge Cases
120+
121+- **Empty plan**: Reject with "No plan content found"
122+- **Overly broad scope**: Flag and suggest breaking into multiple agents
123+- **Conflicts with other plans**: Defer to conflict-detector agent
124+- **Already-implemented changes**: Flag as potential duplicate work
@@ -1,0 +1,81 @@
1+---
2+name: status-checker
3+description: Monitors swarm progress by reading status files, identifying conflicts, stuck agents, and overall health. Launch periodically during swarm execution to enable proactive coordination.
4+tools: Read, Glob, Grep
5+model: haiku
6+color: cyan
7+---
8+
9+You are an expert swarm health monitor specializing in tracking multi-agent coordination status.
10+
11+## Core Mission
12+
13+Quickly assess swarm health by reading status files and identifying any issues that require orchestrator intervention.
14+
15+## Status Check Process
16+
17+**1. Read Swarm Status**
18+- Read `.claude/swarm-status.json` for current agent states
19+- Check timestamps to identify stale/stuck agents (>2 minutes without update)
20+- Note which agents are active, completed, or failed
21+
22+**2. Check File Claims**
23+- Read `.claude/file-claims.md` for current file ownership
24+- Identify any conflicts (multiple agents claiming same file)
25+- Note stale claims (agent completed but claim not released)
26+
27+**3. Analyze Progress**
28+- Calculate overall completion percentage
29+- Identify bottlenecks (agents waiting on others)
30+- Detect circular dependencies or deadlocks
31+
32+**4. Identify Issues**
33+- **Conflicts**: Multiple agents editing same files
34+- **Stuck Agents**: No progress for >2 minutes
35+- **Failed Agents**: Agents that reported errors
36+- **Stale Claims**: File claims from completed agents
37+
38+## Output Format
39+
40+Return a JSON status report:
41+
42+```json
43+{
44+ "timestamp": "[current time]",
45+ "overall_health": "healthy|warning|critical",
46+ "completion_percentage": [0-100],
47+ "active_agents": [
48+ {"id": "agent-1", "task": "description", "status": "working", "last_update": "timestamp"}
49+ ],
50+ "completed_agents": ["agent-2", "agent-3"],
51+ "issues": {
52+ "conflicts": [
53+ {"file": "path/to/file.ts", "agents": ["agent-1", "agent-4"], "severity": "critical"}
54+ ],
55+ "stuck_agents": [
56+ {"id": "agent-5", "last_update": "timestamp", "duration_seconds": 180}
57+ ],
58+ "stale_claims": [
59+ {"file": "path/to/file.ts", "agent": "agent-2", "reason": "agent completed"}
60+ ]
61+ },
62+ "recommendations": [
63+ {"action": "pause", "target": "agent-4", "reason": "file conflict with agent-1"},
64+ {"action": "reassign", "target": "agent-5", "reason": "stuck for 3 minutes"}
65+ ]
66+}
67+```
68+
69+## Quality Standards
70+
71+- Fast execution (this runs frequently, keep it lightweight)
72+- Accurate conflict detection (no false positives)
73+- Clear, actionable recommendations
74+- Machine-readable JSON output for orchestrator parsing
75+
76+## Edge Cases
77+
78+- **No status file exists**: Report as "no swarm active"
79+- **Empty status file**: Report as "swarm initializing"
80+- **All agents completed**: Report healthy with 100% completion
81+- **Multiple critical issues**: Prioritize by severity (conflicts > stuck > stale)
@@ -1,0 +1,287 @@
1+---
2+description: Coordinate multi-agent swarm with conflict prevention, status polling, and checkpoint-based orchestration
3+argument-hint: [task description]
4+---
5+
6+# Coordinated Swarm Orchestration
7+
8+You are orchestrating a multi-agent swarm to complete a complex task. Follow this checkpoint-based workflow to prevent conflicts and enable proactive monitoring.
9+
10+## Task Description
11+$ARGUMENTS
12+
13+---
14+
15+## Phase 1: Initialization
16+
17+**Goal**: Set up swarm coordination infrastructure
18+
19+**Actions**:
20+1. Create coordination files:
21+ - `.claude/swarm-status.json` - Agent status tracking
22+ - `.claude/file-claims.md` - File ownership registry
23+ - `.claude/swarm-plans/` - Directory for agent plans
24+
25+2. Initialize status file:
26+```json
27+{
28+ "swarm_id": "[generated-id]",
29+ "task": "[task description]",
30+ "started": "[timestamp]",
31+ "phase": "planning",
32+ "agents": {}
33+}
34+```
35+
36+3. Initialize file claims:
37+```markdown
38+# File Claims Registry
39+
40+| Agent ID | File Path | Claimed At | Status |
41+|----------|-----------|------------|--------|
42+```
43+
44+4. Create todo list tracking all phases
45+
46+---
47+
48+## Phase 2: Planning (Parallel, Read-Only)
49+
50+**Goal**: Have multiple agents analyze the codebase and create implementation plans WITHOUT making changes
51+
52+**Actions**:
53+1. Launch 2-4 planning agents in parallel, depending on task complexity. Each agent should:
54+ - Analyze a different aspect of the task
55+ - Create a detailed implementation plan
56+ - List ALL files they intend to modify/create/delete
57+ - Identify dependencies on other files or agents
58+ - **CRITICAL**: Agents must NOT edit any files - planning only
59+
60+2. Each agent writes their plan to `.claude/swarm-plans/[agent-id].md`:
61+```markdown
62+## Agent Plan: [agent-id]
63+
64+### Task Summary
65+[What this agent will accomplish]
66+
67+### Files to Modify
68+- `path/to/file.ts`: [Description of changes]
69+
70+### Files to Create
71+- `path/to/new-file.ts`: [Purpose]
72+
73+### Dependencies
74+- Requires: [what this depends on]
75+- Blocks: [what depends on this]
76+
77+### Implementation Steps
78+1. [Step 1]
79+2. [Step 2]
80+```
81+
82+3. Update swarm status as agents complete:
83+```json
84+{
85+ "agents": {
86+ "agent-1": {"status": "plan_complete", "plan_file": ".claude/swarm-plans/agent-1.md"}
87+ }
88+}
89+```
90+
91+---
92+
93+## Phase 3: Conflict Detection
94+
95+**Goal**: Review all plans and identify conflicts before implementation
96+
97+**Actions**:
98+1. Wait for ALL planning agents to complete
99+2. Read all plans from `.claude/swarm-plans/`
100+3. Launch the **conflict-detector** agent to analyze all plans
101+4. Review the conflict report
102+
103+**If conflicts found**:
104+- Present conflict report to user
105+- Ask for resolution preference:
106+ - **Sequence**: Execute conflicting agents one at a time
107+ - **Reassign**: Move conflicting files to single agent
108+ - **Manual**: User provides custom resolution
109+- Update plans based on resolution
110+- Re-run conflict detection to confirm resolution
111+
112+**If no conflicts**:
113+- Proceed to Phase 4
114+
115+---
116+
117+## Phase 4: File Claiming
118+
119+**Goal**: Register file ownership before implementation begins
120+
121+**Actions**:
122+1. For each approved plan, register file claims in `.claude/file-claims.md`:
123+```markdown
124+| agent-1 | src/api/handler.ts | 2025-01-15T10:30:00Z | claimed |
125+| agent-1 | src/utils/auth.ts | 2025-01-15T10:30:00Z | claimed |
126+| agent-2 | src/db/queries.ts | 2025-01-15T10:30:00Z | claimed |
127+```
128+
129+2. Determine execution order based on conflict analysis:
130+ - **Parallel batch 1**: Agents with no conflicts or dependencies
131+ - **Sequential queue**: Agents that must wait for others
132+
133+3. Update swarm status:
134+```json
135+{
136+ "phase": "implementing",
137+ "execution_order": [
138+ {"batch": 1, "agents": ["agent-1", "agent-2"], "parallel": true},
139+ {"batch": 2, "agents": ["agent-3"], "parallel": false, "waits_for": ["agent-1"]}
140+ ]
141+}
142+```
143+
144+---
145+
146+## Phase 5: Implementation with Monitoring
147+
148+**Goal**: Execute implementation with proactive status monitoring
149+
150+**Actions**:
151+1. Launch first batch of implementation agents
152+
153+2. **Status Polling Loop** (every 30-60 seconds during execution):
154+ - Launch a **status-checker** agent (haiku model for speed)
155+ - Review status report
156+ - If issues detected:
157+ - **Conflict**: Pause later agent, let first complete
158+ - **Stuck agent**: Check logs, consider reassignment
159+ - **Failed agent**: Report to user, decide whether to retry or skip
160+
161+3. As each agent completes:
162+ - Update swarm status: `"status": "completed"`
163+ - Release file claims in `.claude/file-claims.md`: change status to `released`
164+ - Launch next queued agents that were waiting
165+
166+4. **Agent Instructions** (include in each implementation agent's prompt):
167+```markdown
168+## Coordination Requirements
169+
170+Before editing any file:
171+1. Read `.claude/file-claims.md`
172+2. Verify the file is claimed by YOU (your agent ID)
173+3. If claimed by another agent, SKIP and note in your results
174+4. If not claimed, DO NOT edit - report the missing claim
175+
176+After completing work:
177+1. Update your status in swarm communication
178+2. Report files modified for claim release
179+
180+If you encounter a conflict:
181+1. STOP editing the conflicted file
182+2. Report the conflict immediately
183+3. Wait for orchestrator resolution
184+```
185+
186+---
187+
188+## Phase 6: Verification
189+
190+**Goal**: Verify swarm completed successfully
191+
192+**Actions**:
193+1. Check all agents completed:
194+ - Read final swarm status
195+ - Verify all planned files were modified
196+ - Check for any orphaned claims
197+
198+2. Run integration checks:
199+ - Build/compile if applicable
200+ - Run tests if applicable
201+ - Check for import/type errors
202+
203+3. Clean up coordination files:
204+ - Archive swarm status to `.claude/swarm-history/`
205+ - Clear file claims
206+ - Remove plan files
207+
208+---
209+
210+## Phase 7: Summary
211+
212+**Goal**: Report swarm execution results
213+
214+**Actions**:
215+1. Summarize:
216+ - Total agents launched
217+ - Files modified/created/deleted
218+ - Conflicts detected and resolved
219+ - Issues encountered
220+ - Total execution time
221+
222+2. Present to user:
223+ - What was accomplished
224+ - Any items requiring follow-up
225+ - Suggested next steps
226+
227+---
228+
229+## Error Handling
230+
231+**Agent Failure**:
232+1. Log failure in swarm status
233+2. Release failed agent's file claims
234+3. Ask user: retry, skip, or abort swarm
235+
236+**Unresolvable Conflict**:
237+1. Pause all conflicting agents
238+2. Present options to user
239+3. Wait for manual resolution
240+
241+**Stuck Swarm**:
242+1. If no progress for 5+ minutes, alert user
243+2. Provide diagnostic information
244+3. Offer to abort and roll back
245+
246+---
247+
248+## File Claim Convention (For All Agents)
249+
250+Include this instruction block in every implementation agent's system prompt:
251+
252+```markdown
253+## File Claiming Protocol
254+
255+You are part of a coordinated swarm. Follow these rules strictly:
256+
257+1. **Before ANY file edit**:
258+ - Read `.claude/file-claims.md`
259+ - Find your agent ID in the registry
260+ - Only edit files claimed by YOUR agent ID
261+
262+2. **If file is claimed by another agent**:
263+ - DO NOT edit the file
264+ - Note in your results: "Skipped [file] - claimed by [other-agent]"
265+ - Continue with other work
266+
267+3. **If file is not in claims registry**:
268+ - DO NOT edit the file
269+ - Report: "Cannot edit [file] - not in approved claims"
270+ - This indicates a planning oversight
271+
272+4. **Update your progress**:
273+ - After each significant step, your status will be tracked
274+ - If you encounter issues, report them clearly
275+```
276+
277+---
278+
279+## Status Polling Schedule
280+
281+During Phase 5, launch status-checker agent:
282+- After initial batch launch: wait 30 seconds, then check
283+- During active execution: check every 45-60 seconds
284+- After agent completion: immediate check to launch next batch
285+- On any reported issue: immediate check
286+
287+Use **haiku model** for status-checker to minimize latency and cost.
@@ -1,0 +1,80 @@
1+# Swarm Coordination Patterns
2+
3+Comprehensive guidance for coordinating multi-agent swarms to prevent conflicts and enable proactive monitoring.
4+
5+## When to Activate
6+
7+Activate this skill when:
8+- Orchestrating multiple agents working on the same codebase
9+- Implementing features that require parallel agent execution
10+- Designing workflows where agents might edit overlapping files
11+- Debugging swarm coordination issues
12+
13+## Core Concepts
14+
15+### The Problem with Uncoordinated Swarms
16+
17+When multiple agents work in parallel without coordination:
18+1. **File Conflicts**: Multiple agents edit the same file simultaneously
19+2. **Merge Conflicts**: Changes overwrite each other
20+3. **Endless Loops**: Agents "fix" each other's code in circles
21+4. **Wasted Work**: Duplicate effort on same files
22+
23+### Three-Pillar Solution
24+
25+This skill teaches three complementary patterns:
26+
27+1. **Status Polling (Fix 1)**: Orchestrator proactively monitors agent progress
28+2. **File Claiming (Fix 2)**: Agents claim ownership before editing
29+3. **Checkpoint Orchestration (Fix 5)**: Plan first, detect conflicts, then implement
30+
31+## Key Files
32+
33+### Coordination Files
34+- `.claude/swarm-status.json` - Central status tracking
35+- `.claude/file-claims.md` - File ownership registry
36+- `.claude/swarm-plans/` - Agent implementation plans
37+
38+### Status File Format
39+```json
40+{
41+ "swarm_id": "swarm-20250115-abc123",
42+ "task": "Implement user authentication",
43+ "started": "2025-01-15T10:00:00Z",
44+ "phase": "implementing",
45+ "agents": {
46+ "auth-impl": {"status": "working", "last_update": "2025-01-15T10:05:00Z"},
47+ "db-schema": {"status": "completed", "last_update": "2025-01-15T10:03:00Z"}
48+ },
49+ "execution_order": [
50+ {"batch": 1, "agents": ["db-schema"], "parallel": false},
51+ {"batch": 2, "agents": ["auth-impl", "api-routes"], "parallel": true}
52+ ]
53+}
54+```
55+
56+### File Claims Format
57+```markdown
58+# File Claims Registry
59+
60+| Agent ID | File Path | Claimed At | Status |
61+|----------|-----------|------------|--------|
62+| auth-impl | src/auth/handler.ts | 2025-01-15T10:00:00Z | claimed |
63+| auth-impl | src/auth/types.ts | 2025-01-15T10:00:00Z | claimed |
64+| db-schema | src/db/schema.ts | 2025-01-15T10:00:00Z | released |
65+```
66+
67+## References
68+
69+- `references/status-polling.md` - Detailed polling patterns
70+- `references/file-claiming.md` - File ownership conventions
71+- `references/checkpoint-flow.md` - Phase-based orchestration
72+- `examples/simple-swarm.md` - Basic two-agent swarm
73+- `examples/complex-swarm.md` - Multi-phase feature implementation
74+
75+## Quick Start
76+
77+1. Use `/swarm [task]` command for full orchestrated flow
78+2. For manual coordination, create the three coordination files
79+3. Include file claiming instructions in all implementation agents
80+4. Launch status-checker every 30-60 seconds during execution
@@ -1,0 +1,260 @@
1+# Simple Swarm Example
2+
3+A two-agent swarm implementing a feature with coordinated file claiming.
4+
5+## Scenario
6+
7+Task: Add user authentication to an Express API
8+
9+## Initial Setup
10+
11+### Swarm Status File
12+`.claude/swarm-status.json`:
13+```json
14+{
15+ "swarm_id": "auth-feature-001",
16+ "task": "Add user authentication",
17+ "started": "2025-01-15T10:00:00Z",
18+ "phase": "initialized",
19+ "agents": {}
20+}
21+```
22+
23+### File Claims Registry
24+`.claude/file-claims.md`:
25+```markdown
26+# File Claims Registry
27+
28+Last updated: 2025-01-15T10:00:00Z
29+Swarm ID: auth-feature-001
30+
31+| Agent ID | File Path | Claimed At | Status |
32+|----------|-----------|------------|--------|
33+```
34+
35+## Phase 1: Planning
36+
37+Launch two planning agents:
38+
39+**Agent 1 Prompt**:
40+```
41+Analyze the codebase and create an implementation plan for:
42+Adding JWT token validation middleware
43+
44+You are in PLANNING MODE - DO NOT modify any files.
45+Output a structured plan with all files you need to modify.
46+```
47+
48+**Agent 2 Prompt**:
49+```
50+Analyze the codebase and create an implementation plan for:
51+Adding user login/logout API endpoints
52+
53+You are in PLANNING MODE - DO NOT modify any files.
54+Output a structured plan with all files you need to modify.
55+```
56+
57+### Agent 1 Plan Output
58+`.claude/swarm-plans/jwt-middleware.md`:
59+```markdown
60+## Agent Plan: jwt-middleware
61+
62+### Task Summary
63+Implement JWT token validation middleware for protected routes.
64+
65+### Files to Modify
66+- `src/middleware/index.ts`: Export new auth middleware
67+
68+### Files to Create
69+- `src/middleware/auth.ts`: JWT validation middleware
70+- `src/types/auth.ts`: Token payload types
71+
72+### Dependencies
73+- Requires: None
74+- Blocks: Protected routes need this middleware
75+
76+### Implementation Steps
77+1. Create auth types
78+2. Implement JWT validation middleware
79+3. Export from middleware index
80+```
81+
82+### Agent 2 Plan Output
83+`.claude/swarm-plans/auth-endpoints.md`:
84+```markdown
85+## Agent Plan: auth-endpoints
86+
87+### Task Summary
88+Implement login and logout API endpoints.
89+
90+### Files to Modify
91+- `src/routes/index.ts`: Add auth routes
92+- `src/middleware/index.ts`: Import auth utilities
93+
94+### Files to Create
95+- `src/routes/auth.ts`: Login/logout endpoints
96+- `src/services/auth.ts`: Authentication service
97+
98+### Dependencies
99+- Requires: JWT middleware for logout validation
100+- Blocks: None
101+
102+### Implementation Steps
103+1. Create auth service
104+2. Implement auth routes
105+3. Update routes index
106+4. Update middleware index
107+```
108+
109+## Phase 2: Conflict Detection
110+
111+Analyzing plans:
112+
113+```
114+File: src/middleware/index.ts
115+ - jwt-middleware: modify (export new middleware)
116+ - auth-endpoints: modify (import auth utilities)
117+ → CONFLICT DETECTED
118+```
119+
120+### Conflict Report
121+```markdown
122+## Conflict Analysis
123+
124+### Conflicts Found: 1
125+
126+#### Conflict 1: src/middleware/index.ts
127+Agents: jwt-middleware, auth-endpoints
128+Nature: Both agents plan to modify this file
129+- jwt-middleware: Add export for auth middleware
130+- auth-endpoints: Import auth utilities
131+
132+**Resolution Options**:
133+1. Sequential: jwt-middleware first, then auth-endpoints
134+2. Merge: Have jwt-middleware handle all middleware/index.ts changes
135+```
136+
137+## Phase 3: Resolution
138+
139+**Chosen Resolution**: Option 1 - Sequential execution
140+
141+Updated execution plan:
142+- Batch 1: jwt-middleware (no dependencies)
143+- Batch 2: auth-endpoints (after jwt-middleware completes)
144+
145+## Phase 4: File Claiming
146+
147+Updated `.claude/file-claims.md`:
148+```markdown
149+# File Claims Registry
150+
151+Last updated: 2025-01-15T10:05:00Z
152+Swarm ID: auth-feature-001
153+
154+| Agent ID | File Path | Claimed At | Status |
155+|----------|-----------|------------|--------|
156+| jwt-middleware | src/middleware/auth.ts | 2025-01-15T10:05:00Z | claimed |
157+| jwt-middleware | src/middleware/index.ts | 2025-01-15T10:05:00Z | claimed |
158+| jwt-middleware | src/types/auth.ts | 2025-01-15T10:05:00Z | claimed |
159+| auth-endpoints | src/routes/auth.ts | 2025-01-15T10:05:00Z | pending |
160+| auth-endpoints | src/routes/index.ts | 2025-01-15T10:05:00Z | pending |
161+| auth-endpoints | src/services/auth.ts | 2025-01-15T10:05:00Z | pending |
162+```
163+
164+Note: auth-endpoints claims are "pending" until jwt-middleware completes.
165+
166+## Phase 5: Implementation
167+
168+### Batch 1: jwt-middleware
169+
170+Launch jwt-middleware agent with implementation instructions:
171+```
172+Execute your approved plan from .claude/swarm-plans/jwt-middleware.md
173+Only modify files claimed by jwt-middleware in .claude/file-claims.md
174+```
175+
176+**Status after 45 seconds** (from status-checker):
177+```json
178+{
179+ "overall_health": "healthy",
180+ "agents": {
181+ "jwt-middleware": {"status": "working", "progress": "Creating middleware"}
182+ }
183+}
184+```
185+
186+**Status after 2 minutes**:
187+```json
188+{
189+ "overall_health": "healthy",
190+ "agents": {
191+ "jwt-middleware": {"status": "completed"}
192+ }
193+}
194+```
195+
196+### Release Claims & Activate Batch 2
197+
198+Updated `.claude/file-claims.md`:
199+```markdown
200+| jwt-middleware | src/middleware/auth.ts | 2025-01-15T10:05:00Z | released |
201+| jwt-middleware | src/middleware/index.ts | 2025-01-15T10:05:00Z | released |
202+| jwt-middleware | src/types/auth.ts | 2025-01-15T10:05:00Z | released |
203+| auth-endpoints | src/routes/auth.ts | 2025-01-15T10:07:00Z | claimed |
204+| auth-endpoints | src/routes/index.ts | 2025-01-15T10:07:00Z | claimed |
205+| auth-endpoints | src/services/auth.ts | 2025-01-15T10:07:00Z | claimed |
206+| auth-endpoints | src/middleware/index.ts | 2025-01-15T10:07:00Z | claimed |
207+```
208+
209+Note: auth-endpoints now also claims middleware/index.ts after jwt-middleware released it.
210+
211+### Batch 2: auth-endpoints
212+
213+Launch auth-endpoints agent with implementation instructions.
214+
215+**Status after 3 minutes**:
216+```json
217+{
218+ "overall_health": "healthy",
219+ "agents": {
220+ "jwt-middleware": {"status": "completed"},
221+ "auth-endpoints": {"status": "completed"}
222+ },
223+ "completion_percentage": 100
224+}
225+```
226+
227+## Phase 6: Verification
228+
229+Checks:
230+- [x] jwt-middleware completed
231+- [x] auth-endpoints completed
232+- [x] All files modified as planned
233+- [x] No orphaned claims
234+- [x] Build succeeds
235+- [x] Tests pass
236+
237+## Phase 7: Summary
238+
239+```markdown
240+## Swarm Completion Report
241+
242+### Task: Add user authentication
243+### Duration: 8 minutes
244+### Agents: 2
245+
246+### Files Created
247+- src/middleware/auth.ts
248+- src/types/auth.ts
249+- src/routes/auth.ts
250+- src/services/auth.ts
251+
252+### Files Modified
253+- src/middleware/index.ts
254+- src/routes/index.ts
255+
256+### Conflicts Resolved
257+- 1 conflict on src/middleware/index.ts (sequential resolution)
258+
259+### Status: SUCCESS
260+```
@@ -1,0 +1,287 @@
1+# Checkpoint-Based Orchestration
2+
3+A phased approach to swarm execution that prevents conflicts through planning, review, and controlled implementation.
4+
5+## Overview
6+
7+Checkpoint-based orchestration separates swarm execution into distinct phases:
8+
9+1. **Planning** - Agents analyze and plan (read-only)
10+2. **Review** - Orchestrator detects conflicts
11+3. **Resolution** - Conflicts resolved before implementation
12+4. **Claiming** - Files assigned to agents
13+5. **Implementation** - Agents execute plans
14+6. **Verification** - Results validated
15+
16+## Why Checkpoints?
17+
18+### Without Checkpoints
19+```
20+Launch agents → Agents work in parallel → CONFLICT! →
21+Agents overwrite each other → Endless fix loops → Chaos
22+```
23+
24+### With Checkpoints
25+```
26+Launch planning agents → Collect plans → Detect conflicts →
27+Resolve conflicts → Claim files → Sequential/parallel execution → Success
28+```
29+
30+## Phase Details
31+
32+### Phase 1: Planning (Parallel, Read-Only)
33+
34+**Purpose**: Gather implementation plans without making changes
35+
36+**Key Rules**:
37+- Agents may READ any file
38+- Agents must NOT WRITE any file
39+- Each agent produces a structured plan
40+
41+**Agent Instructions**:
42+```markdown
43+You are in PLANNING MODE. Analyze the codebase and create an implementation plan.
44+
45+CRITICAL RESTRICTIONS:
46+- DO NOT use Edit, Write, or any file modification tools
47+- DO NOT execute commands that modify files
48+- ONLY use Read, Glob, Grep for analysis
49+
50+Your output must be a structured plan listing:
51+- All files you need to modify (with full paths)
52+- All files you need to create
53+- All files you need to delete
54+- Dependencies on other components
55+- Step-by-step implementation approach
56+```
57+
58+**Plan Format**:
59+```markdown
60+## Agent Plan: [agent-id]
61+
62+### Task Summary
63+[1-2 sentence description of what this agent will accomplish]
64+
65+### Files to Modify
66+- `src/auth/handler.ts`: Add validateToken() function and update handleRequest()
67+- `src/types/auth.ts`: Add TokenPayload interface
68+
69+### Files to Create
70+- `src/auth/tokens.ts`: Token generation and validation utilities
71+
72+### Files to Delete
73+- `src/auth/legacy-auth.ts`: Replaced by new implementation
74+
75+### Dependencies
76+- **Requires**: Database schema must include users table
77+- **Blocks**: API routes cannot be updated until auth is complete
78+
79+### Implementation Steps
80+1. Create TokenPayload interface in types
81+2. Implement token utilities in new file
82+3. Update handler with validation logic
83+4. Remove legacy file after verification
84+
85+### Estimated Scope
86+- Files touched: 4
87+- Lines added: ~150
88+- Lines removed: ~80
89+- Risk level: Medium (touching auth system)
90+```
91+
92+### Phase 2: Conflict Detection
93+
94+**Purpose**: Identify overlapping file edits before they happen
95+
96+**Process**:
97+1. Collect all agent plans
98+2. Build file → agent mapping
99+3. Identify conflicts:
100+ - Same file modified by multiple agents
101+ - Delete conflicts with modify
102+ - Creation conflicts
103+ - Dependency cycles
104+
105+**Conflict Types**:
106+
107+| Type | Severity | Example |
108+|------|----------|---------|
109+| Same file modify | Critical | agent-1 and agent-2 both modify handler.ts |
110+| Create collision | Critical | Both agents create utils/helper.ts |
111+| Delete + Modify | Critical | agent-1 deletes file agent-2 modifies |
112+| Dependency cycle | Critical | agent-1 waits for agent-2, agent-2 waits for agent-1 |
113+| Same directory | Warning | Both agents add files to src/utils/ |
114+| Import chain | Info | agent-1's file imports from agent-2's file |
115+
116+### Phase 3: Resolution
117+
118+**Purpose**: Resolve all conflicts before implementation begins
119+
120+**Resolution Strategies**:
121+
122+**Sequential Execution**:
123+```markdown
124+Conflict: agent-1 and agent-2 both modify src/api/index.ts
125+
126+Resolution: Execute sequentially
127+- Execution order: agent-1 first, then agent-2
128+- agent-2 will see agent-1's changes before starting
129+```
130+
131+**Scope Reassignment**:
132+```markdown
133+Conflict: agent-1 (auth) and agent-2 (logging) both modify middleware.ts
134+
135+Resolution: Reassign to single agent
136+- Expand agent-1's scope to include logging changes
137+- Remove middleware.ts from agent-2's plan
138+```
139+
140+**File Splitting**:
141+```markdown
142+Conflict: agent-1 and agent-2 both modify large config.ts
143+
144+Resolution: Split the file
145+- Create config/auth.ts (agent-1)
146+- Create config/db.ts (agent-2)
147+- Update config/index.ts to re-export
148+```
149+
150+**User Decision**:
151+```markdown
152+Conflict: Complex dependency between agent-1 and agent-3
153+
154+Resolution: Present to user
155+"Agents 1 and 3 have interleaved dependencies. Options:
156+1. Merge into single agent
157+2. Manual sequencing with intermediate reviews
158+3. Redesign the task split"
159+```
160+
161+### Phase 4: File Claiming
162+
163+**Purpose**: Register file ownership before implementation
164+
165+**Process**:
166+1. For each resolved plan, register claims
167+2. Update `.claude/file-claims.md`
168+3. Determine execution batches
169+
170+**Execution Order Determination**:
171+```markdown
172+Given resolved plans:
173+- agent-1: No dependencies
174+- agent-2: No dependencies
175+- agent-3: Depends on agent-1
176+- agent-4: Depends on agent-2 and agent-3
177+
178+Execution order:
179+Batch 1 (parallel): agent-1, agent-2
180+Batch 2 (after batch 1): agent-3
181+Batch 3 (after agent-3): agent-4
182+```
183+
184+### Phase 5: Implementation with Monitoring
185+
186+**Purpose**: Execute plans with status tracking
187+
188+**Process**:
189+1. Launch batch 1 agents
190+2. Start polling loop (every 30-60 seconds)
191+3. As agents complete:
192+ - Release their file claims
193+ - Launch dependent agents
194+4. Handle issues as detected:
195+ - Stuck agents → investigate/reassign
196+ - Conflicts → pause and resolve
197+ - Failures → report and decide
198+
199+**Agent Instructions for Implementation**:
200+```markdown
201+You are now in IMPLEMENTATION MODE. Execute your approved plan.
202+
203+Your approved plan is in: .claude/swarm-plans/[your-agent-id].md
204+Your claimed files are in: .claude/file-claims.md
205+
206+RULES:
207+1. Only modify files that are claimed by YOUR agent ID
208+2. Follow your plan exactly - do not expand scope
209+3. If you need to modify an unclaimed file, STOP and report
210+4. Update progress by completing your assigned tasks
211+```
212+
213+### Phase 6: Verification
214+
215+**Purpose**: Validate swarm completed successfully
216+
217+**Checks**:
218+- [ ] All agents reported completion
219+- [ ] All planned files were modified
220+- [ ] No orphaned file claims
221+- [ ] Build succeeds (if applicable)
222+- [ ] Tests pass (if applicable)
223+- [ ] No unexpected files modified
224+
225+## Checkpoint Gates
226+
227+Each phase has a gate that must pass before proceeding:
228+
229+| Gate | Condition | Failure Action |
230+|------|-----------|----------------|
231+| Planning → Review | All planning agents completed | Wait or timeout |
232+| Review → Resolution | Conflict report generated | Re-run detection |
233+| Resolution → Claiming | All conflicts resolved | Return to resolution |
234+| Claiming → Implementation | All files claimed, no overlaps | Fix claim issues |
235+| Implementation → Verification | All agents completed | Investigate failures |
236+| Verification → Complete | All checks pass | Fix issues or report |
237+
238+## State Machine
239+
240+```
241+┌─────────────┐
242+│ INITIALIZED │
243+└──────┬──────┘
244+ │ Start swarm
245+ ▼
246+┌─────────────┐
247+│ PLANNING │◄────────────────┐
248+└──────┬──────┘ │
249+ │ All plans received │
250+ ▼ │
251+┌─────────────┐ │
252+│ REVIEWING │ │
253+└──────┬──────┘ │
254+ │ Conflicts identified │
255+ ▼ │
256+┌─────────────┐ │
257+│ RESOLVING │─────────────────┘
258+└──────┬──────┘ Need re-plan
259+ │ All resolved
260+ ▼
261+┌─────────────┐
262+│ CLAIMING │
263+└──────┬──────┘
264+ │ Files assigned
265+ ▼
266+┌─────────────┐
267+│IMPLEMENTING │◄───┐
268+└──────┬──────┘ │
269+ │ │ Next batch
270+ ▼ │
271+┌─────────────┐ │
272+│ VERIFYING │────┘
273+└──────┬──────┘ More batches
274+ │ All verified
275+ ▼
276+┌─────────────┐
277+│ COMPLETED │
278+└─────────────┘
279+```
280+
281+## Benefits
282+
283+1. **No Conflicts**: Detected and resolved before implementation
284+2. **Visibility**: Know exactly what each agent will do
285+3. **Control**: Orchestrator maintains full oversight
286+4. **Recovery**: Can roll back or adjust between phases
287+5. **Efficiency**: Parallel execution where safe, sequential where needed
@@ -1,0 +1,233 @@
1+# File Claiming Convention
2+
3+A coordination protocol where agents claim file ownership before editing to prevent conflicts.
4+
5+## Overview
6+
7+File claiming is a simple but effective convention:
8+1. Before editing any file, agent checks if it's claimed
9+2. If unclaimed or claimed by self, proceed
10+3. If claimed by another agent, skip and report
11+4. After completion, release claims
12+
13+## The Claims Registry
14+
15+Location: `.claude/file-claims.md`
16+
17+### Format
18+
19+```markdown
20+# File Claims Registry
21+
22+Last updated: 2025-01-15T10:30:00Z
23+Swarm ID: swarm-20250115-abc123
24+
25+| Agent ID | File Path | Claimed At | Status |
26+|----------|-----------|------------|--------|
27+| auth-impl | src/auth/handler.ts | 2025-01-15T10:00:00Z | claimed |
28+| auth-impl | src/auth/types.ts | 2025-01-15T10:00:00Z | claimed |
29+| auth-impl | src/auth/middleware.ts | 2025-01-15T10:00:00Z | claimed |
30+| db-agent | src/db/schema.ts | 2025-01-15T10:00:00Z | released |
31+| db-agent | src/db/queries.ts | 2025-01-15T10:00:00Z | released |
32+```
33+
34+### Status Values
35+
36+| Status | Meaning |
37+|--------|---------|
38+| `claimed` | Agent is actively working on this file |
39+| `released` | Agent completed, file available |
40+| `conflict` | Multiple agents claimed (needs resolution) |
41+
42+## Agent Instructions
43+
44+Include this block in every implementation agent's system prompt:
45+
46+```markdown
47+## File Claiming Protocol
48+
49+You are part of a coordinated swarm. Follow these rules strictly:
50+
51+### Before ANY File Edit
52+
53+1. Read `.claude/file-claims.md`
54+2. Find the file you want to edit in the registry
55+3. Check the claim status:
56+
57+**If claimed by YOUR agent ID** → Proceed with edit
58+**If claimed by ANOTHER agent** → DO NOT edit, report:
59+ "Skipped [file] - claimed by [other-agent]"
60+**If file NOT in registry** → DO NOT edit, report:
61+ "Cannot edit [file] - not in approved claims"
62+
63+### During Execution
64+
65+- Only edit files explicitly claimed by you
66+- If you discover a need to edit an unclaimed file, report it
67+- Do not modify the claims registry yourself
68+
69+### After Completion
70+
71+Report all files you modified so claims can be released.
72+```
73+
74+## Claim Lifecycle
75+
76+```
77+┌─────────────────────────────────────────────────────────┐
78+│ PLANNING PHASE │
79+│ Agent creates plan → Lists files to modify │
80+└────────────────────────┬────────────────────────────────┘
81+ │
82+ ▼
83+┌─────────────────────────────────────────────────────────┐
84+│ CONFLICT DETECTION │
85+│ Orchestrator reviews all plans → Identifies overlaps │
86+│ Resolves conflicts → Determines execution order │
87+└────────────────────────┬────────────────────────────────┘
88+ │
89+ ▼
90+┌─────────────────────────────────────────────────────────┐
91+│ CLAIM REGISTRATION │
92+│ Orchestrator writes claims to registry │
93+│ Each file → exactly one agent │
94+└────────────────────────┬────────────────────────────────┘
95+ │
96+ ▼
97+┌─────────────────────────────────────────────────────────┐
98+│ IMPLEMENTATION │
99+│ Agents check registry before each edit │
100+│ Only edit files claimed by self │
101+└────────────────────────┬────────────────────────────────┘
102+ │
103+ ▼
104+┌─────────────────────────────────────────────────────────┐
105+│ CLAIM RELEASE │
106+│ Agent completes → Reports to orchestrator │
107+│ Orchestrator marks claims as "released" │
108+└─────────────────────────────────────────────────────────┘
109+```
110+
111+## Conflict Resolution Strategies
112+
113+When multiple agents need the same file:
114+
115+### Strategy 1: Sequential Execution
116+
117+```markdown
118+Conflict: agent-1 and agent-3 both need src/api/handler.ts
119+
120+Resolution:
121+- agent-1 claims file, executes first
122+- After agent-1 completes, release claim
123+- agent-3 claims file, executes second
124+```
125+
126+### Strategy 2: Scope Partition
127+
128+```markdown
129+Conflict: agent-1 and agent-2 both need src/types/index.ts
130+
131+Resolution:
132+- Split file into src/types/auth.ts and src/types/user.ts
133+- agent-1 claims auth.ts
134+- agent-2 claims user.ts
135+- Update index.ts to re-export (claimed by orchestrator)
136+```
137+
138+### Strategy 3: Merge Responsibility
139+
140+```markdown
141+Conflict: agent-1 (auth) and agent-2 (validation) both need middleware.ts
142+
143+Resolution:
144+- Expand agent-1's scope to include validation changes
145+- Remove middleware.ts from agent-2's plan
146+- agent-1 handles all middleware changes
147+```
148+
149+### Strategy 4: Section-Based Claims
150+
151+```markdown
152+Conflict: Multiple agents need same config file
153+
154+Resolution:
155+- Claim specific sections rather than whole file
156+- agent-1 claims: config.ts lines 1-50 (auth section)
157+- agent-2 claims: config.ts lines 51-100 (db section)
158+- Requires careful merge at end
159+```
160+
161+## Handling Violations
162+
163+### Agent Edits Unclaimed File
164+
165+```markdown
166+Detected: agent-2 modified src/utils/helper.ts (not in claims)
167+
168+Response:
169+1. Flag as violation in status report
170+2. Options:
171+ a. Add retroactive claim if no conflict
172+ b. Revert change if conflicts with another agent
173+ c. Pause agent and request clarification
174+```
175+
176+### Agent Edits Another's File
177+
178+```markdown
179+Detected: agent-2 modified src/auth/handler.ts (claimed by agent-1)
180+
181+Response:
182+1. CRITICAL violation
183+2. Pause agent-2 immediately
184+3. Check if agent-1's work is corrupted
185+4. Options:
186+ a. Revert agent-2's changes
187+ b. Have agent-1 re-do affected work
188+ c. Manual merge by orchestrator
189+```
190+
191+## Best Practices
192+
193+1. **Register claims BEFORE launching agents** - Not during
194+2. **One file, one owner** - Never have overlapping claims
195+3. **Include all touched files** - Even read-heavy files if modified
196+4. **Release promptly** - Don't hold claims after completion
197+5. **Verify at completion** - Check all claimed files were handled
198+6. **Track unclaimed edits** - They indicate planning gaps
199+
200+## Claims Registry Management
201+
202+### Creating the Registry
203+
204+```markdown
205+# File Claims Registry
206+
207+Last updated: [timestamp]
208+Swarm ID: [swarm-id]
209+
210+| Agent ID | File Path | Claimed At | Status |
211+|----------|-----------|------------|--------|
212+```
213+
214+### Adding Claims (Orchestrator Only)
215+
216+```markdown
217+| new-agent | src/new/file.ts | [timestamp] | claimed |
218+```
219+
220+### Releasing Claims
221+
222+Change status from `claimed` to `released`:
223+
224+```markdown
225+| agent-id | src/file.ts | [timestamp] | released |
226+```
227+
228+### Cleaning Up
229+
230+After swarm completion:
231+1. Archive registry to `.claude/swarm-history/`
232+2. Delete or clear current registry
233+3. Ready for next swarm
@@ -1,0 +1,152 @@
1+# Status Polling Pattern
2+
3+Proactive orchestrator monitoring for swarm health and conflict detection.
4+
5+## Overview
6+
7+Instead of fire-and-forget agent launching, the orchestrator periodically spawns lightweight "status checker" agents to monitor swarm progress and identify issues early.
8+
9+## Why Polling Matters
10+
11+Without polling:
12+- Orchestrator has no visibility into agent progress
13+- Conflicts discovered only after damage is done
14+- Stuck agents waste time until final timeout
15+- No opportunity for mid-execution corrections
16+
17+With polling:
18+- Real-time visibility into agent status
19+- Conflicts detected and resolved quickly
20+- Stuck agents identified and reassigned
21+- Dynamic load balancing possible
22+
23+## Polling Schedule
24+
25+### Recommended Intervals
26+
27+| Phase | Interval | Reason |
28+|-------|----------|--------|
29+| Initial launch | 30 seconds | Catch early failures fast |
30+| Active execution | 45-60 seconds | Balance visibility vs overhead |
31+| Near completion | 30 seconds | Ensure clean handoffs |
32+| Post-completion | Immediate | Verify success, launch next batch |
33+
34+### Adaptive Polling
35+
36+Adjust frequency based on:
37+- **More frequent**: High-conflict swarms, many parallel agents
38+- **Less frequent**: Simple tasks, sequential execution
39+- **Immediate**: After any agent reports an issue
40+
41+## Status Checker Agent
42+
43+The status-checker agent is designed for fast, lightweight execution:
44+
45+```yaml
46+model: haiku # Fast and cheap
47+tools: Read, Glob, Grep # Read-only, no edits
48+```
49+
50+### What It Checks
51+
52+1. **Agent Status**
53+ - Last update timestamp
54+ - Current task progress
55+ - Reported errors or warnings
56+
57+2. **File Claims**
58+ - Ownership conflicts
59+ - Stale claims from completed agents
60+ - Unclaimed files being edited
61+
62+3. **Overall Health**
63+ - Completion percentage
64+ - Estimated time remaining
65+ - Bottlenecks and blockers
66+
67+### Output Format
68+
69+```json
70+{
71+ "timestamp": "2025-01-15T10:35:00Z",
72+ "overall_health": "warning",
73+ "completion_percentage": 65,
74+ "issues": {
75+ "conflicts": [{
76+ "file": "src/api/handler.ts",
77+ "agents": ["agent-1", "agent-3"],
78+ "severity": "critical"
79+ }],
80+ "stuck_agents": [{
81+ "id": "agent-2",
82+ "last_update": "2025-01-15T10:30:00Z",
83+ "duration_seconds": 300
84+ }]
85+ },
86+ "recommendations": [
87+ {"action": "pause", "target": "agent-3", "reason": "resolve conflict"}
88+ ]
89+}
90+```
91+
92+## Responding to Status Reports
93+
94+### Healthy Status
95+```json
96+{"overall_health": "healthy"}
97+```
98+- Continue execution
99+- Schedule next poll at normal interval
100+
101+### Warning Status
102+```json
103+{"overall_health": "warning", "issues": {...}}
104+```
105+- Review specific issues
106+- Take corrective action if needed
107+- Increase polling frequency temporarily
108+
109+### Critical Status
110+```json
111+{"overall_health": "critical", "issues": {...}}
112+```
113+- Pause affected agents immediately
114+- Resolve conflicts before continuing
115+- Consider notifying user for input
116+
117+## Implementation Example
118+
119+```markdown
120+## During Implementation Phase
121+
122+1. Launch batch 1 agents (agent-1, agent-2)
123+2. Wait 30 seconds
124+3. Launch status-checker agent
125+4. If healthy: continue, schedule next check in 45 seconds
126+5. If issues:
127+ - Conflicts: Pause later agent, let first complete
128+ - Stuck: Check logs, consider timeout or reassignment
129+ - Failed: Report to user, decide on retry/skip
130+6. Repeat until all agents complete
131+```
132+
133+## Polling vs Event-Driven
134+
135+| Approach | Pros | Cons |
136+|----------|------|------|
137+| Polling | Simple, no agent modification needed | Some latency in detection |
138+| Events | Immediate detection | Requires agent cooperation |
139+
140+This plugin uses polling because:
141+- Works with any agent without modification
142+- Orchestrator maintains full control
143+- Simpler implementation
144+- Haiku model makes polling cheap
145+
146+## Best Practices
147+
148+1. **Use haiku for status checks** - Fast and cheap
149+2. **Don't poll too frequently** - 30 seconds minimum
150+3. **Act on issues promptly** - Don't just log and continue
151+4. **Track polling history** - Useful for debugging
152+5. **Combine with file claims** - Polling detects, claims prevent