AI Wikis / Agentic Web

Formal Coordination Protocol for Concurrent Multi-Agent Codebase Editing

Report summary

The integration of multiple autonomous Artificial Intelligence (AI) agents operating concurrently within a single source repository introduces profound distributed systems challenges. Historically, AI agent environments have been designed as isolated, single-threaded feedback loops where an LLM agen

Status
Research archive item
Category
AI Wikis / Agentic Web
Length
5,207 words
Reading time
24 minutes
Report type
guidance

Key topics

  • AI Wikis / Agentic Web
  • AI Wikis
  • Agentic Web
  • AI
  • .NET
  • SQL
  • Runtime
  • Semantic Systems
  • Research Archive

Research provenance

Archive status
Research archive item
Content identity
sha256:47a85e848246c789182fcac72ecd7b30490ef3a84d1929d9d27583e808dce617

For citation, use the report title and canonical URL. Archival presence does not establish authorship or promote report statements into portfolio evidence.

This page renders the archived Markdown as safe, formatted HTML. It is background research and does not become a portfolio claim without evidence review.

Full report

On this page

The integration of multiple autonomous Artificial Intelligence (AI) agents operating concurrently within a single source repository introduces profound distributed systems challenges. Historically, AI agent environments have been designed as isolated, single-threaded feedback loops where an LLM agent holds exclusive domain over the context window, the filesystem, and the active-memory state. However, as multi-agent frameworks evolve to support sophisticated software engineering workloads, orchestrating concurrent agents within a shared codebase becomes a necessity. When isolated agents attempt to modify overlapping logic, shared dependencies, and collective active memory without a rigorous coordination substrate, the inevitable result is a fragmented and corrupted system state1. Traditional memory paradigms, such as utilizing a static, flat Markdown or JSON file (e.g., MEMORY.md or .cursorrules), catastrophically fail under concurrent load. These implementations typically rely on naive read-modify-write cycles without concurrency control, leading to silent overwrites, truncation of historical context, and severe write-write conflicts3. Similarly, codebase manipulation relies on Git, a version control system optimized for asynchronous human collaboration, not synchronous, high-speed agentic execution5. Without architectural intervention, two agents might implement conflicting utility functions, inadvertently overwrite each other's active-memory findings, or endlessly race to push commits to a remote repository, resulting in non-fast-forward rejections and logical deadlocks6. This report defines an exhaustive coordination protocol and architectural model to mediate multi-agent concurrent operations. By coupling a highly available Hosted Coordination Service (HCS) with local Git worktree isolation and mathematically convergent data structures for active memory, the proposed architecture guarantees deterministic reconciliation. The solution preserves local agent autonomy, enforces cryptographic evidence of completion prior to the release of system leases, and explicitly avoids brittle one-off lock files or informal "do not touch this" messages.

Comparative Analysis of Concurrency Techniques

To architect a resilient multi-agent system, underlying concurrency mechanisms must be evaluated against the unique behaviors of LLM agents, which exhibit long-running transactions, non-deterministic latency, and complex semantic overlap. The evaluation encompasses source control strategies, distributed coordination locking, and data consistency models.

TechniquePrimary MechanismAppropriate ApplicationUnnecessary Complexity / Drawbacks
Git WorktreesIsolates working directories while sharing the .git database.Parallel agent execution, isolated builds, preventing port collisions8.Does not prevent logical code collisions or semantic overlap between agents.
Branch IsolationIsolates commits on separate divergent paths.Tracking independent features prior to a formalized merge review.Pushes conflict resolution to the merge phase, which is notoriously difficult for LLMs to resolve post-hoc.
File Ownership DeclarationsStatically assigns directories/files to specific agents.Highly modular codebases with strict domain-driven design boundaries.Too rigid for modern frameworks where concerns (e.g., authentication, logging) cross-cut modules.
Edit-Intent RecordsBroadcasts semantic goals before acting to discover overlap.Dynamic negotiation of scope in complex, entangled codebases.Requires a semantic matching engine (vector database) to calculate intent similarity.
Leases with HeartbeatsGrants coarse-grained, time-bound locks requiring periodic renewal.Managing agent lifecycles, preventing deadlocks when agents hang10.Overhead of maintaining heartbeat infrastructure and managing TTL expirations.
Optimistic Concurrency (OCC)Executes freely, validating for conflicts only at commit time.Low-contention environments; Git server-side push validation12.Causes cascading retries and wasted inference cost under high contention14.
Compare-and-Swap (CAS)Atomic updates conditional on an expected previous state.Updating explicit database rows, such as lease TTL increments.Too granular and rigid for coordinating broad, semantic code changes.
Append-Only EventsImmutable logs of state changes.Episodic memory, audit trails, and deterministic replay16.Requires periodic compaction to prevent unbounded context window growth2.
Vector ClocksTracks causal history of events across distributed nodes.Detecting causality and concurrent mutations in partitioned networks18.Merely detects conflicts without resolving them; increases payload size20.
CRDTsData structures guaranteeing mathematical convergence.Shared semantic memory, real-time configuration merging22.High implementation complexity; requires adapting standard data types to CRDT equivalents.
Patch QueuesSerializes all operations into a sequential queue.Absolute safety in legacy systems with zero concurrency tolerance.Destroys the throughput benefits of multi-agent parallelism.
Human ArbitrationEscapes to a human operator to resolve deadlocks.Emergency Byzantine failures, catastrophic outages, or security overrides.Breaks agentic autonomy; unacceptable for the critical path of normal execution.

