🐝Swarm Tools

Swarm Tools Documentation

Multi-agent coordination that survives context death and learns from outcomes

███████╗██╗    ██╗ █████╗ ██████╗ ███╗   ███╗  ████████╗ ██████╗  ██████╗ ██╗     ███████╗
██╔════╝██║    ██║██╔══██╗██╔══██╗████╗ ████║  ╚══██╔══╝██╔═══██╗██╔═══██╗██║     ██╔════╝
███████╗██║ █╗ ██║███████║██████╔╝██╔████╔██║     ██║   ██║   ██║██║   ██║██║     ███████╗
╚════██║██║███╗██║██╔══██║██╔══██╗██║╚██╔╝██║     ██║   ██║   ██║██║   ██║██║     ╚════██║
███████║╚███╔███╔╝██║  ██║██║  ██║██║ ╚═╝ ██║     ██║   ╚██████╔╝╚██████╔╝███████╗███████║
╚══════╝ ╚══╝╚══╝ ╚═╝  ╚═╝╚═╝  ╚═╝╚═╝     ╚═╝     ╚═╝    ╚═════╝  ╚═════╝ ╚══════╝╚══════╝
                                    🐝

Framework-agnostic primitives for building multi-agent AI systems. Works with Claude, GPT, Gemini, or any AI agent framework.

The Problem

You're working with an AI coding agent. You ask it to "add OAuth authentication." It starts writing code. Five minutes later, you realize it's going down the wrong path. Or it's touching files it shouldn't. Or it's making changes that conflict with what you just did in another session.

The fundamental issue: AI agents are single-threaded, context-limited, and have no memory of what worked before.

The Solution

What if the agent could:

  • Break the task into pieces that can be worked on simultaneously
  • Spawn parallel workers that don't step on each other
  • Remember what worked and avoid patterns that failed
  • Survive context compaction without losing progress

That's what Swarm does.

How It Works

                            "Add OAuth"


                    ┌────────────────────────┐
                    │      COORDINATOR       │
                    │                        │
                    │  1. Query CASS         │
                    │  2. Pick strategy      │
                    │  3. Break into pieces  │
                    └────────────────────────┘

           ┌─────────────────────┼─────────────────────┐
           ▼                     ▼                     ▼
    ┌─────────────┐       ┌─────────────┐       ┌─────────────┐
    │  Worker A   │       │  Worker B   │       │  Worker C   │
    │ auth/oauth  │       │ auth/session│       │ auth/tests  │
    │   🔒 files  │       │   🔒 files  │       │   🔒 files  │
    └─────────────┘       └─────────────┘       └─────────────┘

The opencode-swarm-plugin is what you install and use. It provides:

  • Task decomposition - Breaks complex requests into parallel subtasks
  • File reservations - Prevents edit conflicts between workers
  • Learning system - Tracks what strategies work (fast + success = good, slow + errors = bad)
  • Skills - Knowledge packages agents can load when needed
  • Hive - Git-backed work item tracking integrated with swarm coordination

Under the hood, it uses swarm-mail for event sourcing and actor-model messaging. That's the infrastructure layer—interesting if you're building your own coordination system, but you don't need to think about it to use the plugin.

What Makes It Different

1. Survives Context Death[Proven - 95% integration test coverage]

When swarm_progress reports 25%, 50%, or 75% completion, an automatic checkpoint is created and stored in libSQL (embedded SQLite). If context compaction happens or an agent crashes, swarm_recover retrieves the last checkpoint with:

  • Files modified so far
  • Current strategy (file-based, feature-based, risk-based)
  • Progress percentage
  • Coordinator directives (shared context, skills to load, notes)
  • Error context (if checkpoint happened during error handling)

No external database needed—checkpoints persist in system temp directory. Non-fatal failures mean work continues even if checkpoint fails.

2. Learns From Outcomes

Every completed task records learning signals:

  • Fast completion + zero errors → Pattern gets promoted
  • Slow + retries + errors → Pattern gets demoted
  • 60% failure rate → Pattern auto-inverts to anti-pattern

