On this page
  1. The promise and the problem
  2. Pattern 1: Spec-driven task decomposition
    1. The four-phase workflow
    2. Effective vs. ineffective decomposition
  3. Pattern 2: Git worktree isolation
    1. What’s shared vs. isolated
    2. The setup
    3. What this buys you
    4. What this doesn’t protect against
  4. Pattern 3: Coordinator / specialist / verifier architecture
    1. Tier 1: Coordinator (plans, doesn’t code)
    2. Tier 2: Specialist agents (implement, don’t plan)
    3. Tier 3: Verifier (validates, doesn’t implement)
    4. The workflow
  5. Pattern 4: Per-task model routing
  6. Pattern 5: Automated verification gates
    1. The gate checklist
    2. Implementing gates
  7. Pattern 6: Sequential merges
    1. Merge order matters
  8. Putting it all together: a complete multi-agent session
    1. Phase 0: Setup
    2. Phase 1: Coordinator plans (Claude Opus)
    3. Phase 2: Specialists implement (parallel)
    4. Phase 3: Verify and merge (sequential)
    5. Cleanup
  9. When NOT to use multiple agents
  10. Checklist
  11. FAQ
    1. How many agents should I run in parallel?
    2. Do I need a special orchestrator for multi-agent work?
    3. What’s the biggest risk with multi-agent coding?
    4. Can I use different models for different agents?
  12. Related topics
  13. Sources
tutorial

How to Coordinate Multiple AI Coding Agents on One Codebase

Running multiple AI agents in parallel sounds fast, but without coordination they overwrite each other's work. Learn six patterns that keep parallel agents safe: spec-driven decomposition, git worktrees, role splits, model routing, verification gates, and sequential merges.

Quick answer

  • Running multiple AI agents in parallel requires coordination infrastructure, not just more prompts.
  • Six patterns make it safe: spec-driven decomposition, git worktree isolation, coordinator/specialist/verifier roles, per-task model routing, automated verification gates, and sequential merges.
  • Start with 2 agents on non-overlapping tasks. Scale only when coordination is proven.
  • The failures are predictable: merge conflicts, duplicated implementations, and silent semantic contradictions that pass compilation but fail at runtime.

The promise and the problem

Multi-agent coding promises parallel speed: one agent builds the backend, another builds the frontend, a third writes tests — all simultaneously. In practice, without coordination, you get three agents editing the same files, duplicating each other’s work, and producing changes that merge cleanly but break at runtime.

The root cause is simple: agents have partial, stale views of a shared mutable codebase. Agent A changes auth.ts. Agent B changes auth.ts on a different branch. Git merges them. Two days later, the login endpoint returns 500 because the two changes made incompatible assumptions about the user session format. Git saw no conflict — the edits were on different lines — but the code is broken.

This guide covers six coordination patterns that prevent these failures. They’re drawn from teams running multi-agent workflows in production and from the coordination infrastructure built into agentic development platforms like Augment Intent, Claude Code, and OpenAI Codex.

If you haven’t read the concept primer, start with What Is Multi-Agent Coding? — it covers the failure modes in detail. This guide is the how-to.


Pattern 1: Spec-driven task decomposition

The problem: Agents overstep their bounds when they don’t know where their task ends and another agent’s begins. “Add user authentication” to Agent A and “Add user profiles” to Agent B, and both edit the user model, the user routes, and the user validation — differently.

The fix: Decompose work into tasks with explicit file and interface boundaries. Every agent gets a spec that says exactly what files it touches, what interfaces it depends on, and what it must not change.

The four-phase workflow

  1. Specify — Define user journeys and success criteria. Write a shared spec that every agent reads.
  2. Plan — Identify dependencies and integration points. Which interfaces do the tasks share? Define them before any agent writes code.
  3. Tasks — Break work into small units that can be implemented and tested in isolation. Each task gets: target files, input/output contracts, constraints, and acceptance criteria.
  4. Implement — Agents generate code against their task spec. Humans verify at checkpoints.

Effective vs. ineffective decomposition

# ❌ Ineffective (monolithic — agents will collide)
"Add user authentication and profiles to the app"

# ✅ Effective (decomposed with boundaries)
Task 1: Add User model and migration
  - Files: src/models/user.ts, migrations/003_add_users.ts
  - Contract: User { id, email, password_hash, created_at }
  - Constraint: Do NOT add profile fields — Task 2 handles those

Task 2: Add Profile model
  - Files: src/models/profile.ts, migrations/004_add_profiles.ts
  - Contract: Profile { id, user_id (FK to users), display_name, bio }
  - Constraint: Do NOT modify the User model from Task 1

