Coordinate multi-agent swarm execution with a lightweight Pub/Sub protocol, standardized SwarmCommand messages, token-budget control, agent status tracking,...
---
name: swarm-coordinator
description: Coordinate multi-agent swarm execution with a lightweight Pub/Sub protocol, standardized SwarmCommand messages, token-budget control, agent status tracking, negotiation, fallback, and completion gates. Use when building or reviewing multi-agent coordination, swarm execution, task delegation, agent handoff, token quota governance, Redis/in-memory PubSub orchestration, role-based agent teams, or safe parallel AI workflows.
version: "1.1.0"
last_updated: "2026-04-25"
changelog: "ClawHub-ready release: generalized public wording, added execution workflow, safety boundaries, gates, failure handling, validation checklist, and test prompts."
---
# Swarm Coordinator
Swarm Coordinator is a lightweight coordination skill for multi-agent execution. It helps an agent design, validate, and operate a swarm workflow using:
- standardized `SwarmCommand` messages
- Redis or in-memory Pub/Sub coordination
- token-budget governance and downgrade rules
- agent status tracking
- negotiation and conflict resolution
- assignment, completion, and failure notifications
Use it when the task is not “one agent answers once”, but **multiple agents must coordinate without losing control of cost, state, ownership, or completion criteria**.
This skill is intentionally control-oriented: a swarm is only valuable when parallelism improves throughput or quality without causing duplicated work, hidden queue drift, or uncontrolled token spend.
---
## When to Use
Use this skill for:
- multi-agent task delegation or swarm execution
- role-based AI teams, agent crews, or collaborative agent workflows
- Pub/Sub task coordination with Redis or memory queues
- designing a standard command protocol between agents
- assigning roles, budgets, deadlines, and dependencies
- tracking task state across multiple agents
- negotiating conflicts between agents
- enforcing token quota and fallback behavior
- reviewing whether a swarm workflow can converge safely
Do not use it for simple single-agent tasks. If one agent can complete the job directly, avoid swarm overhead.
---
## Core Principle
A swarm is useful only if it improves throughput or quality **without causing coordination chaos**.
Always protect four invariants:
1. **Single task owner** — every task has one accountable owner at a time.
2. **Explicit state** — each command has status, deadline, budget, dependencies, and result.
3. **Bounded cost** — token budget and downgrade rules are part of the protocol.
4. **Verifiable completion** — completion requires artifacts, tests, review, or an explicit result field.
If any invariant is missing, the swarm can drift, duplicate work, or burn tokens.
---
## Default Workflow
### Step 1: Decide whether swarm is justified
Use swarm only when at least one is true:
- task can be split into independent subtasks
- different agents have clearly different roles
- review/verification must be separated from implementation
- latency can be reduced through parallel work
- negotiation is needed because constraints conflict
If not, keep it single-agent.
### Step 2: Define roles and ownership
Specify:
```text
commander / coordinator
executor(s)
reviewer / auditor
monitor / verifier
fallback owner
```
Each task should have one current `assigned_to`. Multiple reviewers are allowed, but multiple executors writing the same artifact are not unless explicitly coordinated.
### Step 3: Create a SwarmCommand
A command must include:
```json
{
"command_id": "cmd_12345678",
"timestamp": "2026-04-25T12:00:00Z",
"sender": {"type": "coordinator", "id": "001"},
"target": {"type": "developer", "id": "003"},
"command": {
"action": "develop",
"module": "login",
"requirements": ["JWT auth", "tests"],
"output_format": "python_code"
},
"metadata": {
"priority": "high",
"token_budget": 1500,
"deadline": "2026-04-25T13:00:00Z",
"dependencies": []
},
"negotiation": {
"allowed": true,
"timeout": 300
}
}
```
Prefer using `coordinator/swarm_protocol.py` for deterministic command creation and validation. If your project has its own agent taxonomy, map local role names to the protocol roles instead of hard-coding private labels in prompts.
### Step 4: Validate before publish
Before publishing to Redis or memory queue, validate:
- schema format
- known sender / target role
- priority is one of `low | medium | high | critical`
- token budget is positive and within tier quota
- dependencies exist or are intentionally empty
- deadline is realistic
- completion gate is clear
If validation fails, do not publish. Return validation errors and ask for correction or auto-fix safe fields.
### Step 5: Publish, subscribe, and track state
Use:
```python
from coordinator.pubsub import PubSubCoordinator
from coordinator.swarm_protocol import SwarmProtocol
protocol = SwarmProtocol()
coordinator = PubSubCoordinator(use_redis=True)
command = protocol.create_command(
agent_type="developer",
command={"action": "analyze", "module": "performance"},
priority="high",
token_budget=2000,
)
valid, errors = protocol.validate_command(command)
if valid:
coordinator.publish("tasks", command.to_dict())
else:
print(errors)
```
Track state transitions:
```text
pending → assigned → in_progress → completed / failed / cancelled
```
No command should remain `in_progress` forever. Use deadline or heartbeat timeout to trigger fallback.
### Step 6: Collect result and close the loop
Completion should include:
- `success: true/false`
- output or artifact path
- tests/review/verification result when applicable
- token usage
- failure reason if failed
- next action recommendation
If result is missing required artifacts, mark as incomplete instead of completed.
---
## Token Budget and Downgrade Rules
Use token budget as a control mechanism, not just metadata.
Recommended rules:
| Condition | Action |
|---|---|
| budget remaining > 40% | continue normal execution |
| budget remaining 20-40% | compress context and reduce parallel agents |
| budget remaining < 20% | downgrade model/tier or require coordinator approval |
| budget exceeded | stop publishing new subtasks and request confirmation |
| repeated failure | lower concurrency and route to reviewer/monitor |
For local implementation, use `coordinator/token_budget.py` if available.
---
## Negotiation Rules
Allow negotiation when:
- two agents propose conflicting plans
- deadline and token budget cannot both be satisfied
- a dependency is blocked
- an agent lacks capability or context
Negotiation output should be a decision, not endless discussion:
```json
{
"decision": "assign_to_developer_then_review_by_auditor",
"reason": "developer owns implementation; auditor reviews risk",
"budget_adjustment": 500,
"deadline_adjustment": null,
"blocked": false
}
```
If negotiation exceeds timeout, coordinator decides or escalates to human.
---
## Failure Handling
Handle these failures explicitly:
| Failure | Response |
|---|---|
| invalid command | reject before publish; return schema errors |
| target unavailable | reroute to fallback owner |
| dependency blocked | keep pending; notify coordinator |
| budget exceeded | pause or downgrade; do not silently continue |
| deadline missed | mark failed or escalate |
| duplicate owner | choose one owner; cancel duplicate assignment |
| incomplete result | reopen task with missing artifact list |
| repeated failure | reduce concurrency; route to reviewer/monitor |
Never let failures become silent queue drift.
---
## Safety Boundaries
Ask for human confirmation before swarm actions that are:
- destructive: delete data, remove files, reset state
- public: publish, message external users, send email
- costly: paid API calls, high-token parallel execution, cloud deployment
- irreversible: production migrations, permission changes, credential rotation
- ambiguous: unclear task owner, conflicting requirements, missing acceptance criteria
Swarm coordination amplifies mistakes. High-risk actions need stronger gates than single-agent execution.
---
## Output Format
When using this skill, return:
```markdown
## Swarm Plan
- Goal:
- Swarm justified? yes/no + reason
- Agents and roles:
- Ownership model:
## Commands
| command_id | target | action | budget | dependencies | gate |
|---|---|---|---:|---|---|
## Coordination Flow
pending → assigned → in_progress → completed/failed
## Budget / Downgrade
- Total budget:
- Per-agent budget:
- Downgrade trigger:
## Failure / Fallback
- Main risks:
- Fallback owner:
- Escalation condition:
## Verification
- Required artifacts:
- Tests / review:
- Done criteria:
```
For code-facing tasks, also mention which files or APIs to use.
---
## Bundled Resources
Use these resources when needed:
- `coordinator/swarm_protocol.py` — deterministic SwarmCommand creation, validation, assignment, completion, negotiation helpers.
- `schemas/swarm_command.json` — JSON Schema for command validation.
- `tests/test_swarm_protocol.py` — regression tests for protocol behavior.
- `test-prompts.json` — Darwin-style prompts for future skill regression evaluation.
Read or run them when modifying the protocol implementation.
---
## Validation Checklist
Before calling a swarm workflow ready, check:
- [ ] Every task has exactly one current owner.
- [ ] Every command validates against schema.
- [ ] Budget and deadline are explicit.
- [ ] Dependencies are declared.
- [ ] Completion gate is explicit.
- [ ] Failure fallback is defined.
- [ ] High-risk actions require confirmation.
- [ ] Tests or review exist for important outputs.
- [ ] No open-ended negotiation loop remains.
---
## Quality Bar
A good swarm plan should reduce confusion, not add bureaucracy.
It succeeds when:
- agents know exactly what they own
- coordinator can see state and budget
- failures route to a clear fallback
- completion is verifiable
- token use stays bounded
- parallelism improves throughput without oscillation
If the swarm adds agents without improving control, do not use swarm.
don't have the plugin yet? install it then click "run inline in claude" again.
swarm executor coordinates multi-agent task execution using standardized SwarmCommand messages, pub/sub orchestration, token-budget governance, and explicit state tracking. use this skill when your task requires multiple agents to work in parallel with clear ownership, bounded cost control, and verifiable completion without duplicating work or burning uncontrolled tokens. avoid it for single-agent tasks. swarm overhead only pays off when parallelism improves throughput, latency, or quality while maintaining strict control over cost, state, and ownership.
SWARM_REDIS_URL (e.g., redis://localhost:6379). if not set, skill falls back to in-memory queue. requires read/write permissions on channels named tasks, results, negotiation.{"developer": ["id_001", "id_002"], "reviewer": ["id_003"]}. pass as env var SWARM_AGENT_REGISTRY or inline dict.coordinator_id: string, identifies the coordinator agent sending commands. default: "coordinator_001".use_redis: boolean, use redis or in-memory pub/sub. default: true if SWARM_REDIS_URL set, else false.command_schema_path: string, path to json schema for swarmcommand validation. default: schemas/swarm_command.json (bundled).negotiation_timeout_sec: int, max seconds to wait for agent negotiation before coordinator decides. default: 300.heartbeat_timeout_sec: int, max seconds an agent can stay in in_progress before triggering fallback. default: 600.inputs: task description, estimated complexity, available agents, latency requirement.
action: evaluate whether swarm adds value. swarm is justified if at least one is true:
output: boolean decision (swarm_justified: true/false) and reasoning string.
edge case: if task is already complex, adding swarm coordination can reduce clarity. document why swarm improves control before proceeding.
inputs: agent registry (mapping of role to agent ids), task scope.
action: assign roles explicitly:
coordinator: publishes commands, resolves conflicts, gates high-risk actionsexecutor(s): performs work on assigned tasks (one per task unless explicitly coordinated)reviewer: validates output before completionmonitor: tracks budget, deadline, and heartbeat; triggers fallback if neededfallback_owner: escalation target if primary executor failsdocument current owner of each task (initially null until assigned).
output: role assignment dict in json format:
{
"coordinator": {"type": "coordinator", "id": "001"},
"executors": [
{"type": "developer", "id": "003"},
{"type": "data_analyst", "id": "004"}
],
"reviewer": {"type": "auditor", "id": "005"},
"monitor": {"type": "monitor", "id": "006"},
"fallback_owner": {"type": "developer", "id": "002"}
}
edge case: if an agent must play multiple roles (e.g., coder + reviewer in small teams), explicitly note the conflict in completion gate (e.g., "coder implements; separate human review required").
inputs: task description, assigned target agent, token budget, deadline, dependencies, completion gate.
action: construct a SwarmCommand json object with required fields:
{
"command_id": "cmd_<8-char-uuid>",
"timestamp": "<ISO 8601 UTC>",
"sender": {"type": "coordinator", "id": "<coordinator_id>"},
"target": {"type": "<agent_type>", "id": "<agent_id>"},
"command": {
"action": "<verb>",
"module": "<scope>",
"requirements": ["<req1>", "<req2>"],
"output_format": "<format>"
},
"metadata": {
"priority": "<low|medium|high|critical>",
"token_budget": <int>,
"deadline": "<ISO 8601 UTC>",
"dependencies": ["cmd_<id>", ...]
},
"negotiation": {
"allowed": <boolean>,
"timeout": <int seconds>
}
}
use bundled coordinator/swarm_protocol.py for deterministic creation and validation; do not hardcode role names in prompt text.
output: validated SwarmCommand json object.
edge cases:
[] (not null).allowed: false.inputs: SwarmCommand object from step 3.
action: run validation against schema:
schemas/swarm_command.jsonlow | medium | high | criticaluse bundled coordinator/swarm_protocol.py method validate_command().
output: tuple (is_valid: bool, errors: list[str]).
if not valid, return errors to user and request correction or auto-fix safe fields. do not publish invalid commands.
edge case: if token oracle is unavailable, skip budget tier check and warn in logs; manual review required.
inputs: validated SwarmCommand, pub/sub backend (redis or in-memory), agent registry.
action:
tasks (topic key = agent type, e.g., tasks:developer){command_id: "cmd_...", state: "pending", assigned_to: null, created_at: "...", started_at: null, completed_at: null, result: null}results:<command_id> to watch for completionin_progress and no heartbeat received within heartbeat_timeout_sec, trigger fallback (step 8)use coordinator/pubsub.py class PubSubCoordinator for safe publish/subscribe with error handling.
output: command published successfully (no exceptions), state record created, monitor started.
edge cases:
inputs: published command_id, target agent_id from registry.
action:
assignedassigned_to field to target agent_idtasks:<target_agent_id> channeloutput: state transitions from pending to assigned, assigned_to field populated.
edge cases:
inputs: command with negotiation.allowed = true, agent response indicating conflict (e.g., insufficient token budget, deadline unrealistic, missing capability).
action:
negotiation:<command_id> channel with reason and counter-proposal (e.g., request +500 token budget, extend deadline by 30 min, or decline if capability missing)negotiation_timeout_sec windownegotiation output must be a decision, not endless loop:
{
"decision": "approve_counter_proposal | reject_reroute | escalate",
"reason": "<explanation>",
"budget_adjustment": <int or 0>,
"deadline_adjustment_sec": <int or 0>,
"new_assigned_to": "<agent_id or null>",
"blocked": false
}
output: negotiation decision published, state updated accordingly.
edge cases:
inputs: command in in_progress state, heartbeat_timeout_sec parameter, fallback_owner from role assignment.
action: run continuous monitor:
failedpending state with original requirements plus note: "previous executor failed after output: command reassigned to fallback owner, state transitions from in_progress to failed to pending (new assignment).
edge cases:
inputs: executor publishes result message to results:<command_id> channel with fields:
{
"command_id": "cmd_...",
"success": true|false,
"output": "<artifact or summary>",
"artifact_path": "<file path or url>",
"token_usage": <int>,
"tests_passed": true|false,
"review_status": "approved|pending|rejected",
"failure_reason": "<string if success=false>",
"next_action": "<recommendation>"
}
action:
tests_passed missing, mark as incomplete and reopen with explicit artifact listreview_status missing, send to reviewer (step 10)completedoutput: state transitions to completed (if all gates passed) or incomplete (if artifacts missing). result record stored.
edge cases:
failed and trigger fallback (step 8).inputs: result with review_status = pending, reviewer agent_id from role assignment.
action:
tasks:reviewer channelapproved | rejected | needs_reworkcompletedoutput: command state transitions to completed or new rework command created.
edge cases:
in_progress state.inputs: completed command, token usage recorded, result artifacts verified.
action:
completed and populate completed_at timestampoutput: command marked complete, budget updated, completion event published.
edge case: if command required dependent tasks, trigger those pending assignments now (dependencies satisfied).
inputs: per-agent token budget, current usage, remaining budget percentage.
action: evaluate budget remaining:
| budget remaining | action |
|---|---|
| > 40% | continue normal execution, no change |
| 20-40% | compress context in next commands; reduce parallel agent count; warn coordinator |
| < 20% | require coordinator approval before publishing new subtasks; suggest model downgrade (gpt-3.5 instead of gpt-4) |
| exceeded | stop publishing new subtasks immediately; mark monitor state as paused; request budget increase or human decision |
| repeated failure with budget pressure | lower concurrency; route next attempt to reviewer/monitor for manual execution |
use bundled coordinator/token_budget.py for deterministic downgrade logic.
output: downgrade action published, monitor state updated, coordinator alerted.
edge cases:
inputs: command state, failure reason from executor or monitor.
action: route failures explicitly:
| failure type | handler | action |
|---|---|---|
| invalid command | coordinator | reject before publish; return schema errors; ask for correction |
| target unavailable | monitor | reroute to fallback_owner immediately |
| dependency blocked | monitor | keep command in pending; notify coordinator with blocked dependency list |
| budget exceeded | monitor | pause all new subtasks; request confirmation |
| deadline missed | monitor | mark command failed; log deadline violation; trigger fallback |
| duplicate owner | coordinator | choose owner; cancel duplicate assignment; investigate cause |
| incomplete result | reviewer | reopen with explicit artifact checklist; send back to executor |
| repeated failure (> 2 attempts) | monitor | reduce concurrency; route to reviewer/auditor for manual review |
| network/pub-sub error | monitor | retry publish up to 3 times; if persistent, escalate to human |
publish failure record:
{
"command_id": "cmd_...",
"failure_type": "<type>",
"reason": "<explanation>",
"timestamp": "<ISO 8601>",
"handler": "<coordinator|monitor|reviewer>",
"action_taken": "<description>",
"escalation_to": "<agent_id or null>"
}
output: failure logged, action taken published, escalation routed.
edge cases:
swarm vs single-agent (step 1): if task is simple and one agent can complete it, do not use swarm. only use if parallelism improves throughput, latency, or quality while maintaining control. if decision unclear, document both options and ask user to choose.
negotiation needed (step 7): if executor indicates conflict (budget, deadline, capability), allow negotiation only if negotiation.allowed = true in command. if false or timeout expires, coordinator decides (approve, reject+reroute, or escalate). no open-ended loops.
target unavailable (step 6, 8): if assigned agent is offline or not in registry, immediately reroute to fallback_owner. do not wait or retry assignment to same agent.
budget downgrade (step 12): if remaining budget < 20%, require explicit coordinator approval before publishing new tasks. if no approval within 5 min, pause all pending work (fail-safe). do not continue silently.
**failure escalation (step 13)