📌 Part of Blueprint: AI Agent & Local GPU Automation → L2: Hybrid LLM Gateway & Agent Loops

The Single-Writer Rule: Orchestrating Coding Agents Without Multi-Agent Chaos

· 9 min read · Case Studies aiagentsarchitecturedevops

Why It Matters

When software teams first experiment with AI coding agents, the intuitive next step is almost always multi-agent parallelism: if one agent can write a feature in ten minutes, spawning four agents simultaneously should ship the entire milestone in three.

In production, the reality is almost always the exact opposite. Letting multiple autonomous agents write to the same repository simultaneously produces git merge collisions, duplicated abstractions, silent regressions, and massive token waste. Coordination overhead devours any theoretical speed gains.

Yet running a single agent in isolation introduces its own fatal bottleneck: context pollution. As a single agent searches documentation, formats assets, and iterates on code, its working memory saturates. Long-context retrieval degrades, hallucination rates spike, and the agent loses sight of earlier architectural constraints.

Over the past year of managing production systems, client platforms, and internal services, I resolved this dilemma by implementing the Single-Writer Rule:

  1. Exactly one agent holds the write lock and edits code.
  2. Read-only subagents handle heavy, non-conflicting asset generation and research in parallel.
  3. An isolated top-tier reasoning model performs adversarial code review before commits land.
  4. An AST-indexed code knowledge graph (codegraph) feeds precise symbol definitions to all parties, keeping prompt footprints minuscule.

Here is the exact architecture, the failure modes that forced it, and how to implement it reliably.


The Multi-Agent Paradox: Cognition vs. Anthropic

In mid-2025, two of the leading teams in agentic AI published contradictory findings within forty-eight hours of each other.

Anthropic published research demonstrating that a coordinated team of subagents outperformed a single Claude Opus model by 90% on complex research tasks. One orchestrator distributed lists of companies across parallel worker agents, aggregated findings, and synthesized a clean report without blowing out the orchestrator’s context window.

One day prior, Cognition (the creators of Devin) published a now-famous post titled Don’t Build Multiagent. Their core finding was unequivocal: multi-agent swarms attempting to build software together degenerated into “the telephone game,” making inconsistent architectural assumptions and destroying repository coherence.

Both conclusions were completely correct within their respective domains:

Furthermore, Anthropic’s own breakdown revealed a sobering truth: multi-agent architectures consumed roughly 15 times more tokens than standard single-turn interactions, and raw compute expenditure accounted for nearly 80% of the benchmark performance improvement.

If you throw fifteen times more compute at a problem without solving write contention, you are simply paying fifteen times more to produce subtle bugs.


What Failed: The Three Traps of Swarm Coding

Before landing on our current orchestration pipeline, I tested multi-agent swarms across production codebases. Every failure traced back to three structural flaws:

1. The Telephone Game

An orchestrator receives a prompt from the human engineer. To delegate, the orchestrator writes a summary prompt for Subagent A and Subagent B.

User Prompt (Explicit Constraints + Implicit Domain Knowledge)
   ↓
Orchestrator Summary (Lossy Abstraction)
   ↓
Subagent Interpretation (Hallucinated Assumptions)

By the third tier of delegation, critical unspoken requirements—such as backward compatibility with legacy endpoints or strict typing conventions—vanish. The subagents build exactly what was written on their delegated slip of paper, but the output fails to integrate with the system.

2. Implicit Architectural Drift

Consider a seemingly trivial task: building an interactive browser widget.

Both agents execute independently. Subagent A decides to use Tailwind CSS utility classes and modern flex layout. Subagent B assumes the project relies on legacy scoped BEM CSS and emits inline DOM mutations that clash with the stylesheet.

Neither agent made an error; both made valid local decisions. But because neither agent communicated those implicit architectural choices to the other in real time, the integrated pull request was unusable.

3. Git Merge Hell and Lock Contention

When three agents attempt to modify code simultaneously, they inevitably edit adjacent lines in shared files (package.json, route registers, central types).

Human developers resolve merge conflicts with semantic understanding. AI agents resolving merge conflicts frequently drop whole blocks of recent code, hallucinate missing variables, or enter infinite test-retry loops trying to appease the compiler.


The Solution: The Single-Writer Architecture

To achieve high throughput without write collisions, we decoupled the development lifecycle into three distinct roles governed by a strict invariant: only one process can touch the repository files at any given time.

                           ┌────────────────────────┐
                           │   Human Requirements   │
                           └───────────┬────────────┘
                                       │
                                       ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                       ORCHESTRATOR / SINGLE WRITER                          │
│                                                                             │
│  • Holds exclusive filesystem write lock & git worktree                     │
│  • Queries pre-indexed AST Code Graph (codegraph) for symbols               │
│  • Issues scoped read/generation tasks to background workers                │
│  • Applies patches and runs local test suites                               │
└──────────────┬──────────────────────────────────────────────▲───────────────┘
               │                                              │
      Delegate │ (Async Read-Only)            Clean Diff Only │ (Strict Gate)
               ▼                                              │