Task 3: Add auth endpoints
  - Files: src/routes/auth.ts
  - Dependencies: User model from Task 1 (import only, don't modify)
  - Constraint: Hash passwords with bcrypt; return JWT

Task 4: Add profile endpoints
  - Files: src/routes/profiles.ts
  - Dependencies: Profile model from Task 2, auth middleware from Task 3
  - Constraint: All endpoints require valid JWT

Each task has non-overlapping files, explicit dependencies on other tasks’ outputs, and constraints preventing scope creep. This is the difference between parallel agents that compose and parallel agents that collide.

For a deeper dive into writing effective task specs, see How to Write a Spec an AI Coding Agent Can Actually Follow.


Pattern 2: Git worktree isolation

The problem: Even with non-overlapping file assignments, agents running in the same working directory can overwrite each other’s changes, corrupt each other’s builds, or step on shared config files.

The fix: Give each agent its own git worktree — a separate working directory with its own files and index, sharing the same .git object database.

What’s shared vs. isolated

ComponentShared or IsolatedImplication
.git/objects/ (history)SharedHistory stored once; space-efficient
.git/refs/ (references)SharedBranch names visible across worktrees
Working directory filesIsolatedEach agent edits independently
.git/index (staging)IsolatedEach agent stages independently
.git/HEADIsolatedEach agent tracks its own branch

The setup

# Create isolated worktrees, one per agent
git worktree add ../agent-1-auth -b feature/auth
git worktree add ../agent-2-profiles -b feature/profiles
git worktree add ../agent-3-tests -b feature/tests

# Launch each agent in its own worktree
cd ../agent-1-auth && claude    # Agent 1: auth endpoints
cd ../agent-2-profiles && codex  # Agent 2: profile endpoints
cd ../agent-3-tests && cursor    # Agent 3: integration tests

# ⚠️ Critical: serialize git operations across worktrees
# Don't run concurrent commits, fetches, or pulls
git -C ../agent-1-auth commit -am "Add auth endpoints"
git -C ../agent-2-profiles commit -am "Add profile endpoints"
git -C ../agent-3-tests commit -am "Add integration tests"

What this buys you

  • Agent 1 edits src/routes/auth.ts in its worktree. Agent 2 edits src/routes/profiles.ts in its worktree. They never touch each other’s files.
  • Each agent has its own build artifacts, its own node_modules, its own test output.
  • Conflicts are deferred to intentional merge points, not discovered when an agent’s build mysteriously breaks.

What this doesn’t protect against

  • Shared external state: local databases, Docker containers, caches. If two agents both hit the same local Postgres instance, they can still conflict. Isolate these too, or run agents sequentially when they touch shared infrastructure.
  • Concurrent git operations: never run git commit, git fetch, or git pull in two worktrees simultaneously. The shared metadata can corrupt. Serialize all git operations.

Pattern 3: Coordinator / specialist / verifier architecture

The problem: Agents working independently make incompatible design decisions. Agent A uses JWT with a 1-hour expiry. Agent B assumes session tokens with a 7-day expiry. Both are “correct” on their own; together, the auth system is incoherent.

The fix: Split work into three roles with distinct responsibilities.

Tier 1: Coordinator (plans, doesn’t code)

The coordinator reads the codebase, designs the approach, decomposes the work, and tracks progress. It never writes code — it writes specs and tasks.

Responsibilities:

  • Analyze the codebase and identify integration points
  • Draft the shared spec with interface contracts
  • Decompose the spec into non-overlapping tasks
  • Assign tasks to specialist agents
  • Track progress and update the spec as work completes

Model recommendation: Frontier reasoning model (Claude Opus, GPT-5, Claude Fable). This is the role where reasoning quality matters most — a bad decomposition causes failures across all agents.

Tier 2: Specialist agents (implement, don’t plan)

Specialists execute bounded tasks: frontend implementation, database migrations, test authoring, refactoring. Each specialist gets one task spec and must not expand scope.

Responsibilities:

  • Read the task spec and its declared dependencies
  • Implement the task within the declared file and interface boundaries
  • Write tests that verify the task’s acceptance criteria
  • Report completion with evidence (passing tests, unchanged files outside scope)

Model recommendation: Mid-tier models (Claude Sonnet, GPT-4o, Qwen3-Coder 80B). Quality matters but cost matters more — you’re running 2-4 specialists per session.

Tier 3: Verifier (validates, doesn’t implement)

The verifier checks specialist output against the shared spec and acceptance criteria. It’s the quality gate before human review.

Responsibilities:

  • Run the test suite and confirm all tests pass
  • Verify that the agent didn’t modify files outside its task boundary
  • Check that interface contracts are satisfied (e.g., Task 2’s Profile model correctly references Task 1’s User model)
  • Flag regressions, scope violations, and contract breaks

Model recommendation: Budget models (Claude Haiku, GPT-4o-mini, Gemma 4 26B). Verification is pattern-matching, not deep reasoning — a cheap model handles it well.

The workflow

Coordinator: "Here's the spec and 4 tasks."

Specialist 1: implements Task 1 (auth model)  ──┐
Specialist 2: implements Task 2 (profile model) ─┤ parallel
Specialist 3: implements Task 3 (auth routes)   ─┤
Specialist 4: implements Task 4 (profile routes) ─┘

Verifier: runs tests, checks contracts, flags issues

Human: reviews Verifier's report, approves or requests fixes

Merge all branches sequentially (Pattern 6)

Pattern 4: Per-task model routing

The problem: Running every agent on Claude Opus burns money. Running every agent on a budget model produces bugs. Neither extreme is optimal.

The fix: Route each task to the cheapest model that can handle it well.

RoleTask typeRecommended modelRationale
CoordinatorPlanning, decompositionClaude Opus / GPT-5 / Claude FableReasoning quality directly affects all downstream agents
SpecialistComplex feature (multi-file, new patterns)Claude Sonnet / GPT-4o / Qwen3-Coder-Next 80BStrong enough for implementation, 3-5x cheaper than Opus
SpecialistSimple feature (single file, existing patterns)Qwen3-Coder 30B / DeepSeek V4 API / Haiku10-20x cheaper than Opus, sufficient for pattern-matched work
SpecialistTest generationQwen3-Coder 30B / Gemma 4 26B / HaikuTests follow existing patterns — cheap models do this well
VerifierValidation, contract checkingHaiku / Gemma 4 26B / GPT-4o-miniPattern-matching, not deep reasoning
DebuggerInvestigating a test failureClaude Sonnet / OpusDebugging needs stronger reasoning than test generation

The cost impact: A coordinator (Opus) + 3 specialists (one Sonnet, two Qwen3-Coder) + a verifier (Haiku) costs roughly 40% of running all five agents on Opus, with no measurable quality difference for most tasks.

For a detailed comparison of available models, see Self-Hosted AI Coding Models in 2026: The Practical Review.


Pattern 5: Automated verification gates

The problem: Agents declare “done” when the code compiles. Silent semantic contradictions — two agents’ changes compose at the text level but break at runtime — are the hardest multi-agent failure to catch.

The fix: Every merge must pass automated gates before a human sees it.

The gate checklist

  1. Test suite passes — the minimum. If tests fail, the merge is blocked.
  2. No out-of-scope file changes — did the agent touch files outside its task boundary? Diff the branch against its declared file set.
  3. Contract compliance — does Task 2’s code use Task 1’s interface correctly? For typed languages, the compiler catches some of this. For dynamic languages, verify with integration tests at the seams.
  4. No regression — do previously passing tests still pass? Run the full suite after every merge.
  5. Lint and format — did the agent follow the codebase’s conventions? Auto-fix if possible, flag if not.

Implementing gates

# In CI, or as a local script before merge:

# 1. Full test suite
npm test

# 2. Check for out-of-scope changes
# Compare changed files against the task spec's declared file set
git diff --name-only main..feature/auth | grep -v -f task-auth-allowed-files.txt

# 3. Type checking (catches contract violations at compile time)
npx tsc --noEmit

# 4. Lint
npx eslint . --max-warnings 0

# 5. If all pass: merge
git merge feature/auth

The verifier agent (Pattern 3) can automate this: give it the gate script, run it after each merge, and only notify the human if something fails.


Pattern 6: Sequential merges

The problem: Merging all branches simultaneously creates a combinatorial explosion of conflicts. If 4 agents each changed 3 files, a simultaneous merge produces up to 12 conflict points to resolve — and no guarantee the resolution is semantically correct.

The fix: Merge branches one at a time, running the full verification gate (Pattern 5) after each merge.

# ❌ Simultaneous merge (risk of hidden semantic conflicts)
git merge feature/auth feature/profiles feature/tests

# ✅ Sequential merge (each merge verified before the next)
git merge feature/auth
npm test && npx tsc --noEmit  # Gate passes
git merge feature/profiles
npm test && npx tsc --noEmit  # Gate passes
git merge feature/tests
npm test && npx tsc --noEmit  # Gate passes

If a merge fails the gate, you know exactly which branch introduced the problem — because it was the last one merged. Debug the failure, fix it, and continue.

Merge order matters

Merge in dependency order:

  1. Models and migrations first — everything depends on the data layer
  2. Utilities and middleware second — shared infrastructure that endpoints consume
  3. Endpoints and routes third — the consumers of everything above
  4. Tests last — they verify the integrated whole

This minimizes the chance that a merge breaks a dependency that hasn’t been merged yet.


Putting it all together: a complete multi-agent session

Here’s a real workflow for splitting a feature across 3 agents on a Node.js codebase:

Phase 0: Setup

# Create worktrees
git worktree add ../agent-1-models -b feature/user-models
git worktree add ../agent-2-routes -b feature/user-routes
git worktree add ../agent-3-tests -b feature/user-tests

Phase 1: Coordinator plans (Claude Opus)

Prompt: "Here's the feature spec. Decompose into 3 tasks with
explicit file boundaries, interface contracts, and constraints."

Output: Task specs for Agent 1 (models), Agent 2 (routes), Agent 3 (tests)

Phase 2: Specialists implement (parallel)

Agent 1 (Qwen3-Coder 30B, in worktree ../agent-1-models):
  "Implement Task 1: User and Profile models.
   Files: src/models/user.ts, src/models/profile.ts
   Contract: User { id, email, passwordHash }, Profile { id, userId, displayName }
   Constraint: Do NOT add routes or middleware"

Agent 2 (Claude Sonnet, in worktree ../agent-2-routes):
  "Implement Task 2: User endpoints.
   Files: src/routes/users.ts, src/middleware/auth.ts
   Dependencies: User model from Task 1 (import only, don't modify)
   Constraint: Hash passwords with bcrypt; return JWT; add rate limiting"

Agent 3 (Qwen3-Coder 30B, in worktree ../agent-3-tests):
  "Implement Task 3: Integration tests.
   Files: tests/users.test.ts, tests/auth.test.ts
   Dependencies: Routes from Task 2, Models from Task 1
   Constraint: Test both happy path and edge cases from the shared spec"

Phase 3: Verify and merge (sequential)

# Merge Agent 1 → verify → continue
git merge feature/user-models
npm test && npx tsc --noEmit  # ✅ Passes

# Merge Agent 2 → verify → continue
git merge feature/user-routes
npm test && npx tsc --noEmit  # ❌ Fails: missing import

# Debug: Agent 2 imported User from '../models/User' but file is '../models/user'
# Fix: correct the import, re-run verification
npm test && npx tsc --noEmit  # ✅ Passes

# Merge Agent 3 → verify → done
git merge feature/user-tests
npm test && npx tsc --noEmit  # ✅ Passes — all 3 agents' work is integrated

Cleanup

git worktree remove ../agent-1-models
git worktree remove ../agent-2-routes
git worktree remove ../agent-3-tests

When NOT to use multiple agents

Multi-agent workflows add coordination overhead. For small tasks, a single agent is faster:

  • Single-file changes (add a function, fix a typo, rename a variable) — one agent, no coordination needed.
  • Sequential dependencies (Task 2 can’t start until Task 1 is done) — one agent doing both tasks sequentially avoids the handoff cost.
  • Unfamiliar codebase — a single agent exploring the codebase first, then decomposing, produces better task specs than a coordinator that doesn’t understand the code.

Where this bites vibecoders

The vibecoder instinct is to spin up 5 agents for a todo app. What happens: agents overwrite each other’s config files, three different auth patterns emerge, the CSS is a patchwork of conflicting frameworks, and the merge devolves into a rewrite. The discipline: start with one agent and a spec. Only add more agents when the spec reveals genuinely independent work units. Parallelism is a multiplier on your coordination, not a substitute for it.

Checklist

  • Write a shared spec before assigning any tasks
  • Decompose into tasks with non-overlapping file boundaries
  • Give each agent an explicit list of files it can and cannot touch
  • Create a separate git worktree for each agent
  • Assign a coordinator (plans), specialists (implement), and a verifier (validates)
  • Route each role to the cheapest model that handles it well
  • Run automated verification gates after every merge
  • Merge branches sequentially in dependency order
  • Clean up worktrees after the session

FAQ

How many agents should I run in parallel?

Start with 2. One agent per non-overlapping task. The failure modes of 3+ agents compound faster than the speed gains. Only add more agents when your coordination infrastructure — specs, worktrees, verification gates — is proven with 2. Most teams overestimate how much parallelization their codebase can absorb without conflict.

Do I need a special orchestrator for multi-agent work?

Not for 2-3 agents. Git worktrees + a shared spec + sequential merges is sufficient. Orchestrators (Intent, Augment, Claude Code’s sub-agents, OpenAI Codex’s subagents) help at 4+ agents by managing context distribution and integration automatically, but the principles — isolation, verification, serialization — don’t change.

What’s the biggest risk with multi-agent coding?

Silent semantic conflicts: two agents’ changes merge cleanly at the text level but break each other’s assumptions at runtime. One agent changes a function signature; another adds a call to the old signature. Git sees no conflict, the code compiles, it fails in production. Only integration tests at the seams catch this.

Can I use different models for different agents?

Yes, and you should. Route a frontier model (Opus, GPT-5) for the coordinator/planner role, mid-tier models (Sonnet, Qwen3-Coder 80B) for specialist implementation, and budget models for verification and test generation. This is both cost-efficient and quality-optimal — planning needs stronger reasoning than test generation.


Sources

Share: