Skip to main content
日本語

Run AI Coding Agents in Parallel Without Merge Chaos

Tomohiro Iida · Published August 14, 2026 · Updated August 23, 2026

Two coding agents can generate code faster than one. That does not mean the repository moves forward twice as fast. As implementation becomes parallel, integration, verification, and final judgment become the bottleneck. The operating rule in this article is simple: parallelize implementation, but serialize integration into main.

This article focuses on multiple agents working in the same repository. For the broader split between ChatGPT as design support, Claude Code as implementation, Codex as an independent reviewer, and a human as the final integrator, see the related role-separated development article.

How Netsujo separates design, implementation, audit, and final judgment

Conclusion: implementation can be parallel; integration should be sequential

Key takeaways

  • Parallelize only tasks whose completion criteria can be judged independently.
  • Give every task one branch, one worktree, one base commit, and an explicit file boundary.
  • A worktree isolates files and Git working state; it does not automatically isolate API contracts, databases, ports, test data, caches, or merge order.
  • Use a Task Contract to define allowed paths, prohibited paths, acceptance criteria, and stop conditions before an agent edits the repository.
  • Merge one pull request at a time in dependency order, update the remaining branches from main, and rerun verification.

The slowest stage determines effective development throughput

Agentic development has three operational stages. Adding agents increases implementation capacity, but review and integration capacity do not increase automatically. When pull requests arrive faster than they can be integrated, the result is inventory: branches based on older commits, duplicated assumptions, and more expensive conflict resolution.

StageWorkTypical bottleneck
ImplementationCode, tests, and documentationAmbiguous tasks and incomplete repository context
IntegrationCombining changes into one valid stateDependencies, ownership, and merge order
VerificationDeciding whether the combined state is correctTest scope, review capacity, and runtime environments

The useful metric is not how many agents were active. It is how much verified change reached main, how long integration took, and how much rework was required.

Four conflicts must be managed separately

ConflictDoes Git detect it?ExamplePrimary control
Text conflictUsuallyTwo branches edit the same component or configuration linesWorktrees, file ownership, merge or rebase
Contract conflictUsually notThe API returns a nested object while the UI expects flat fieldsShared types, API contracts, contract tests
Runtime conflictNoTwo worktrees migrate the same database or use the same test tenantSeparate ports, databases, namespaces, and fixtures
Integration-order conflictNoA UI depending on a new API is merged before that API exists in mainDependency map and one integration owner

A clean Git merge is not proof that the combined system is valid. The most damaging conflicts often occur between assumptions in different files or between processes using shared infrastructure.

Choose tasks by dependency, not by agent capability

Good parallel candidates
Independent pages or components, tests for an already fixed contract, documentation, logging, read-only investigation, and changes in separate packages or services.
Parallel after a contract is fixed
Frontend and backend work, a shared component and its consuming screen, a data model and validation, or implementation and end-to-end tests.
Prefer sequential work
The same database migration, core authentication and authorization, large shared-type changes, repository-wide renames, dependency upgrades with one lockfile, or a refactor whose direction is still undecided.

If any answer is unclear, change the split or run the tasks sequentially. Forcing a dependency-heavy task into parallel work creates more integration work than implementation time saved.

Use four layers of isolation

Workspace isolation
Each agent works in a separate Git worktree instead of sharing uncommitted files and generated output in one checkout.
Change-responsibility isolation
Each task lists allowed and prohibited paths. Shared contracts, authentication, migrations, and package files have an explicit owner.
Runtime isolation
Development ports, databases, queue prefixes, object-storage prefixes, test users, and external sandbox namespaces are separated where possible.
Integration-authority isolation
Implementation agents prepare commits and pull requests. One integration owner decides merge order, conflict meaning, and release readiness.

Git worktree separates working directories, not every shared resource

Git worktree lets one repository have multiple linked working trees so more than one branch can be checked out at the same time. A practical rule is one task, one branch, and one worktree. A detached worktree is also useful for read-only review or experiments.

Claude Code supports starting an isolated session with the --worktree or -w option. The Codex app also provides built-in worktree support for multiple agents on the same repository. These features reduce file collisions, but application-level resources still need separate controls.

A worktree is a fresh checkout. Gitignored environment files may not be present, and a shared local database or staging project remains shared unless you deliberately separate it.

Give every agent a Task Contract

The contract should constrain the task before code is generated. The most important section is often what the agent must not change. Broad instructions such as “improve related areas as needed” erase ownership boundaries and let one agent enter another task’s scope.

FieldPurpose
Task ID and objectiveGive the work one traceable purpose
Base commitRecord the exact repository state the agent assumed
Allowed pathsDefine where edits are expected
Prohibited pathsProtect shared contracts, migrations, authentication, package manifests, or lockfiles
Dependent contractFix API shapes, events, error formats, and null handling
Acceptance criteriaMake completion independently testable
Verification commandsSpecify lint, typecheck, focused tests, build, or E2E checks
Stop conditionsRequire the agent to report instead of silently expanding scope
Completion reportReturn commit SHA, changed files, checks run, remaining risks, and deviations

Before editing, ask the agent to list planned files. At completion, compare that list with git diff --name-only origin/main...HEAD. Unexpected files should be formally added to scope, reverted, split into another pull request, or treated as a dependency—not left as an undocumented extra improvement.

Isolate the runtime environment as deliberately as the files

ResourceExample isolation
Development serverUse ports such as 3001 and 3002
DatabaseUse separate database names, schemas, or tenant IDs
Redis or queuesUse a task-specific prefix or namespace
Object storageUse a separate bucket prefix
Test usersUse agent-a and agent-b fixtures
External APIsUse separate sandbox projects or idempotency keys
Temporary filesWrite inside the task worktree

When a shared resource cannot be separated, add a lock. For example, only one task may migrate a shared staging database at a time. Refusing to parallelize an unsafe resource is part of a correct parallel operating model.

Subagents and worktrees solve different problems

NeedPrimary mechanism
Separate investigation context or specialist rolesSubagent or custom agent
Edit multiple implementations at the same timeGit worktree
Keep API and type assumptions consistentTask Contract and shared contract
Control what reaches mainPull request, CI, branch protection, integration owner

Creating more subagents does not automatically separate their file systems. When agents can write concurrently, workspace isolation must be explicit.

Serialize integration in dependency order

Completion time is not merge order. A frontend pull request that depends on a new API must wait even if it was finished first. The integration owner keeps main valid at every step.

Do not make Claude Code and Codex race to implement the same task

Unless comparison is the experiment, two implementations create another selection and integration task. A more efficient default is to let one agent implement and another review the final diff without write access. Findings normally return to the original implementation owner for correction, keeping ownership legible.

RoleResponsibilityWrite authority
Integration ownerTask split, shared contracts, merge order, release decisionMain and shared contracts
Implementation agent AOne independent featureDedicated worktree
Implementation agent BA separate feature or test scopeDedicated worktree
Review agentDiff review, regression and security findingsRead-only by default
CILint, typecheck, tests, and build checksDecision signal only

Make main a technical gate rather than a reminder

Use cheap checks early and expensive checks near integration. Focused lint, tests, and typecheck can run during implementation; broader tests, build, E2E, authorization checks, and migration verification should run before high-risk changes merge.

Limit work in progress before adding another agent

Fast implementation makes it easy to start more tasks while existing pull requests wait. That is usually the wrong response. Waiting branches age, their base commits diverge, and later integration becomes more expensive.

Minimum operating rules

Frequently asked questions

Does a worktree eliminate conflicts?

No. It separates working directories and Git state. API contracts, shared types, databases, ports, external services, and merge order still need explicit controls.

Can frontend and backend work run in parallel?

Yes, after the request shape, response shape, error format, authorization conditions, and null handling are fixed. If the contract is still moving, sequential work usually produces less rework.

How many agents should run at once?

Use the number the integration owner can review and merge without growing a backlog. Hardware and model limits are not the operational limit; review and integration throughput are.

Official references

Git: git-worktree documentation

Anthropic: Run parallel Claude Code sessions with worktrees

OpenAI: Introducing the Codex app

GitHub: About protected branches

Product features and official documentation references were checked on 14 August 2026.

Netsujo supports AI implementation, proof-of-concept design, and the operating controls that determine where agents may act and where human judgment remains mandatory.

Discuss an AI implementation and governance design

AI agent development and operations incident log

The same work item, different chat names

Claude Code specification-driven development

A one-person, four-project Claude Code operating record

Solo development with AI agents and the concentration of judgment(日本語)

Continue the series

Previous: #08 Cutting CI cost almost removed the safety checks

Next: #10 A green deploy is not production verification

Back to all 12 episodes of the AI Agent Development Incident Log

What Broke When We Put AI Agents to Work #09

We parallelized AI agents and the merge queue stopped draining

How a missing controller creates queue starvation

More workers increased pull requests, reruns, and coordination, but did not increase completed delivery. The missing layer was a controller that owned UNKNOWN states, drift, collision, fairness, and canonical task claims.

Incident Card

We expected more agents to increase throughput. Pull requests were created faster and several lanes stayed active, yet the merge queue stopped producing completed changes.

The system was optimizing worker activity rather than terminal delivery.

FieldObserved condition
SymptomMore workers and pull requests, but almost no merge throughput.
Direct impactCI reruns, review invalidation, and branch synchronization increased.
Hidden impactLower-priority candidates starved while the same blocked candidates were reconsidered.
Incorrect premiseLocally correct agents naturally produce globally convergent execution.

UNKNOWN is not failure

Immediately after a merge, one controller run observed mergeable as null for every candidate. A later run observed no null values. The first run had not discovered thirty-six unmergeable pull requests; GitHub had not finished computing mergeability.

Collapsing true, false, and null into a binary result converted eventual consistency into terminal failure. The controller must preserve MERGEABLE, NOT_MERGEABLE, and UNKNOWN as distinct states.

  • MERGEABLE: the platform has established that the candidate can be integrated.
  • NOT_MERGEABLE: the platform has established a blocking condition.
  • UNKNOWN: the observation is incomplete or temporarily unavailable.

Main drift can invalidate your own evidence

Synchronizing every branch whenever main advances appears conservative, but every synchronization moves the pull-request head. That can invalidate CI, review, and authorization that were valid for the previous exact SHA.

The correct question is not how many commits the branch is behind. The correct question is whether the new main state affects the current task contract, dependency surface, or integration result.

Drift classController action
No impactKeep the current plan and evidence.
Possible impactRun targeted verification.
Confirmed impactSynchronize only with an active mutation owner, then replan the affected subgraph.

Collision detection needs an authority that breaks ties

Two candidates can each correctly decide that they collide with the other and therefore wait. Without an ordering authority, symmetric safety logic becomes deadlock.

The controller must choose one candidate using a deterministic policy such as incident severity, valid evidence already accumulated, downstream blocking value, remaining work, risk, and age.

Priority without fairness creates starvation

A high-priority candidate that repeatedly returns UNKNOWN can occupy the front of the queue forever. Re-observation should use backoff, and independent lower candidates should continue when they do not share resources or dependencies.

  • Set a next-observation time for UNKNOWN candidates.
  • Temporarily remove them from the runnable queue.
  • Allow independent candidates to advance.
  • Track consecutive deferrals and maximum queue age.
  • Use age boosting when a candidate has been postponed repeatedly.

Deduplicate work before it becomes a pull request

Several lanes can discover different implementations for the same root cause. If every proposal becomes a branch and pull request, the human eventually becomes the canonicalization layer.

A controller should manage task claims in addition to pull requests. A claim binds a root-cause key to one canonical owner and one canonical mutable delivery path.

  • JOIN_EXISTING when another worker can contribute to the canonical task.
  • PROPOSE_TO_CANONICAL_OWNER when an alternate implementation is useful.
  • SPLIT_AS_INDEPENDENT_SUBTASK only when the work can terminate independently.
  • REJECT_DUPLICATE when a new branch adds no independent delivery value.

Rule

Design the controller before increasing worker count. The controller owns priority, ownership, UNKNOWN states, collision resolution, fairness, and evidence invalidation.

Guardrail

  • Keep UNKNOWN distinct from failure.
  • Use backoff without blocking unrelated queue candidates.
  • Evaluate main drift by impact rather than commit count.
  • Require an active mutation owner and expected head for branch synchronization.
  • Resolve collisions with a deterministic controller policy.
  • Maintain one canonical task claim per root cause.
  • Treat alternate implementations as proposals before creating duplicate pull requests.
  • Measure queue drainage rather than pull-request creation volume.

Evidence

  • Percentage of queued tasks reaching a terminal state
  • Time from pull-request creation to merge
  • Recovery rate from UNKNOWN observations
  • Unnecessary branch synchronizations after main drift
  • Duplicate pull requests for the same task claim
  • Maximum queue age and starvation count
  • Evidence reacquisition caused by avoidable head movement

Remaining Risk

A controller can become a new central bottleneck. Poor priority rules can starve valid work, weak impact analysis can miss real dependencies, and task claims can be defined too broadly or too narrowly.

Keep deterministic state transitions, leases, and evidence validity in code. Use language models only where semantic judgment is actually required.