Preparing your workspace...

assistant-chat.tsx2.5k
utils.ts850
button.tsx720
Quick Actions
codmir
Docs
Discord
Get started
API
  • Introduction
  • Installation
  • Your First Project
  • Your First Agent
  • All Guides
    • Swarm Execution
    • Cortex Protocol
    • Voice Control
    • CLI Reference

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

StrategyHow It Works
parallelAll agents work independently on their assigned subtasks. Results are merged at the end.
pipelineSequential execution. Each agent's output feeds into the next agent's input.
hierarchicalA coordinator agent delegates to worker agents, reviews their output, and delegates further.
consensusAgents vote on the approach before executing. Requires agreement threshold.
competitiveMultiple 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;
}
StrategyWhen to Use
autoNon-conflicting changes (separate files). Merge automatically.
votingMultiple agents solved the same subtask. Majority wins.
coordinator_reviewCoordinator agent reviews and approves all merges.
human_reviewHuman 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
Open in ChatGPTOpen in ClaudeConnect MCP on CursorConnect MCP on WindsurfEdit on GitHub
codmir
Products
Desktop AppMobile AppIDE ExtensionAI AgentsOverseerVoice ModeCortex ProtocolHive MindGame Dev (Godat)PricingDownload
Solutions
AI Code AgentsCode ReviewError TrackingSelf-HealingDeploy TrackingAI Tracking SDKWorkflow AutomationTesting FrameworkTime TrackingVoice Control
Platform
ProjectsTickets & BoardsAgent MarketplaceIntegrationsTemplatesApp HubAdmin PanelAnalytics
Integrations
GitHubSlackDiscordVercelSentryRailwayLinearAll Integrations
Developers
DocumentationAPI ReferenceSDKCLIDeveloper PortalMarketplaceMCP ConnectorsWebhooksExamplesnpm Packages
Resources
BlogChangelogCommunityTutorialsGet StartedSupportStatusFeedback
Company
AboutCareersContact SalesKickstarterReferral Program
Legal
Terms of UsePrivacy PolicyEULATrademarkSecurity
Download on the App StoreGet it on Google Play

Codmir™ 2026. All rights reserved.

Free & open source SDK — Apache 2.0 License