┌──────────────────────────────┐              ┌───────────────┴───────────────┐
│     ASSET & RESEARCH BOT     │              │     ADVERSARIAL REVIEWER      │
│                              │              │                               │
│ • Web documentation extract  │              │ • Isolated high-tier model    │
│ • Local ComfyUI / PIL assets │              │   (e.g., Claude 3.5 Sonnet)   │
│ • SenseVoice / TTS pipelines │              │ • Zero prior context baggage  │
│ • Strictly isolated context  │              │ • Reviews unified git diff    │
└──────────────────────────────┘              └───────────────────────────────┘

Component 1: The Exclusive Single Writer

The primary coding agent is the only entity with access to patch, write_file, and git staging tools.

Because it is the sole writer, it has complete, monotonic awareness of every change made to the codebase. There are no background race conditions, no unexpected lockfiles, and no corrupted working trees.

Component 2: Parallel Asset & Research Workers

When building full-stack features, significant time and context are consumed by auxiliary tasks:

Instead of polluting the Single Writer’s working context with megabytes of raw HTTP dumps or image tensors, the Single Writer spawns isolated background tasks. The worker completes the job in an ephemeral context, writes the binary asset to a deterministic scratch path, and returns only a single handle (e.g., file path or JSON payload) to the writer.

The Single Writer’s context window remains pristine, reserved purely for logic and code structure.

Component 3: Adversarial Reviewer (The Fresh Eyes Rule)

When an agent spends twenty turns debugging an intricate function, it develops cognitive bias: it believes its own implementation is correct because it remembers the effort required to produce it.

Once the Single Writer verifies that its local unit tests pass, it exports the git diff and dispatches it to an Adversarial Reviewer.

The Reviewer runs on a top-tier reasoning model (such as Claude 3.5 Sonnet or flagship reasoning models) with zero conversational context. It is given only:

  1. The original task objective.
  2. The unified git diff.
  3. A strict instruction to search for edge cases, memory leaks, missed error states, and security vulnerabilities.

Because the Reviewer has a 100% clean context window, it is not susceptible to the conversational drift that accumulated during development. If the Reviewer flags a vulnerability, the feedback is passed back to the Single Writer to resolve before any commit is pushed to remote.

Component 4: Pre-Indexed AST Code Knowledge Graph

To eliminate the need for the Single Writer to scan whole repositories via crude directory greps, we integrated a local code knowledge graph (colbymchenry/codegraph).

Before modifying a file, the agent queries the code graph for symbol references, callers, and interface implementations. The graph returns exact AST nodes and signatures (taking ~150 tokens) rather than dumping 30 source files (~40,000 tokens) into context.


Quantified Results: Production Comparison

We evaluated this architecture against traditional single-agent development and unbounded multi-agent swarms across 5 full-stack tasks in a ~50,000-line TypeScript/Python codebase (average per task):

MetricUnbounded Multi-Agent SwarmTraditional Single AgentSingle-Writer + Adversarial Review
Git Merge Conflicts14 conflicts / run0 conflicts0 conflicts
Token Consumption~480,000 tokens~85,000 tokens~62,000 tokens (via Code Graph)
Context Exhaustion FailuresHigh (memory saturation)Moderate (long task sprawl)Zero
Edge-Case Regression Rate22% (architectural drift)12% (author bias)< 1.5% (adversarial caught)
End-to-End Task Wall Time18.4 min (merge retries)14.2 min (sequential)6.8 min

By restricting file mutation to a single process, outsourcing non-coding subtasks to isolated workers, and gating output through an unpolluted reviewer, development speed improved by over 2x while regression rates dropped to near zero.


The Rules for Implementation

If you are designing an agentic pipeline for your own team or infrastructure, follow these four rules:

  1. One Writer at a Time: Never allow two LLM threads to possess write tools over the same working directory. If you need parallel coding, use distinct git worktrees with strict human-gated PR merges.
  2. Workers Return Handles, Not Transcripts: When delegating research or asset creation, instruct subagents to write results to disk and return a file path. Never serialize intermediate multi-page reasoning back into the orchestrator.
  3. Reviewers Must Be Stateless: The model auditing your code should never be the model that wrote it, and it should never see the author’s conversational struggle. Give it the diff and tell it to break it.
  4. Index Symbols Before Spawning Agents: Raw text search inside a 50,000-line repository is an invitation for token bankruptcy. Pre-index your AST into a graph database or symbol index so agents can locate dependencies with micro-queries.

Want This for Your Business?

I design, implement, and operate autonomous agent infrastructure, custom internal tooling, and self-hosted automation systems for companies that need software shipped reliably without human babysitting.

Whether you are looking to deploy an automated technical pipeline, build custom internal tools, or eliminate manual operations with robust agent architectures:

Lee Teong Hoe

Lee Teong Hoe · Mr Hoelee

Full-stack developer & DevOps engineer based in Malaysia. I run my own production infrastructure and build web systems for small businesses — this blog is the living record.

Hiring? Profile & stack · Malaysian SME? Website design & development ↗ · All posts