Distributed File-Lock Arbiters for Coding Agents: Preventing Multi-Agent Overwrites with SQLite WAL and PreToolUse Hooks Benni Alencar, Chief AI Systems Architect at Benni OS, built claude-code-swarm, a distributed file-lock arbiter that prevents parallel coding agents from overwriting each other's changes in a shared working tree. The system hooks into Claude Code's PreToolUse lifecycle event and uses a local SQLite3 WAL database to enforce atomic, lease-backed locks on every mutating filesystem call in under 1 millisecond, with time-bounded leases (default 120 seconds) that self-heal after agent crashes without background reaper daemons. 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/distributed-file-lock-arbiters-coding-agents-sqlite-wal-pretooluse.html . Running a single AI coding agent is fast; running four or eight specialized subagents in parallel across a monorepo is transformative—until two agents touch the same file. In a standard shared working tree, every agent operates with an independent, stale snapshot of disk state inside its context window. Consider a classic lost-update race condition : t = 0s , src/router.py and begins reasoning over a 25-line patch. t = 1.8s , Write or Edit to add an auth guard. t = 3.1s , Asking agents to coordinate via natural language "only edit files assigned to you in the prompt" is probabilistic and breaks down immediately on shared barrel files, lockfiles, database schemas, or transitive imports. You cannot solve a concurrency hazard with prompt engineering. You need a deterministic mutual-exclusion arbiter at the tool-execution boundary. Architectural Invariant: Every mutating filesystem call Write , Edit , MultiEdit must acquire an atomic, lease-backed lock before the tool executes. Benni-OS/claude-code-swarm https://github.com/Benni-OS/claude-code-swarm enforces this in under 1 millisecond using a local SQLite3 WAL arbiter hooked directly into Claude Code's PreToolUse lifecycle event. When designing a concurrency control layer for autonomous coding agents, the first architectural decision is choosing between optimistic and pessimistic locking. PreToolUse hook fails fast < 1ms and returns a deterministic conflict error before the agent corrupts state or wastes further turns. In distributed systems, an indefinite lock is a deadlock waiting to happen. Coding agents are ephemeral processes: a subagent can hit a timeout, get killed by Ctrl+C , crash on an OOM, or trip a FinOps circuit breaker mid-task. If that agent never reaches PostToolUse or SubagentStop to release its lock, the file remains wedged forever. Every lock in claude-code-swarm is therefore a time-bounded lease default ttl seconds = 120 . Each lease stores owner session id , fencing token a monotonically increasing integer , acquired at , and expires at . Any subsequent BEGIN IMMEDIATE transaction atomically evicts expired rows WHERE expires at <= now before evaluating ownership—delivering self-healing crash recovery with zero background reaper daemons. Claude Code invokes PreToolUse synchronously via stdin JSON before executing any tool. When two parallel agents target the same canonical path, the SQLite WAL arbiter serializes their lock requests cleanly: sequenceDiagram autonumber participant A as Agent A Session 101 participant H as PreToolUse Hook participant DB as SQLite3 WAL Arbiter participant B as Agent B Session 204 A- H: Propose Edit src/router.py H- DB: BEGIN IMMEDIATE; evict expired; UPSERT lease src/router.py, owner=101, TTL=120s DB-- H: OK fencing token=42 H-- A: Exit 0 Allow Write/Edit B- H: Propose Write src/router.py H- DB: BEGIN IMMEDIATE; check owner for src/router.py DB-- H: CONFLICT held by 101, expires at now H-- B: Exit 2 + stderr "LOCK CONFLICT: held by session 101, retry in 15s" A- H: PostToolUse / SubagentStop release lease 101 H- DB: DELETE FROM file leases WHERE path='...' AND owner='101' DB-- H: Released Notice two critical properties in this flow: expires at and allows execution immediately. 2 , allowing it to pivot to an uncontested module or wait until Agent A's SubagentStop releases the lease. Naive filesystem .lock files suffer from TOCTOU Time-of-Check to Time-of-Use races and stale-file cleanup bugs across platforms. SQLite3 in Write-Ahead Logging WAL mode gives us ACID transactions, single-file zero-daemon deployment, and sub-millisecond contention handling via busy timeout . PRAGMA journal mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA busy timeout = 5000; CREATE TABLE IF NOT EXISTS file leases canonical path TEXT PRIMARY KEY, owner id TEXT NOT NULL, fencing token INTEGER NOT NULL, acquired at REAL NOT NULL, expires at REAL NOT NULL ; CREATE TABLE IF NOT EXISTS lease sequence id INTEGER PRIMARY KEY CHECK id = 1 , next token INTEGER NOT NULL DEFAULT 1 ; INSERT OR IGNORE INTO lease sequence id, next token VALUES 1, 1 ; CREATE INDEX IF NOT EXISTS idx leases expires ON file leases expires at ; Below is the core atomic arbiter used by claude-code-swarm . Every path is resolved via os.path.realpath so symlinks and relative paths ./src/../src/router.py map to the exact same lock key: python import json import os import sqlite3 import sys import time from pathlib import Path DB PATH = Path ".swarm/file leases.db" MUTATING TOOLS = {"Write", "Edit", "MultiEdit"} DEFAULT TTL SECONDS = 120.0 def init db conn: sqlite3.Connection - None: conn.execute "PRAGMA journal mode = WAL;" conn.execute "PRAGMA synchronous = NORMAL;" conn.execute "PRAGMA busy timeout = 5000;" conn.executescript """ CREATE TABLE IF NOT EXISTS file leases canonical path TEXT PRIMARY KEY, owner id TEXT NOT NULL, fencing token INTEGER NOT NULL, acquired at REAL NOT NULL, expires at REAL NOT NULL ; CREATE TABLE IF NOT EXISTS lease sequence id INTEGER PRIMARY KEY CHECK id = 1 , next token INTEGER NOT NULL DEFAULT 1 ; INSERT OR IGNORE INTO lease sequence id, next token VALUES 1, 1 ; """ def acquire lease db path: Path, target path: str, owner id: str, ttl: float = DEFAULT TTL SECONDS - tuple bool, int, str : canonical = os.path.realpath target path now = time.time expires at = now + ttl db path.parent.mkdir parents=True, exist ok=True conn = sqlite3.connect str db path , isolation level=None, timeout=5.0 try: init db conn conn.execute "BEGIN IMMEDIATE;" 1. Atomically reap expired leases self-healing crash recovery conn.execute "DELETE FROM file leases WHERE expires at <= ?;", now, 2. Check active lease holder row = conn.execute "SELECT owner id, fencing token, expires at FROM file leases WHERE canonical path = ?;", canonical, , .fetchone if row is not None and row 0 = owner id: remaining = max 0.0, row 2 - now conn.execute "ROLLBACK;" return False, row 1 , f"LOCK CONFLICT: '{canonical}' is leased by session '{row 0 }' " f" token={row 1 }, expires in {remaining:.1f}s .", 3. Mint monotonic fencing token & upsert lease token = conn.execute "UPDATE lease sequence SET next token = next token + 1 WHERE id = 1 RETURNING next token - 1;" .fetchone 0 conn.execute """ INSERT INTO file leases canonical path, owner id, fencing token, acquired at, expires at VALUES ?, ?, ?, ?, ? ON CONFLICT canonical path DO UPDATE SET owner id = excluded.owner id, fencing token = excluded.fencing token, acquired at = excluded.acquired at, expires at = excluded.expires at; """, canonical, owner id, token, now, expires at , conn.execute "COMMIT;" return True, token, f"LOCK ACQUIRED: '{canonical}' token={token} ." except Exception: conn.execute "ROLLBACK;" raise finally: conn.close def main - None: payload = json.load sys.stdin tool name = payload.get "tool name", "" if tool name not in MUTATING TOOLS: sys.exit 0 tool input = payload.get "tool input", {} file path = tool input.get "file path" or tool input.get "path" if not file path: sys.exit 0 owner id = payload.get "session id", "default-agent" acquired, , message = acquire lease DB PATH, file path, owner id if not acquired: sys.stderr.write message + "\n" sys.exit 2 sys.exit 0 if name == " main ": main Why choose SQLite3 WAL + PreToolUse over Git worktrees, Redis, or naive filesystem lockfiles? Here is how the approaches compare under parallel swarm workloads: | Arbitration Strategy | Acquisition Latency | Crash Recovery TTL | External Infra | Race-Condition Safety | |---|---|---|---|---| | Prompt-Only Coordination CLAUDE.md | 0 ms probabilistic | N/A | None | Unsafe silent overwrites on shared files | | Naive .lock Files open ..., 'x' | 0.2 – 1.5 ms | Manual / brittle mtime checks | None | Partial TOCTOU on cleanup & no fencing token | | Git Worktrees per Agent | 150 – 800 ms checkout | Process-bound | Git CLI | High isolated trees, but defers merge conflicts | | Redis Distributed Lock Redlock | 1.5 – 5.0 ms TCP/localhost | Native PX TTL | Redis daemon | High requires running & monitoring Redis | | claude-code-swarm SQLite3 WAL | 0.3 – 0.9 ms in-process | Atomic TTL eviction on BEGIN IMMEDIATE | Zero stdlib sqlite3 | ACID Serialized + Monotonic Fencing Tokens | In practice, SQLite3 WAL hits the exact engineering sweet spot for local multi-agent coding swarms: sub-millisecond lock acquisition, zero external daemons, ACID serialization across independent OS processes, and deterministic crash recovery via TTL. Deploy Benni-OS/claude-code-swarm to add atomic SQLite WAL file-lock arbitration, TTL lease recovery, and deterministic PreToolUse coordination to your parallel Claude Code workflows. Explore Benni-OS/claude-code-swarm on GitHub → Why do parallel AI coding agents silently overwrite each other's files? When multiple coding agents share a workspace, their Read-Think-Write cycles overlap. Agent A reads a file at t=0, Agent B writes a patch at t=2, and Agent A emits a full-file Write or stale Edit at t=3 based on its stale context—silently clobbering Agent B's changes without triggering any OS-level error. Why use pessimistic TTL leases instead of optimistic concurrency control for coding agents? Optimistic concurrency detects conflicts only after an agent has already burned LLM tokens and wall-clock time generating a patch. Pessimistic leases fail fast in PreToolUse before execution, while a bounded Time-To-Live TTL ensures that a crashed or SIGKILL ed agent never leaves the file permanently deadlocked. How does SQLite3 WAL guarantee atomic lock acquisition across concurrent hook processes? By enabling PRAGMA journal mode=WAL and opening transactions with BEGIN IMMEDIATE , SQLite serializes all write transactions across independent OS hook processes at the C-library level. Expired leases are evicted and new leases are inserted inside a single atomic transaction, eliminating check-then-act TOCTOU race conditions. How does Benni-OS/claude-code-swarm enforce file locks in Claude Code? claude-code-swarm registers a PreToolUse hook that intercepts Write , Edit , and MultiEdit tool calls, normalizes the target path with realpath , and queries the SQLite WAL arbiter. If another active agent holds a valid lease, the hook exits with code 2 and returns a structured stderr conflict message so the blocked agent backs off or coordinates. When multiple coding agents share a workspace, their Read-Think-Write cycles overlap. Agent A reads a file at t=0 , Agent B writes a patch at t=2 , and Agent A emits a full-file Write or stale Edit at t=3 based on its stale context—silently clobbering Agent B's changes without triggering any OS-level error. Optimistic concurrency detects conflicts only after an agent has already burned LLM tokens and wall-clock time generating a patch. Pessimistic leases fail fast in PreToolUse before execution, while a bounded Time-To-Live TTL ensures that a crashed or SIGKILL ed agent never leaves the file permanently deadlocked. By enabling PRAGMA journal mode=WAL and opening transactions with BEGIN IMMEDIATE , SQLite serializes all write transactions across independent OS hook processes at the C-library level. Expired leases are evicted and new leases are inserted inside a single atomic transaction, eliminating check-then-act TOCTOU race conditions. claude-code-swarm registers a PreToolUse hook that intercepts Write , Edit , and MultiEdit tool calls, normalizes the target path with realpath , and queries the SQLite WAL arbiter. If another active agent holds a valid lease, the hook exits with code 2 and returns a structured stderr conflict message so the blocked agent backs off or coordinates.