Source Control and Environmental Isolation

The foundation of concurrent agent operation requires environmental isolation. Traditional Git workflows utilize a single working directory, necessitating the stash or commit of changes before switching branches. For autonomous agents, this single working directory becomes an immediate bottleneck, resulting in the corruption of build artifacts and index.lock collisions25. Git worktrees provide the optimal solution by creating separate working directories that share the identical underlying .git object database27. This permits agents to operate in true parallel isolation, each maintaining its own HEAD pointer, index, and untracked files28. When combined with the extensions.worktreeConfig setting, the architecture can persist per-worktree metadata—such as the parent branch reference—without polluting the global Git configuration30. While worktrees solve the physical filesystem overlap and prevent agents from contaminating each other's compilation caches8, they do not solve the logical coordination problem. Two agents operating in separate worktrees can successfully write logically contradictory code, such as two incompatible implementations of a utility function, which will eventually collide during the merge phase7. Therefore, Git worktrees are necessary for physical isolation but entirely insufficient for semantic coordination.

Distributed Coordination and Locking Mechanisms

To bridge the gap between physical isolation and logical coordination, the system must employ distributed locking mechanisms. However, indefinite file locks (pessimistic locking) are inherently dangerous in multi-agent systems. If an agent crashes, experiences an out-of-memory error, or is evicted by the orchestration layer, a static lock results in a permanent deadlock, requiring human intervention. The architecture must instead utilize Leases with Heartbeats, a paradigm pioneered by distributed systems such as Google's Chubby10. A lease grants a coarse-grained lock bound by a Time-To-Live (TTL). The agent must periodically send a heartbeat to the coordinator to renew the lease32. If the heartbeat ceases, the coordinator automatically expires the lease, returning the semantic space to the available pool. This provides fault tolerance against agent disappearance. To determine what to lock, the protocol rejects static File Ownership Declarations. Modern software architecture rarely confines features to singular directories; implementing a new route often requires touching UI components, backend controllers, and database schemas simultaneously. Instead, the protocol relies on Edit-Intent Records. An agent broadcasts a semantic description of its intended modifications. This allows the coordination service to dynamically detect overlap based on the meaning of the work, rather than enforcing rigid, brittle directory monopolies.

Data Consistency Models

The integration of changes across concurrent agents requires a nuanced application of concurrency control. Optimistic Concurrency Control (OCC), first formalized by Kung and Robinson, assumes that conflicts are rare13. Transactions execute against a local copy and only check for conflicts during a final validation phase34. If a conflict exists, the transaction is aborted and retried. Git inherently uses OCC during the push operation; the server attempts an atomic Compare-and-Swap (CAS) on the branch reference, rejecting the push if the reference has moved since the client's last fetch25. OCC is exceptionally efficient for source code commits where contention on specific lines is low, but it is disastrous for highly contended shared resources, where it causes cascading retries and massive inference waste14. For local active-memory files, which are highly contended by all operating agents, OCC is inadequate. Vector clocks offer a method to track causality and detect concurrent edits in distributed systems without synchronized clocks18. While vector clocks accurately detect conflicts by comparing causal histories, they push the resolution burden back to the application logic20. To achieve true autonomy and seamless memory merging, the protocol must utilize Conflict-Free Replicated Data Types (CRDTs). CRDTs are specialized data structures that provide Strong Eventual Consistency (SEC)22. They mathematically guarantee that any two nodes receiving the same set of updates will converge to the exact same state, completely eliminating the need for synchronous consensus or lock acquisition16. By representing the shared active memory as a composition of Last-Writer-Wins (LWW) Registers and Observed-Remove Sets (OR-Sets), agents can concurrently mutate memory states with the absolute guarantee that the Hosted Coordination Service will deterministically merge the divergent states23.

Protocol Architecture and Semantic Negotiation

