{"slug": "orchestrating-parallel-claude-code-swarms-without-merge-chaos-git-worktrees-file", "title": "Orchestrating Parallel Claude Code Swarms Without Merge Chaos: Git Worktrees, File Leases, and Shared MCP Blackboards", "summary": "Benni Alencar, Chief AI Systems Architect at Benni OS, released claude-code-swarm, an open-source tool that coordinates multiple parallel Claude Code agents using isolated git worktree sandboxes, SQLite3 WAL file leases enforced in PreToolUse hooks, a shared MCP task blackboard, global USD spending caps, and pre-merge AST gates. The design targets four failure modes of naive parallelism: file clobbering, .git/index.lock contention, runaway multi-terminal token bills, and merge conflicts. Blocked workers receive exit code 2 with the lease holder's ID and are redirected to another task on the blackboard.", "body_md": "*By **Benni Alencar** — Chief AI Systems Architect at [Benni OS](https://benni-os.net). Canonical article & interactive benchmarks at [benni-os.net](https://benni-os.net/blog/en/claude-code-swarm-parallel-worktrees-file-leases-mcp-blackboard.html).*\n\nEvery 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.\n\nWithin minutes, naive parallelism collapses into four predictable failure modes:\n\n`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.\n**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.\n\n```\n**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.\n```\n\nInstead 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:\n\n```\nflowchart TD\n    M[\"Shared MCP Task Blackboard<br/>(Claims, Dependencies, Contracts)\"] -->|\"Assign Task\"| W1[\"Worker 1 (git worktree: swarm/w1)\"]\n    M -->|\"Assign Task\"| W2[\"Worker 2 (git worktree: swarm/w2)\"]\n    W1 -->|\"PreToolUse (< 1ms)\"| L[\"SQLite3 WAL Coordinator<br/>File Leases + Global USD Ledger\"]\n    W2 -->|\"PreToolUse (< 1ms)\"| L\n    L -->|\"Lease Held by Peer / Cap Hit\"| X[\"Exit 2: Blocked Deterministically\"]\n    L -->|\"Lease Granted + Budget OK\"| E[\"Isolated Edit & Test in Worktree\"]\n    E -->|\"Done\"| G[\"Pre-Merge AST & Lint Gate\"]\n    G -->|\"Syntax / Stub Defect\"| E\n    G -->|\"Verified Clean\"| R[\"Atomic Fast-Forward / Rebase to main\"]\n```\n\nEach 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.\n\nWhen 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.\n\nWorktrees 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`:\n\n`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.\nEvery 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.\n\nPer-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.\n\nPassing 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.\n\nSetting up a coordinated swarm requires registering the shared MCP blackboard and binding the deterministic lease and budget hooks in `.claude/settings.json`:\n\n```\n# Install and bootstrap a 3-worker isolated git worktree swarm\npip install claude-code-swarm\nclaude-swarm init --workers 3 --max-swarm-usd 6.00 --lease-ttl 300\n\n# Register the shared MCP Task Blackboard\nclaude mcp add swarm-blackboard -- claude-swarm mcp-serve\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Edit|Write|MultiEdit|Bash\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"claude-swarm hook pre-tool-use\",\n            \"timeout\": 2000\n          }\n        ]\n      }\n    ],\n    \"PostToolUse\": [\n      {\n        \"matcher\": \"*\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"claude-swarm hook post-tool-use\",\n            \"timeout\": 2000\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\nBelow 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:\n\n``` python\nimport json\nimport sqlite3\nimport sys\nimport time\nfrom pathlib import Path\n\nDB_PATH = Path(\".swarm/coordinator.db\")\n\ndef enforce_lease_and_budget(\n    worker_id: str,\n    target_path: str | None,\n    max_swarm_usd: float = 6.00,\n    ttl_sec: int = 300,\n) -> tuple[int, str]:\n    now = time.time()\n    conn = sqlite3.connect(DB_PATH, timeout=5.0, isolation_level=None)\n    conn.execute(\"PRAGMA journal_mode=WAL;\")\n    try:\n        conn.execute(\"BEGIN IMMEDIATE;\")\n\n        # 1. Global Swarm FinOps Circuit Breaker\n        row = conn.execute(\"SELECT COALESCE(SUM(cost_usd), 0.0) FROM spend_ledger\").fetchone()\n        total_usd = float(row[0])\n        if total_usd >= max_swarm_usd:\n            conn.execute(\"ROLLBACK;\")\n            return 2, f\"SWARM_BUDGET_CAP: Global spend ${total_usd:.4f} >= cap ${max_swarm_usd:.2f}.\"\n\n        # 2. Atomic File Lease Check (if tool mutates a path)\n        if target_path:\n            conn.execute(\"DELETE FROM file_leases WHERE expires_at < ?\", (now,))\n            holder = conn.execute(\n                \"SELECT worker_id FROM file_leases WHERE file_path = ?\",\n                (target_path,),\n            ).fetchone()\n\n            if holder and holder[0] != worker_id:\n                conn.execute(\"ROLLBACK;\")\n                return 2, (\n                    f\"FILE_LEASE_CONFLICT: '{target_path}' is leased by '{holder[0]}'. \"\n                    \"Claim another task on the MCP blackboard.\"\n                )\n\n            conn.execute(\n                \"\"\"\n                INSERT INTO file_leases (file_path, worker_id, expires_at)\n                VALUES (?, ?, ?)\n                ON CONFLICT(file_path) DO UPDATE SET\n                    worker_id = excluded.worker_id,\n                    expires_at = excluded.expires_at\n                \"\"\",\n                (target_path, worker_id, now + ttl_sec),\n            )\n\n        conn.execute(\"COMMIT;\")\n        return 0, json.dumps({\"decision\": \"allow\", \"worker_id\": worker_id, \"global_usd\": total_usd})\n    finally:\n        conn.close()\n\nif __name__ == \"__main__\":\n    payload = json.load(sys.stdin)\n    worker = payload.get(\"worker_id\", \"worker-1\")\n    file_path = payload.get(\"tool_input\", {}).get(\"file_path\")\n    code, msg = enforce_lease_and_budget(worker, file_path)\n    if code != 0:\n        sys.stderr.write(msg + \"\\n\")\n    sys.exit(code)\n```\n\n| Orchestration Dimension | Uncoordinated Parallel Terminals | `Benni-OS/claude-code-swarm` | \n|---|---|---|\n| **Filesystem Isolation** | Shared working tree (silent overwrites & index locks) | **Dedicated `git worktree` & branch per worker** | \n| **Concurrent File Edits** | Race conditions & three-way merge chaos | **Atomic SQLite3 WAL File Leases in `PreToolUse`** | \n| **Task & Contract Sharing** | Manual copy-paste or duplicated work | **Shared MCP Task Blackboard with atomic claims** | \n| **Multi-Terminal Spend Control** | No global visibility; *N* × runaway loops | **Global Swarm USD Cap across all workers** | \n| **Merge Quality Gate** | Manual conflict resolution & broken stubs | **Deterministic Pre-Merge AST & Lint Gate** | \n\nDeploy **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.\n\n```\n    Explore Benni-OS/claude-code-swarm on GitHub →\nWhy do parallel Claude Code terminals overwrite each other's files?\n      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.\n\n  How do SQLite3 WAL file leases in PreToolUse prevent edit collisions?\n  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.\n\n  What role does the shared MCP task blackboard play?\n  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.\n\n  How do global swarm USD caps and pre-merge AST gates protect production?\n  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.\n```\n\nWhen 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.\n\nEven 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.\n\nThe 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.\n\nEvery 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.", "url": "https://wpnews.pro/news/orchestrating-parallel-claude-code-swarms-without-merge-chaos-git-worktrees-file", "canonical_source": "https://dev.to/bennialencar/orchestrating-parallel-claude-code-swarms-without-merge-chaos-git-worktrees-file-leases-and-29g3", "published_at": "2026-11-23 22:39:34+00:00", "updated_at": "2026-11-23 22:43:09.092409+00:00", "lang": "en", "topics": ["ai-agents", "developer-tools", "ai-tools", "agent-protocols", "mlops"], "entities": ["Benni Alencar", "Benni OS", "Claude Code", "claude-code-swarm", "Anthropic", "SQLite3", "MCP"], "also_reported_by": [], "takeaway": "Isolate each parallel coding agent in its own git worktree and gate every Edit/Write/Bash call through a SQLite3 WAL lease check in PreToolUse, returning exit 2 with the holder's ID so blocked workers pick another task instead of creating merge conflicts.", "recommendation": {"advice": "Give each parallel coding agent its own git worktree and enforce file leases plus a shared USD ledger in PreToolUse hooks so conflicting edits are blocked deterministically before they run.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/orchestrating-parallel-claude-code-swarms-without-merge-chaos-git-worktrees-file", "markdown": "https://wpnews.pro/news/orchestrating-parallel-claude-code-swarms-without-merge-chaos-git-worktrees-file.md", "text": "https://wpnews.pro/news/orchestrating-parallel-claude-code-swarms-without-merge-chaos-git-worktrees-file.txt", "jsonld": "https://wpnews.pro/news/orchestrating-parallel-claude-code-swarms-without-merge-chaos-git-worktrees-file.jsonld"}}