Deploy 10,000 agents on one task — parallel, pipeline, or consensus strategies.
Swarm Execution
The SwarmProtocol from @codmir/cortex coordinates thousands of AI agents working on a single task. It handles task decomposition, agent recruitment, file locking, budget tracking, and result merging.
What Is Swarm Execution
A swarm is a group of AI agents working on one task with a shared plan. Instead of one agent doing everything sequentially, a swarm decomposes the task into subtasks and distributes them across agents that work in parallel, in pipelines, or through consensus.
The swarm state lives in the .cortex/ directory as swarm.crtx, readable by any agent in the project.
Create a Swarm
import { CortexIO, Timeline, SwarmProtocol } from '@codmir/cortex';
const io = new CortexIO('/path/to/project');
await io.init();
const timeline = new Timeline(io);
const swarm = new SwarmProtocol(io, timeline);
const manifest = await swarm.create({
task: 'Migrate authentication from sessions to JWT',
coordinatorId: 'agent-coordinator-1',
strategy: 'parallel',
maxAgents: 50,
maxTokens: 10_000_000,
maxCostUsd: 25.0,
maxDurationMs: 3_600_000, // 1 hour
mergePolicy: {
strategy: 'coordinator_review',
conflictResolution: 'coordinator_decides',
requireHumanApproval: false,
},
decomposition: {
id: 'root',
description: 'Migrate auth to JWT',
status: 'pending',
priority: 1,
estimatedTokens: 10_000_000,
dependencies: [],
children: [
{
id: 'task-1',
description: 'Create JWT utility module',
status: 'pending',
priority: 1,
estimatedTokens: 500_000,
dependencies: [],
children: [],
},
{
id: 'task-2',
description: 'Update login endpoint',
status: 'pending',
priority: 2,
estimatedTokens: 800_000,
dependencies: ['task-1'],
children: [],
},
{
id: 'task-3',
description: 'Update middleware to validate JWT',
status: 'pending',
priority: 2,
estimatedTokens: 600_000,
dependencies: ['task-1'],
children: [],
},
],
},
});
console.log(manifest.id); // Unique swarm ID
console.log(manifest.strategy); // 'parallel'
console.log(manifest.budget); // { maxAgents: 50, maxTokens: 10000000, ... }Strategies
| Strategy | How It Works |
|---|---|
parallel | All agents work independently on their assigned subtasks. Results are merged at the end. |
pipeline | Sequential execution. Each agent's output feeds into the next agent's input. |
hierarchical | A coordinator agent delegates to worker agents, reviews their output, and delegates further. |
consensus | Agents vote on the approach before executing. Requires agreement threshold. |
competitive | Multiple agents solve the same subtask. The best result wins. |
Recruit Agents
Add agents to the swarm with defined roles and expertise:
const agent1 = await swarm.recruit(
'agent-jwt-specialist',
'jwt-implementer',
['authentication', 'cryptography', 'node.js'],
);
const agent2 = await swarm.recruit(
'agent-api-dev',
'endpoint-developer',
['rest-api', 'express', 'middleware'],
);
const agent3 = await swarm.recruit(
'agent-test-writer',
'test-engineer',
['jest', 'integration-testing', 'auth-testing'],
);Recruitment fails if the swarm is at capacity (maxAgents in budget).
Assign and Complete Tasks
// Assign a task to an agent
await swarm.assign('agent-jwt-specialist', 'task-1');
// Mark task as complete with usage stats
await swarm.complete(
'agent-jwt-specialist',
'task-1',
450_000, // tokens used
1.35, // cost in USD
{ files: ['src/lib/jwt.ts', 'src/lib/jwt.test.ts'] },
);Budget Tracking
Every swarm has a budget that tracks four dimensions:
interface SwarmBudget {
maxAgents: number; // Maximum concurrent agents
maxTokens: number; // Total token budget
maxCostUsd: number; // Total cost cap in USD
maxDurationMs: number; // Wall-clock time limit
spent: {
agents: number; // Agents recruited so far
tokens: number; // Tokens consumed so far
costUsd: number; // Cost incurred so far
durationMs: number; // Time elapsed so far
};
}The swarm refuses to recruit agents or assign tasks when any budget dimension is exceeded.
File Locking for Parallel Writes
When multiple agents work in parallel, file locks prevent conflicting writes:
interface SwarmLock {
path: string; // File path being locked
agentId: string; // Agent holding the lock
type: 'exclusive' | 'shared';
acquiredAt: number;
expiresAt: number;
reason: string;
}- Exclusive locks prevent other agents from reading or writing the file
- Shared locks allow concurrent reads but block writes
Locks are stored in the swarm manifest and expire automatically.
Merging Results
The MergePolicy controls how agent outputs are combined:
interface MergePolicy {
strategy: 'auto' | 'voting' | 'coordinator_review' | 'human_review';
conflictResolution: 'last_write' | 'highest_confidence' | 'coordinator_decides' | 'vote';
minAgreePercent?: number;
requireHumanApproval: boolean;
}| Strategy | When to Use |
|---|---|
auto | Non-conflicting changes (separate files). Merge automatically. |
voting | Multiple agents solved the same subtask. Majority wins. |
coordinator_review | Coordinator agent reviews and approves all merges. |
human_review | Human must approve before merging. Safest option. |
Timeline Integration
Every swarm action is recorded in the Cortex timeline for auditability:
const timeline = new Timeline(io);
// All swarm operations (create, recruit, assign, complete) automatically
// record entries in the timeline with type 'delegation'This means any future agent can read the timeline and understand what was tried, what worked, and what failed.
Next Steps
- Cortex Protocol -- the file format that makes swarm coordination possible
- Multi-Provider AI -- route swarm tasks to different AI providers
- Self-Healing -- trigger swarms from production incidents