The recommended architecture establishes a hybrid substrate. The control plane is governed by a Hosted Coordination Service (HCS), while the data plane relies on Git Worktrees and a Local Memory Daemon residing on the host machine. The HCS acts as the central arbiter, maintaining a highly available relational database for lease state management and a vector database for semantic intent matching. To augment local active memory without migrating all memory files to the cloud, the Local Memory Daemon intercepts all agent memory operations, translates them into CRDT vectors, and asynchronously synchronizes with the HCS. To prevent overlap, agents operate under a strict semantic discovery and negotiation protocol.

The Claim Announcement

Prior to initiating any edits within the codebase, an agent must construct and submit a ClaimIntent to the HCS. This intent is not a blind request for a lock; it is a comprehensive broadcast of the agent's operational parameters. The HCS requires the following structured payload:

FieldData TypeOperational Description
objectiveStringA dense semantic description of the goal (e.g., "Implement retry backoff in the Redis client").
working\_pathStringThe root directory of the isolated Git worktree where execution will occur.
intended\_filesArray\[Glob\]Explicit file paths or module globs the agent intends to mutate.
expected\_contractsArray\[String\]Declared changes to shared interfaces, API schemas, or database models.
test\_responsibilityEnumThe scope of testing the agent commits to passing prior to completion (e.g., UNIT\_AND\_E2E).
lease\_duration\_msIntegerThe requested TTL for the lease before a heartbeat renewal is required.

Semantic Discovery and the Meeting Room

Upon receipt of the ClaimIntent, the HCS initiates the discovery phase. Traditional systems check for file lock collisions using exact string matching. However, logical conflicts often span disparate files. The HCS utilizes a dual-layered detection mechanism. First, it checks for strict lexical overlap within the intended\_files globs. Second, it encodes the objective and expected\_contracts into high-dimensional vector embeddings and performs a cosine similarity search against the vector space of all currently active claims1. If the cosine similarity score exceeds a strict heuristic threshold, or if lexical file paths intersect, the HCS flags a collision. The HCS does not simply reject the claim; it places the incoming agent and the existing leaseholder into a "Meeting Room" state. The Meeting Room is an automated, coordinator-mediated negotiation sub-protocol. The HCS injects the active leaseholder's objective and intended files into the incoming agent's context window. The agents communicate to delineate a boundary. For instance, if Agent A is refactoring the auth.ts middleware, and Agent B is tasked with updating the auth.ts token issuance logic, they will negotiate an architectural interface. Agent A may agree to stub a specific interface that Agent B will implement. Once the agents reach consensus, they submit a jointly signed NegotiationResult to the HCS. The HCS updates both claims, narrowing their respective intended\_files arrays to enforce mutual exclusivity, and grants the lease.

Lease Lifecycle and Semantics

A lease in this protocol does not silently grant the authority to overwrite arbitrary work. It grants the cryptographic authority to attempt a merge against the parent branch within the negotiated boundaries. The lease lifecycle is strictly governed by the HCS state machine.

  • Renewal: A lease remains ACTIVE strictly contingent upon the receipt of heartbeats. The agent's Local Memory Daemon must emit a heartbeat every [Figure omitted from source export] milliseconds, where [Figure omitted from source export] is the lease\_duration\_ms. The HCS processes this heartbeat using an OCC Compare-and-Swap operation on the database record to safely increment the expiration timestamp, preventing race conditions during concurrent renewal attempts14.
  • Expiration: Should an agent process crash, hang in an infinite reasoning loop, or lose network connectivity, the heartbeats will cease. Once the current timestamp surpasses the lease's expires\_at value, the HCS autonomously transitions the claim to EXPIRED. A WebSocket event is broadcast to the swarm, notifying all peers that the semantic space is available. The orphaned worktree is untracked by the HCS, and a local garbage collection process will eventually prune it using git worktree prune9.
  • Abandonment: If an agent encounters an insurmountable architectural blocker or realizes the objective is malformed, it can proactively invoke the abandonment endpoint. The lease transitions to ABANDONED, immediately releasing the semantic space without waiting for the TTL to expire.
  • Split Ownership and Handoff: Complex refactoring tasks often reveal the need for specialized assistance. An agent may realize a subset of its objective requires a database migration expert. The agent can invoke a SPLIT operation, delegating a subset of its intended\_files to a new child claim, or it can execute a complete HANDOFF, cryptographically transferring the lease token to a peer agent.
  • Emergency Takeover: In circumstances requiring human intervention—such as an ongoing production incident where critical files are locked by a background agent—a human operator can issue a REVOKE command. The HCS immediately terminates the lease, broadcasts a cancellation signal to the agent's daemon, and forces the agent to abort its execution loop, returning control of the codebase to the human.

Local Active-Memory Rules and Synchronization

