By Benni Alencar — Chief AI Systems Architect at Benni OS. Canonical article & interactive benchmarks at benni-os.net.
Every power user eventually hits the same scaling wall: one Claude Code session is fast, so opening four terminal tabs in the same repository ought to be four times faster. In practice, uncoordinated parallel coding agents behave like four developers editing the same working directory with zero locks, zero communication, and zero shared budget.
Within minutes, naive parallelism collapses into four predictable failure modes:
src/auth.py, Worker B rewrites it, and Worker A's next Edit or Write call clobbers Worker B's patch without warning..git/index.lock contention.
Runaway Multi-Terminal Token Bills: Four agents stuck in competing test-fix loops multiply API burn by 4×—with no global USD circuit breaker across terminals.
**Core Architectural Principle:** Parallelism without mutual exclusion is just distributed race conditions. **[Benni-OS/claude-code-swarm](https://github.com/Benni-OS/claude-code-swarm)** turns independent Claude Code processes into a deterministic swarm using isolated `git worktree` sandboxes, SQLite3 WAL file leases enforced in `PreToolUse`, a shared MCP blackboard, global USD caps, and pre-merge AST gates.
Instead of letting agents race inside one directory or coordinate via fragile markdown files, claude-code-swarm separates filesystem isolation, concurrency control, and task coordination into three deterministic layers:
flowchart TD
M["Shared MCP Task Blackboard<br/>(Claims, Dependencies, Contracts)"] -->|"Assign Task"| W1["Worker 1 (git worktree: swarm/w1)"]
M -->|"Assign Task"| W2["Worker 2 (git worktree: swarm/w2)"]
W1 -->|"PreToolUse (< 1ms)"| L["SQLite3 WAL Coordinator<br/>File Leases + Global USD Ledger"]
W2 -->|"PreToolUse (< 1ms)"| L
L -->|"Lease Held by Peer / Cap Hit"| X["Exit 2: Blocked Deterministically"]
L -->|"Lease Granted + Budget OK"| E["Isolated Edit & Test in Worktree"]
E -->|"Done"| G["Pre-Merge AST & Lint Gate"]
G -->|"Syntax / Stub Defect"| E
G -->|"Verified Clean"| R["Atomic Fast-Forward / Rebase to main"]
Each worker gets its own physical directory via git worktree, its own branch, and its own build/test state—while sharing a single local SQLite3 database in Write-Ahead Logging (WAL) mode and a unified MCP blackboard server.
When you spawn a swarm of N workers, claude-code-swarm provisions N dedicated git worktree checkouts under .swarm/worktrees/<worker_id>, each bound to a clean feature branch. Workers never share a working tree, never contend on .git/index.lock, and can run isolated test suites concurrently.
Worktrees isolate directories, but if Worker 1 and Worker 2 both rewrite src/router.py on separate branches, you still face a painful merge conflict. Before any Edit, Write, or mutating Bash tool executes, the PreToolUse hook queries the shared SQLite3 WAL lease table with BEGIN IMMEDIATE:
worker_id), the lease is atomically acquired or renewed with a TTL. 2 with the holder's ID and active task—forcing the blocked worker to pick another task on the MCP blackboard instead of creating a merge conflict.
Every worker connects to the swarm's MCP server (claude mcp add swarm-blackboard). The blackboard exposes deterministic tools to list unclaimed tasks, atomically claim a task ID, post interface contracts (such as new TypeScript types or REST payloads) for downstream workers, and mark tasks ready for merge.
Per-terminal budgets are useless if four terminals each burn $5 on a stuck retry loop. Every worker's PostToolUse hook records token deltas into the same SQLite3 WAL ledger. Before any worker executes its next tool call, PreToolUse checks SUM(cost_usd) across the entire swarm. The moment global spend hits max_swarm_usd, every worker trips the circuit breaker simultaneously.
Passing a worker's own unit tests is not enough to land on main. Before the coordinator merges any git worktree branch, a deterministic AST gate parses all modified files to reject syntax errors, unresolved merge markers, banned TODO/ NotImplementedError stubs, and broken imports—guaranteeing that main never receives half-finished agent output.
Setting up a coordinated swarm requires registering the shared MCP blackboard and binding the deterministic lease and budget hooks in .claude/settings.json:
pip install claude-code-swarm
claude-swarm init --workers 3 --max-swarm-usd 6.00 --lease-ttl 300
claude mcp add swarm-blackboard -- claude-swarm mcp-serve
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write|MultiEdit|Bash",
"hooks": [
{
"type": "command",
"command": "claude-swarm hook pre-tool-use",
"timeout": 2000
}
]
}
],
"PostToolUse": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "claude-swarm hook post-tool-use",
"timeout": 2000
}
]
}
]
}
}
Below is the core atomic lease and budget enforcement logic executed in under a millisecond inside PreToolUse. Because SQLite3 runs in WAL mode with BEGIN IMMEDIATE, concurrent workers never corrupt state or race past each other:
import json
import sqlite3
import sys
import time
from pathlib import Path
DB_PATH = Path(".swarm/coordinator.db")
def enforce_lease_and_budget(
worker_id: str,
target_path: str | None,
max_swarm_usd: float = 6.00,
ttl_sec: int = 300,
) -> tuple[int, str]:
now = time.time()
conn = sqlite3.connect(DB_PATH, timeout=5.0, isolation_level=None)
conn.execute("PRAGMA journal_mode=WAL;")
try:
conn.execute("BEGIN IMMEDIATE;")
row = conn.execute("SELECT COALESCE(SUM(cost_usd), 0.0) FROM spend_ledger").fetchone()
total_usd = float(row[0])
if total_usd >= max_swarm_usd:
conn.execute("ROLLBACK;")
return 2, f"SWARM_BUDGET_CAP: Global spend ${total_usd:.4f} >= cap ${max_swarm_usd:.2f}."
if target_path:
conn.execute("DELETE FROM file_leases WHERE expires_at < ?", (now,))
holder = conn.execute(
"SELECT worker_id FROM file_leases WHERE file_path = ?",
(target_path,),
).fetchone()
if holder and holder[0] != worker_id:
conn.execute("ROLLBACK;")
return 2, (
f"FILE_LEASE_CONFLICT: '{target_path}' is leased by '{holder[0]}'. "
"Claim another task on the MCP blackboard."
)
conn.execute(
"""
INSERT INTO file_leases (file_path, worker_id, expires_at)
VALUES (?, ?, ?)
ON CONFLICT(file_path) DO UPDATE SET
worker_id = excluded.worker_id,
expires_at = excluded.expires_at
""",
(target_path, worker_id, now + ttl_sec),
)
conn.execute("COMMIT;")
return 0, json.dumps({"decision": "allow", "worker_id": worker_id, "global_usd": total_usd})
finally:
conn.close()
if __name__ == "__main__":
payload = json.load(sys.stdin)
worker = payload.get("worker_id", "worker-1")
file_path = payload.get("tool_input", {}).get("file_path")
code, msg = enforce_lease_and_budget(worker, file_path)
if code != 0:
sys.stderr.write(msg + "\n")
sys.exit(code)
| Orchestration Dimension | Uncoordinated Parallel Terminals | Benni-OS/claude-code-swarm |
|---|---|---|
| Filesystem Isolation | Shared working tree (silent overwrites & index locks) | Dedicated git worktree & branch per worker |
| Concurrent File Edits | Race conditions & three-way merge chaos | Atomic SQLite3 WAL File Leases in PreToolUse |
| Task & Contract Sharing | Manual copy-paste or duplicated work | Shared MCP Task Blackboard with atomic claims |
| Multi-Terminal Spend Control | No global visibility; N × runaway loops | Global Swarm USD Cap across all workers |
| Merge Quality Gate | Manual conflict resolution & broken stubs | Deterministic Pre-Merge AST & Lint Gate |
Deploy Benni-OS/claude-code-swarm to isolate parallel workers in git worktree sandboxes, enforce SQLite3 WAL file leases in PreToolUse, coordinate via MCP, and cap global swarm spend.
Explore Benni-OS/claude-code-swarm on GitHub →
Why do parallel Claude Code terminals overwrite each other's files?
When multiple Claude Code instances share a single working tree, they operate against the same filesystem paths concurrently without mutual exclusion. Worker A can read a file, Worker B can rewrite it, and Worker A's subsequent Edit or Write call silently clobbers Worker B's changes or triggers git index lock collisions.
How do SQLite3 WAL file leases in PreToolUse prevent edit collisions?
Even with isolated `git worktree` checkouts, two workers editing the same logical file path across branches will produce nasty merge conflicts. `claude-code-swarm` stores path-level leases in a shared SQLite3 database running in WAL mode. Before any `Edit` or `Write` executes, the `PreToolUse` hook attempts an atomic lease acquisition; if another active worker holds the lease, it exits with code `2` and redirects the agent.
What role does the shared MCP task blackboard play?
The MCP blackboard gives every worker a single, atomic source of truth for task claims, dependency graphs, heartbeats, and completion artifacts. Instead of duplicating work across terminals, workers claim unclaimed tasks via MCP, publish interface contracts for downstream tasks, and release leases upon completion.
How do global swarm USD caps and pre-merge AST gates protect production?
Every worker's token and USD spend rolls up into the shared SQLite3 WAL ledger; once the global swarm cap is reached, `PreToolUse` trips the circuit breaker across all terminals simultaneously. Before any worker's `git worktree` branch is merged back to `main`, an AST gate validates syntax, imports, and zero placeholder stubs deterministically.
When multiple Claude Code instances share a single working tree, they operate against the same filesystem paths concurrently without mutual exclusion. Worker A can read a file, Worker B can rewrite it, and Worker A's subsequent Edit or Write call silently clobbers Worker B's changes or triggers git index lock collisions.
Even with isolated git worktree checkouts, two workers editing the same logical file path across branches will produce nasty merge conflicts. claude-code-swarm stores path-level leases in a shared SQLite3 database running in WAL mode. Before any Edit or Write executes, the PreToolUse hook attempts an atomic lease acquisition; if another active worker holds the lease, it exits with code 2 and redirects the agent.
The MCP blackboard gives every worker a single, atomic source of truth for task claims, dependency graphs, heartbeats, and completion artifacts. Instead of duplicating work across terminals, workers claim unclaimed tasks via MCP, publish interface contracts for downstream tasks, and release leases upon completion.
Every worker's token and USD spend rolls up into the shared SQLite3 WAL ledger; once the global swarm cap is reached, PreToolUse trips the circuit breaker across all terminals simultaneously. Before any worker's git worktree branch is merged back to main, an AST gate validates syntax, imports, and zero placeholder stubs deterministically.