3. Has Skills

Bundled knowledge packages for common domains:

  • testing-patterns - Feathers dependency-breaking techniques
  • swarm-coordination - Multi-agent orchestration
  • cli-builder - Argument parsing, help text, subcommands
  • learning-systems - Confidence decay, pattern maturity

Checkpoint & Recovery

The checkpoint system ensures no work is lost during context compaction or crashes.

How It Works

Automatic Checkpoints - When swarm_progress reports:

  • 25% completion → First checkpoint saved
  • 50% completion → Midpoint checkpoint saved
  • 75% completion → Near-completion checkpoint saved

Each checkpoint stores:

{
  files: ["src/auth.ts", "src/middleware.ts"],
  strategy: "file-based",
  progress_percent: 50,
  directives: {
    shared_context: "OAuth implementation notes",
    skills_to_load: ["testing-patterns"],
    coordinator_notes: "Watch for race conditions"
  },
  recovery: {
    last_checkpoint: 1234567890,
    files_modified: ["src/auth.ts"],
    error_context: "Optional: errors encountered"
  }
}

Manual Checkpoints - Workers can also create checkpoints explicitly:

swarm_checkpoint({
  project_key: "/path/to/project",
  agent_name: "WorkerA",
  cell_id: "bd-123.1",
  epic_id: "bd-123",
  files_modified: ["src/auth.ts"],
  progress_percent: 30,
  directives: { /* optional */ },
  error_context: "Optional error details"
})

Recovery - Resume from last checkpoint:

swarm_recover({
  project_key: "/path/to/project",
  epic_id: "bd-123"
})
// Returns: { found: true, context: { ... }, age_seconds: 120 }

Storage

Checkpoints are stored in libSQL (embedded SQLite) in your system's temp directory. No external database needed. The swarm_contexts table tracks all checkpoints with full event sourcing for audit trail.

Failure Handling

Checkpoint failures are non-fatal—if a checkpoint fails, work continues. You'll see a warning in logs but the agent keeps going. This prevents checkpoint infrastructure from blocking actual work.

Quick Start

See the Quickstart Guide for detailed installation instructions.

TL;DR:

npm install -g opencode-swarm-plugin@latest
swarm setup

Then in OpenCode:

/swarm "Add user authentication with OAuth"

The plugin queries past decompositions (via CASS), picks a strategy, creates cells, spawns workers, and tracks learning signals.

Dependencies

Required

DependencyPurpose
OpenCodeAI coding agent (the plugin runs inside OpenCode)
HiveGit-backed work item tracking

These tools significantly enhance the swarm experience:

ToolPurpose
CASSHistorical context - queries past sessions for similar decompositions
UBSBug scanning - runs on subtask completion to catch issues

Installing Optional Dependencies

git clone https://github.com/Dicklesworthstone/coding_agent_session_search
cd coding_agent_session_search
pip install -e .
cass index  # Build the index (run periodically)

UBS (Ultimate Bug Scanner)

git clone https://github.com/Dicklesworthstone/ultimate_bug_scanner
cd ultimate_bug_scanner
pip install -e .

Why install these?

  • CASS - When you run /swarm "Add OAuth", the coordinator queries CASS for similar past tasks. Without it, decomposition is based only on the current task description.
  • UBS - Every swarm_complete runs UBS to scan for bugs. Without it, you lose automatic bug detection.

Note: Semantic memory is now embedded in the plugin—no separate installation required. Pattern maturity and anti-pattern detection persist automatically using libSQL.

Run swarm doctor to check which dependencies are installed.

What's Included

opencode-swarm-plugin - The plugin you install (40+ tools):

CategoryToolsPurpose
Hive8 toolsGit-backed work item tracking with atomic epic creation
Swarm Mail6 toolsInter-agent messaging with file reservations
Swarm20+ toolsTask decomposition, parallel orchestration, learning
Skills4 toolsKnowledge injection with bundled domain expertise

View all plugin tools →

swarm-mail - Event sourcing infrastructure (used by the plugin):

If you're building your own agent coordination system, swarm-mail provides the primitives:

bun add swarm-mail

View swarm-mail architecture →

Examples

Swarm Coordination (Plugin)

// In OpenCode, use the /swarm command:
/swarm "Add user authentication with OAuth"

// The plugin:
// 1. Queries CASS for similar past decompositions
// 2. Generates a strategy-specific decomposition
// 3. Creates epic + subtasks atomically
// 4. Spawns parallel worker agents
// 5. Tracks progress via Agent Mail
// 6. Records learning signals for future improvements

File Reservations

import { reserveSwarmFiles, releaseSwarmFiles } from 'swarm-mail';

// Reserve files before editing (prevents conflicts)
await reserveSwarmFiles(
  'WorkerA',
  ['src/auth/**', 'src/lib/jwt.ts'],
  { reason: 'bd-123.2: Auth service implementation' }
);

// Do work...

// Release when done
await releaseSwarmFiles('WorkerA');

Event Sourcing (swarm-mail)

import { getSwarmMailLibSQL } from 'swarm-mail';

// Get swarm mail instance (libSQL adapter)
const swarmMail = await getSwarmMailLibSQL('/my/project');

// Append events
await swarmMail.appendEvent({
  type: 'agent_registered',
  agent_name: 'WorkerA',
  task_description: 'Implementing auth service',
  timestamp: Date.now(),
});

// Query projections
const agents = await swarmMail.getAgents();
const messages = await swarmMail.getInbox('WorkerA', { limit: 5 });

Durable Primitives (swarm-mail + Effect-TS)

import { DurableMailbox, DurableLock, ask } from 'swarm-mail';
import { Effect } from 'effect';

// Actor mailbox
const mailbox = DurableMailbox.create<MyMessage>('worker-a');
await Effect.runPromise(
  mailbox.send({ type: 'task', payload: 'implement feature' })
);

// File locking with automatic release
const lock = DurableLock.create('src/auth.ts');
await Effect.runPromise(
  lock.acquire({ ttl: 60000 }).pipe(
    Effect.flatMap(() => /* do work */),
    Effect.ensuring(lock.release())
  )
);

// Request/response pattern
const response = await Effect.runPromise(
  ask<Request, Response>('other-agent', { type: 'get-types' })
);

Technical Details

Architecture

┌─────────────────────────────────────────────────────────────┐
│                     SWARM TOOLS STACK                       │
├─────────────────────────────────────────────────────────────┤
│  TIER 3: ORCHESTRATION                                      │
│  └── OpenCode Plugin (hive, swarm, skills, learning)       │
│                                                             │
│  TIER 2: COORDINATION                                       │
│  ├── DurableMailbox - Actor inbox with typed envelopes     │
│  ├── DurableLock - CAS-based mutual exclusion              │
│  └── ask<Req, Res>() - Request/Response (RPC-style)        │
│                                                             │
│  TIER 1: PRIMITIVES                                         │
│  ├── DurableCursor - Checkpointed stream reader            │
│  └── DurableDeferred - Distributed promise                 │
│                                                             │
│  STORAGE                                                    │
│  └── libSQL (Embedded SQLite) + Event Sourcing             │
└─────────────────────────────────────────────────────────────┘

Philosophy

Primitives, not frameworks. Each package solves one problem well.

  • Composable - Mix and match what you need
  • Zero lock-in - Works with any agent framework
  • Type-safe - Full TypeScript with Zod schemas
  • Local-first - libSQL embedded database, no external servers
  • Fast - Bun-native, minimal dependencies

Next Steps

Get Started:

Using the Plugin:

Building Your Own:

Historical:

  • Roadmap - Future plans and experimental features
  • Credits - People and projects that inspired this work

Community

License

MIT - Use freely in commercial and open-source projects.

On this page