Agent memory persistence is a critical requirement for long-horizon autonomous operation. Memory allows agents to learn operational preferences, repository quirks, and historical architectural decisions41. Traditional implementations treat memory as passive storage, appending facts to a flat MEMORY.md file4. When multiple agents write to this file simultaneously, the resulting race conditions lead to silent data loss, duplicate entries, and corrupted context windows3. To preserve local autonomy while ensuring seamless multi-agent coordination, the architecture bifurcates active memory into two distinct operational paradigms managed by the Local Memory Daemon.

Append-Only Coordination Events (Episodic Memory)

Temporal and sequential facts—such as "Attempted to use library X, but it failed due to version mismatch"—are classified as Episodic Memory. These entries are written as immutable, append-only records to a local event log2. Because the log is append-only, write-write conflicts are mathematically impossible; the histories from multiple agents simply interleave. To maintain causal ordering across the distributed swarm, the daemon attaches a vector clock to each event before syncing it with the HCS18. The HCS acts as the canonical event store, allowing any agent to query the chronological history of the codebase without risking mutation conflicts.

CRDT-Mediated Structural State (Semantic Memory)

Structured data, such as environment configurations, user preferences, and dynamic codebase maps, are managed as Semantic Memory. Implementing OCC or pessimistic locking for Semantic Memory would introduce unacceptable latency and block agent execution during network partitions36. Instead, the Local Memory Daemon implements these structures as Conflict-Free Replicated Data Types (CRDTs)22. Specifically, key-value configurations utilize a Last-Writer-Wins Element Set (LWW-Element-Set), while lists of guidelines utilize an Observed-Remove Set (OR-Set)22. The agent interacts with a simple JSON API exposed by the local daemon. The daemon converts these interactions into CRDT operations. Even if the HCS is temporarily unreachable, the agent retains complete local autonomy, continuing to read and write memory operations. The mathematics of CRDTs guarantee that once network connectivity is restored, the local daemon and the HCS will deterministically converge to the exact same state, natively resolving concurrent edits from multiple agents23.

Section-Owned Configuration Reconciliations

While the underlying memory state is a mathematical CRDT graph, humans require readable files (e.g., .cursorrules or CLAUDE.md). To facilitate human oversight without discarding user edits, the system employs a section-owned, generated-from-canonical-events approach. The .cursorrules file is dynamically generated by the daemon from the CRDT state. The file is divided into strictly demarcated sections using distinct Markdown headers. If a human user manually edits a section of the Markdown file, a filesystem watcher within the daemon detects the change. The daemon parses the manual edit, assigns it an artificially high logical timestamp, and injects it into the CRDT graph as a new operation44. Because of the high timestamp, the LWW algorithms prioritize the human's edit, propagating the change back to the HCS and overriding any conflicting agent-generated memories22. This ensures human instructions remain authoritative while preventing agents from continuously overwriting each other.

Evidence Requirements for Completion

An agent cannot arbitrarily declare its objective complete and release its lease. Doing so risks leaving the repository in a broken state, resulting in broken builds and corrupted logic. The protocol enforces a rigorous "Proof of Work" validation phase before the HCS accepts the completion and initiates the merge. When an agent invokes the CompleteClaim endpoint, it must provide a structured payload containing cryptographic and operational evidence. If any of the required evidence is missing or invalid, the HCS rejects the completion, forcing the agent to resolve the deficiencies before its lease expires.

Evidence RequirementValidation Mechanism by the Hosted Coordination Service
Changed Files ArrayThe HCS strictly verifies that the submitted list of modified files intersects perfectly with the intended\_files boundary negotiated during the claim phase. Unauthorized file mutations result in immediate rejection.
Commit IdentityThe agent must supply the Git SHA-1 hash of the finalized commit. The HCS queries the Git remote to verify the commit has been successfully pushed and exists in the object database.
Test Execution StatusThe agent provides a cryptographic signature or a CI/CD webhook ID proving that tests corresponding to the test\_responsibility domain have passed successfully against the specific Commit Identity.
API/Schema DeltasIf expected\_contracts were declared, the agent must attach the generated AST diff or the OpenAPI specification delta, proving the contract was modified as intended.
Migration FilesIf database models were touched, the payload must include proof of corresponding, non-destructive UP and DOWN SQL migration files.
Deployment Status(Optional) If the agent is responsible for continuous deployment, it must provide the target environment status and health check verification.
Unresolved RisksA structured string identifying any technical debt, edge cases, or bypassed logic. The HCS automatically appends this string to the shared Semantic Memory CRDT, ensuring subsequent agents are aware of the deferred work.

Edge Cases and Failure Scenarios

Distributed multi-agent systems are defined by their resilience in the face of aberrant conditions. The coordination protocol utilizes strict deterministic state management to recover from race conditions and data corruption.

Two Agents Racing to Commit

If two agents operating in independent Git worktrees complete their tasks simultaneously, they may both attempt to push their commits to the same remote parent branch at the exact same millisecond. The Git server-side architecture inherently mitigates this via Optimistic Concurrency Control25. During a push, the Git server attempts an atomic CAS operation on the reference file (e.g., refs/heads/main). It locks the reference (via .git/refs/heads/main.lock), verifies the old SHA matches the client's expected SHA, writes the new SHA, and unlocks6. The first agent's push succeeds. The second agent's push is rejected with a non-fast-forward error. The agent's Local Memory Daemon intercepts this failure. It automatically issues a git pull \--rebase to fetch the first agent's commit, applies the second agent's changes on top of the new HEAD, and instructs the LLM to resolve any semantic merge conflicts using its context window. The agent must then re-run its test suite to generate new completion evidence before successfully re-attempting the push26.

Deploying Stale Code

If an agent initiates a deployment based on a stale HEAD, it risks regressing the application by overwriting newer code. To prevent this, the deployment pipeline is integrated directly with the HCS. The agent passes its target commit SHA to the pipeline. The pipeline queries the HCS to verify that no overlapping claims have transitioned to COMPLETED since that SHA was generated. If a newer, overlapping commit exists, the deployment is aborted, and the agent is instructed to rebase and re-validate.

Generated Files Appearing Dirty

Agents frequently trigger build tools (e.g., Webpack, tsc) or package managers that generate massive artifact directories and modify absolute paths in lockfiles (e.g., package-lock.json). Because each agent operates in a unique Git worktree path, these tools generate divergent, path-specific artifacts that cause unintended Git diffs and severe merge conflicts9. To neutralize this, the protocol enforces the use of Git Smudge and Clean Filters47. By configuring the .gitattributes file, any files prone to local absolute path pollution or deterministic generation timestamps are passed through a clean script during git add. The script strips local ephemeral data, replacing absolute worktree paths with a canonical placeholder (e.g., \_\_AGENT\_ID\_PLACEHOLDER\_\_). When the file is checked out, the smudge script restores the local path47. This ensures the Git index remains pristine, preventing generated artifacts from dirtying the tree and colliding during merges.

Protocol State Machine and Database Model

To orchestrate the complex lifecycles of leases and semantic memory, the Hosted Coordination Service requires a resilient internal state machine and a strictly normalized database schema.

Database Schema Model

The HCS is backed by a PostgreSQL database utilizing the pgvector extension for high-dimensional semantic search.

SQL CREATE TABLE claims ( claim\_id UUID PRIMARY KEY, agent\_id VARCHAR(255) NOT NULL, objective TEXT NOT NULL, objective\_embedding VECTOR(1536), \-- Utilized for semantic overlap detection via cosine similarity working\_path VARCHAR(512), test\_responsibility VARCHAR(50), status VARCHAR(20) NOT NULL, \-- PENDING, NEGOTIATING, ACTIVE, EXPIRED, ABANDONED, COMPLETED created\_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), expires\_at TIMESTAMP WITH TIME ZONE, version\_id BIGINT DEFAULT 1 \-- Utilized for OCC CAS lease updates );

CREATE TABLE claim\_files ( claim\_id UUID REFERENCES claims(claim\_id), file\_glob VARCHAR(512) NOT NULL, PRIMARY KEY (claim\_id, file\_glob) );

CREATE TABLE active\_memory\_crdt ( entity\_key VARCHAR(255) PRIMARY KEY, crdt\_payload BYTEA NOT NULL, vector\_clock JSONB NOT NULL, last\_modified TIMESTAMP WITH TIME ZONE DEFAULT NOW() );

Protocol State Transitions

The lifecycle of a claim is strictly governed by the following state transitions:

  1. NULL [Figure omitted from source export] PENDING: An agent submits a ClaimIntent.
  2. PENDING [Figure omitted from source export] ACTIVE: The HCS vector search detects no overlap; a lease is granted.
  3. PENDING [Figure omitted from source export] NEGOTIATING: Overlap is detected; agents are moved to the Meeting Room.
  4. NEGOTIATING [Figure omitted from source export] ACTIVE: Agents submit a signed NegotiationResult, resolving boundaries.
  5. ACTIVE [Figure omitted from source export] ACTIVE: A heartbeat is received; the TTL is extended via CAS.
  6. ACTIVE [Figure omitted from source export] EXPIRED: The TTL is exceeded without a heartbeat; the lease is revoked.
  7. ACTIVE [Figure omitted from source export] ABANDONED: The agent voluntarily yields the lease.
  8. ACTIVE [Figure omitted from source export] COMPLETED: The agent submits valid cryptographic evidence of work.

Endpoint Examples

1\. Announce Claim Intent

HTTP POST /api/v1/claims Content-Type: application/json

{ "agent\_id": "agent-auth-refactor-01", "objective": "Migrate login route to utilize JWT middleware", "intended\_files": \["src/routes/auth.ts", "src/middleware/jwt.ts"\], "test\_responsibility": "UNIT\_AND\_E2E", "lease\_duration\_ms": 300000 }

2\. Heartbeat (Lease Renewal via CAS)

HTTP PUT /api/v1/claims/{claim\_id}/heartbeat Content-Type: application/json

{ "agent\_id": "agent-auth-refactor-01", "expected\_version\_id": 4, "additional\_ttl\_ms": 150000 }

3\. Submit Evidence and Complete

HTTP POST /api/v1/claims/{claim\_id}/complete Content-Type: application/json

{ "commit\_sha": "a1b2c3d4e5f6g7h8i9j0", "changed\_files": \["src/routes/auth.ts"\], "test\_signature": "ci-run-849201", "unresolved\_risks": "JWT expiration refresh logic needs separate handling." }

Security Model and User Experience

Security Architecture

The HCS operates on a strict Zero-Trust model. Agents authenticate via short-lived JSON Web Tokens (JWTs) issued by the orchestration layer. To prevent malicious or buggy agents from monopolizing resources, the HCS relies on OCC (via the version\_id column) to ensure that all lease updates, handoffs, and completions are strictly serialized. This prevents two agents from exploiting API race conditions to concurrently hijack a semantic space36. For memory operations, the HCS cryptographically validates the CRDT state vector, ensuring that malformed payloads cannot corrupt the global mathematical graph of the active memory.

UX for Agents

For the AI agent, the complexities of vector clocks, CRDTs, and OCC are entirely abstracted. The protocol is exposed to the LLM via simple, well-documented callable tools (e.g., function calling). The agent simply invokes memory.remember("key", "value") or coordinator.claim("description", \["files"\]). The Local Memory Daemon handles the network back-off logic, CRDT translations, and Git worktree initializations53. If the HCS returns a 409 Conflict during a claim attempt, the daemon automatically injects the conflicting agent's context and chat history into the tool response. This allows the LLM to seamlessly understand the dispute and dynamically formulate a negotiation strategy without breaking its reasoning loop.

UX for Humans

For human developers overseeing the swarm, transparency is paramount. The system provides a centralized dashboard overlaying active claims onto a visual dependency graph of the codebase. Humans can monitor in real-time which agents are mutating which modules. The notification subsystem, utilizing Server-Sent Events (SSE), pushes real-time alerts to the dashboard when claims transition states. If an agent loops endlessly or modifies restricted files, the human operator can click a "Revoke Lease" button, executing the emergency takeover protocol. Active memory states, while stored mathematically as CRDTs, are continuously translated and rendered into readable Markdown or JSON on the dashboard, ensuring humans can audit the swarm's accumulated knowledge at any time.

Deterministic Integration Tests

To ensure the resilience of the coordination protocol, the implementation must be validated against a strict matrix of deterministic integration tests simulating catastrophic failures and extreme concurrency.

  1. The Simultaneous Claim Test: Fire 50 concurrent ClaimIntent requests for the exact same intended\_files from 50 mocked agents at the exact same millisecond.
  • Assertion: The database transaction isolation ensures exactly 1 agent receives a 201 Created (ACTIVE), and 49 agents receive a 409 Conflict (NEGOTIATING).
  1. The Silent Death Test: Grant a lease with a 5-second TTL. Terminate the mock agent process abruptly, simulating a kernel Out-Of-Memory (OOM) kill.
  • Assertion: At exactly [Figure omitted from source export] seconds, the HCS automatically transitions the claim to EXPIRED and allows a queued agent to claim the space.
  1. The Network Partition CRDT Sync Test: Partition the network of Agent A. Have Agent A write to the memory key auth\_config via the local memory daemon. Concurrently, have Agent B write to the same key on the HCS. Restore the network partition.
  • Assertion: The CRDT merge algorithm deterministically resolves the conflict without throwing an error. Both Agent A and the HCS reflect identical internal states, strictly adhering to LWW timestamp rules.
  1. The Incomplete Evidence Test: Have an agent submit a CompleteClaim request where the changed\_files list contains a file outside its negotiated boundaries.
  • Assertion: The HCS rejects the request with a 400 Bad Request. The lease remains ACTIVE until the agent either reverts the unauthorized change or renegotiates the boundary.
  1. The Git Push Race Test: Provision two agents in separate Git worktrees. Both create a local commit targeting main. Both attempt to push simultaneously.
  • Assertion: One push succeeds. The other fails with a Git non-fast-forward error. The daemon automatically intercepts the error, issues a git pull \--rebase, and successfully pushes the resolved commit on the second attempt.

The deployment of this protocol transforms a chaotic, race-condition-prone multi-agent environment into a deterministic, mathematically convergent system capable of safely executing massive, concurrent software engineering workloads.

Works cited

  1. Building persistent memory for multi-agent AI systems with Amazon S3 Vectors \- AWS, https://aws.amazon.com/blogs/storage/building-persistent-memory-for-multi-agent-ai-systems-with-amazon-s3-vectors/
  2. Agent Memory Wars: Why Your Multi-Agent System Forgets What Matters (And How to Fix It), https://medium.com/@nraman.n6/agent-memory-wars-why-your-multi-agent-system-forgets-what-matters-and-how-to-fix-it-a9a1901df0d9
  3. Auto memory file is not safe for concurrent agent teams \#24130 \- GitHub, https://github.com/anthropics/claude-code/issues/24130
  4. Your AI Agent's Memory Is Just a File? That's the Problem, https://mem0.ai/blog/your-ai-agents-memory-is-just-a-file-thats-the-problem
  5. GitOfThoughts: Version-Controlled Reasoning and Agent Memory You Can Replay, Diff, and Merge \- arXiv, https://arxiv.org/html/2606.14470v2
  6. What would happen if a git server receives push from 2 users at the same time? \- Reddit, https://www.reddit.com/r/git/comments/1n023do/what\_would\_happen\_if\_a\_git\_server\_receives\_push/
  7. Parallel agents \+ git worktrees: real-world experience? : r/cursor \- Reddit, https://www.reddit.com/r/cursor/comments/1rxg2b7/parallel\_agents\_git\_worktrees\_realworld\_experience/
  8. Git Worktrees for Parallel Development: 3x Throughput with AI Agents \- James Phoenix, https://understandingdata.com/posts/git-worktrees-parallel-dev/
  9. Git Worktree Conflicts with Multiple AI Agents: Diagnosis and Fixes | Termdock, https://www.termdock.com/en/blog/git-worktree-conflicts-ai-agents
  10. Chubby Lock Service for Distributed Systems PowerPoint Presentation \- SlideServe, https://www.slideserve.com/jbasil/chubby-powerpoint-ppt-presentation
  11. The Chubby lock service for loosely-coupled distributed systems \- Google Research, https://research.google.com/archive/chubby-osdi06.pdf
  12. Pessimistic vs Optimistic Locking \- ByteByteGo, https://bytebytego.com/guides/pessimistic-vs-optimistic-locking/
  13. On Optimistic Methods for Concurrency Control \- Computer Science, https://www.eecs.harvard.edu/\~htk/publication/1981-tods-kung-robinson.pdf
  14. Optimistic vs Pessimistic Concurrency Control \- Cracking Walnuts, https://crackingwalnuts.com/concurrency/optimistic-vs-pessimistic-locking
  15. Optimistic concurrency control \- Wikipedia, https://en.wikipedia.org/wiki/Optimistic\_concurrency\_control
  16. Log-Structured Conflict-Free Replicated Data Types \- UCSB Computer Science \- University of California, Santa Barbara, https://cs.ucsb.edu/sites/default/files/documents/paper\_9.pdf
  17. Shared Memory for Multi-Agent Systems \- VECTOR Labs | AI, https://vector-labs.ai/insights/why-shared-memory-is-the-unsolved-infrastructure-problem-blocking-your-multi-agent-deployments
  18. How to Create Vector Clocks \- OneUptime, https://oneuptime.com/blog/post/2026-01-30-vector-clocks/view
  19. Vector Clocks in Distributed Systems \- GeeksforGeeks, https://www.geeksforgeeks.org/computer-networks/vector-clocks-in-distributed-systems/
  20. How Vector Clocks Work in Distributed Systems \- DEV Community, https://dev.to/rajat10/how-vector-clocks-work-in-distributed-systems-5b4j
  21. Vector clock. The Fundamental Challenge | by Saahid \- Medium, https://medium.com/@saahid/vector-clock-ce420e7910e2
  22. Conflict-Free Replicated Data Types (basic entry), https://www.lip6.fr/Marc.Shapiro/papers/2016/replicated-data-types-Encyclopedia-DB-systems-2016-authorversion.pdf
  23. Conflict-free replicated data type \- Wikipedia, https://en.wikipedia.org/wiki/Conflict-free\_replicated\_data\_type
  24. About CRDTs • Conflict-free Replicated Data Types, https://crdt.tech/
  25. Locking strategy of git to achieve concurrency? \- Stack Overflow, https://stackoverflow.com/questions/19962024/locking-strategy-of-git-to-achieve-concurrency
  26. Is it safe if more git commands are run on the same repo in parallel? \- Stack Overflow, https://stackoverflow.com/questions/13459219/is-it-safe-if-more-git-commands-are-run-on-the-same-repo-in-parallel
  27. Git Worktrees: Parallel Work Without Losing Your Mind (and Why AI Agents Love Them), https://www.danieleteti.it/post/git-worktree-parallel-development-en/
  28. git-worktree Documentation \- Git, https://git-scm.com/docs/git-worktree
  29. Run parallel sessions with worktrees \- Claude Code Docs, https://code.claude.com/docs/en/worktrees
  30. ccmanager/docs/git-worktree-config.md at main \- GitHub, https://github.com/kbwo/ccmanager/blob/main/docs/git-worktree-config.md
  31. The Chubby lock service for loosely-‐coupled distributed systems \- Semantic Scholar, https://pdfs.semanticscholar.org/cdcd/1976ec997207e46c7d496543664197e061b4.pdf
  32. The Chubby Lock Service for Loosely-Coupled Distributed Systems, Burrows, OSDI 2006, http://muratbuffalo.blogspot.com/2010/10/chubby-lock-service-for-loosely-coupled.html
  33. Chubby: Google's Distributed Lock Service for Loosely-Coupled Systems \- Darsh Shah, https://darshshah.org/blog/2024/08/12/chubby-distributed-lock-service/
  34. (PDF) On optimistic methods for concurrency control (1981) | Hsiang-Tsung Kung | 1561 Citations \- SciSpace, https://scispace.com/papers/on-optimistic-methods-for-concurrency-control-13kptzhred
  35. On Optimistic Methods for Concurrency Control., https://www.cs.cmu.edu/\~dga/15-712/F07/lectures/12-optimism.pdf
  36. Concurrency Control in DBMS: Locking, MVCC & More | Databricks Blog, https://www.databricks.com/blog/concurrency-control
  37. Conflict-free Replicated Data Types ? \- ASC, https://asc.di.fct.unl.pt/\~nmp/pubs/sss-2011.pdf
  38. Conflict-Free Replicated Data Types | Request PDF \- ResearchGate, https://www.researchgate.net/publication/221540578\_Conflict-Free\_Replicated\_Data\_Types
  39. Real-time collaborative editing using CRDTs \- DiVA portal, https://www.diva-portal.org/smash/get/diva2:1304659/FULLTEXT01.pdf
  40. Concurrency in Go: Pessimistic, Optimistic, and Redis Distributed Locks Explained \- Medium, https://medium.com/@hanifmaliki/concurrency-in-go-pessimistic-optimistic-and-redis-distributed-locks-explained-77125355594d
  41. Is Agent Memory a Database? Rethinking Data Foundations for Long-Term AI Agent Memory \- arXiv, https://arxiv.org/html/2605.26252v1
  42. From context to dreams: architecting memory for AI agents \- Red Hat Emerging Technologies, https://next.redhat.com/2026/06/01/from-context-to-dreams-architecting-memory-for-ai-agents/
  43. Handling Race Conditions and Concurrent Resource Updates in Node and MongoDB by Performing Optimistic Updates | by Abdul Saleem Mohamed Faheem | Medium, https://medium.com/@codersauthority/handling-race-conditions-and-concurrent-resource-updates-in-node-and-mongodb-by-performing-f54140da8bc5
  44. Persistent Memory | Hermes Agent \- nous research, https://hermes-agent.nousresearch.com/docs/user-guide/features/memory
  45. Agent Memory Engineering \- Nicolas Bustamante, https://nicolasbustamante.com/blog/agent-memory-engineering
  46. race conditions if two clients git svn rebase and git push to the same git repo?, https://stackoverflow.com/questions/3876651/race-conditions-if-two-clients-git-svn-rebase-and-git-push-to-the-same-git-repo
  47. Using git clean/smudge filters to abstract absolute paths across a shared PetaLinux project, https://www.centennialsoftwaresolutions.com/help/git-pathfix/
  48. A hidden gem of Git: clean/smudge filter \- Medium, https://medium.com/@dimst23/a-hidden-gem-of-git-clean-smudge-filter-6c27bee20081
  49. A Case for Git Filters \- Will Carhart, https://willcarh.art/blog/a-case-for-git-filters
  50. git smudge/clean filter between branches \- Stack Overflow, https://stackoverflow.com/questions/22909620/git-smudge-clean-filter-between-branches
  51. Protect secrets in Git with the clean/smudge filter \- Red Hat Developer, https://developers.redhat.com/articles/2022/02/02/protect-secrets-git-cleansmudge-filter
  52. Git smudge and clean filters \- Super User, https://superuser.com/questions/1131747/git-smudge-and-clean-filters
  53. moorcheh-ai/memanto: Memory that AI Agents Love\! \- GitHub, https://github.com/moorcheh-ai/memanto