Skip to navigation

Claude Code Parallel Agents: Preventing File Conflicts with Worktrees

In short: Parallel Claude Code agents can overwrite the same files. Use separate worktrees, ownership boundaries and merge review.

Published 17 min read
On this page

Direct answer

Give each parallel Claude Code agent a separate working directory and branch, then define which files it owns. Use claude --worktree <name> or -w to create an isolated checkout instead of letting multiple agents edit the same tree. Inspect every merge because isolation prevents simultaneous overwrites, not conflicting intentions.

Official: a Claude Code worktree lives under .claude/worktrees/ on a new branch. Active sessions block edits and commands aimed at the main checkout. Despite separate checkouts, worktrees share .git, project plugins, permission approvals, and some local skills, so they are not complete security or state isolation.

The practical sequence is simple: split the work by file boundary, create one worktree per active editor, return a diff and test evidence from each branch, then merge in a controlled order. Do not put two agents on the same branch and hope timing keeps them apart.

The concrete win is fewer collisions during execution. The honest loss is merge work: separate branches can still touch the same module, duplicate discovery, or encode incompatible assumptions. A human integration review remains necessary.

Why conflicts happen

Parallel agents collide when their writable state overlaps. Two tasks can read the same repository safely, yet still conflict if both edit a shared configuration file, generated manifest, or central module. The collision does not require either agent to be wrong.

Shared context can make the overlap harder to see. A parent may know that one task owns routing and another owns tests, while each subagent receives only its own brief. The subagent context and duplicate-work analysis explains why ownership facts need to be written into the task message.

There is also a timing problem. An agent can read a file before another agent changes it, then write from an older view. Separate worktrees remove that shared-file race during execution, but the stale assumption can reappear during merge review.

Conflict mode What overlaps Typical signal First control
Direct overwrite Same file and lines One diff replaces another change Separate worktrees and file ownership
Generated-file collision Same generator output Conflicting manifest or lockfile Assign one generator owner
Semantic conflict Different files, incompatible behavior Tests pass alone but fail together Integration tests and merge review
Duplicate discovery Same search and reads Reports repeat the same facts Shared scouting brief
Shared external state Same branch, service, or remote resource Nondeterministic side effects Serialize that action outside the agents

A branch boundary is not a transaction system. It does not coordinate deployments, database migrations, or external APIs. The agent harness security boundaries are a useful reminder that filesystem separation is only one layer of a larger workflow.

Worktree isolation

Official: claude --worktree <name> or -w creates a worktree under .claude/worktrees/ on a new branch. Active sessions block edits and commands targeting the main checkout. That behavior supports a clean division between a stable integration tree and active agent checkouts.

A worktree is a linked Git working directory. It shares repository history with the main checkout while giving the session a separate file state. Explain it to a teammate as a second checkout tied to the same Git repository, not as a clone with independent history.

The documented sharing matters. Shared .git data, project plugins, permission approvals and some local skills can connect otherwise separate sessions. If two sessions depend on a plugin or an approved permission, changing that shared component can affect both. Isolation reduces file collisions, but it does not create independent trust domains.

Official limitations: worktrees do not support non-Git repositories. Symlinked paths, Git Large File Storage (LFS) pointers, and locked directories after non-interactive runs can cause problems. Check those conditions before choosing a worktree-heavy workflow.

Worktree property Documented behavior Operational consequence
Location Under .claude/worktrees/ Keep generated agent checkouts out of manual ownership plans
Branch New branch for the worktree Name the task and review its diff
Main checkout Active sessions block edits and commands against it Use the main tree for controlled integration
Shared repository data .git is shared History operations still need coordination
Plugins and approvals Shared across worktrees A shared change can affect every session
Local skills Some are shared Do not assume every local setting is isolated

The official worktrees documentation is the authority for these properties. The permissions documentation separately explains rule evaluation and its limits. Neither source promises that a worktree prevents every unsafe command.

Claude Code Parallel Agents evidence map separating a shared directory, separate worktrees, branch ownership and merge review
Claude Code Parallel Agents evidence map. Anthropic documents worktree creation, shared repository state, and main-checkout blocking; the diagram does not claim worktrees eliminate semantic merge conflicts.

File ownership

A separate directory helps only when the assignment has a boundary. Write the allowed paths into each task brief, along with the files that remain outside scope. If two tasks need the same shared file, make one task the owner and have the other return a proposed patch or review comment.

Use directory boundaries before line boundaries. Asking one agent to own the first half of a file and another to own the second half creates a predictable merge conflict. A module or package boundary gives each agent enough room to finish without sharing a writable surface.

Generated files deserve a single owner. Two agents may legitimately change different inputs that regenerate the same manifest, lockfile, or API client. Let one integration step regenerate the output after both changes land instead of merging two generated diffs by hand.

The large-codebase guidance recommends root and subdirectory CLAUDE.md files, scoped commands, codebase maps, and read-only exploration. Those pointers help an agent understand local conventions before it edits, but they do not assign ownership automatically.

A workable ownership brief

A useful brief names the objective, writable paths, read-only references, forbidden actions, and acceptance checks. It also names the integration owner. That person decides how branches combine and who resolves a semantic disagreement.

Avoid vague boundaries such as “improve the backend.” A broad assignment invites every agent to inspect the same entry points and edit the same shared utilities. A narrower assignment such as “change validation in the checkout module and return tests” still leaves room for judgment while making the writable surface visible.

Leave destructive recovery outside the parallel plan. The destructive git guardrails explain why rollback language can lead to data loss. If an agent branch is unwanted, review and discard it deliberately instead of resetting a shared checkout with uncommitted work.

Shared state still needs an owner

Worktree isolation changes where files live, but it does not make every dependency private. Because .git, project plugins, permission approvals, and some local skills are shared, decide which settings are repository policy and which belong to one task before the batch starts.

A plugin change made for one agent can alter the tools available to another. A new permission approval can change what every session may do. Test shared configuration in one controlled session, record the change, and tell the other task owners what became different.

External systems sit outside the worktree boundary. Deployments, database migrations, package publishing, and remote cleanup need a separate serialization rule. Two branches may be perfectly isolated while their deployment steps still target the same environment. Give those actions to the integration owner rather than to parallel implementers.

Repository history also needs coordination. A worktree shares Git data with the main checkout, so branch naming and cleanup should follow one plan. Preserve each returned diff and verification result before removing a worktree, especially when a non-interactive run may leave a locked directory.

A safe concurrency pattern

Start with a read-only scouting phase when the repository is unfamiliar. Ask one explorer to map the relevant package boundaries and return candidate files without editing. The parent can then divide implementation work using evidence rather than guesses.

Next, create one worktree per active implementation task. Preserve the main checkout for integration. Each agent receives its ownership brief and returns a branch diff, changed-file list, test output, and unresolved assumptions.

Official: custom subagents start with isolated context, and the default concurrent subagent limit is 20, adjustable with CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS. A configurable ceiling is not a target. Choose a batch size that a reviewer can understand and merge in a deliberate order.

Phase Writable surface Required output Gate before continuing
Scout Read-only repository access Package map and candidate files Parent confirms boundaries
Implement One worktree per task Branch diff and test evidence Ownership matches the brief
Integrate Main checkout or designated integration branch Combined diff No task is still writing
Verify Integration tree Focused and regression tests Review accepts behavior
Clean up Agent worktrees Recorded result before removal No unmerged evidence remains

The proof-of-work packet fits the output contract. A branch name and a success sentence are not enough. Ask for the files changed, the command run, the result, and any check that could not be completed.

Read-only tools can run concurrently in the Agent SDK while state-modifying tools execute sequentially, according to the agent loop documentation. Use that as a design clue for scouting and implementation phases, not as proof that every interactive session enforces identical ordering.

Claude Code Parallel Agents workflow moving from a shared directory to separate worktrees, branch ownership and merge review
Claude Code Parallel Agents workflow. Worktree behavior comes from Anthropic documentation; the scout, implement, integrate, and verify sequence is an operating pattern rather than a measured performance result.

Worked example: three tasks, one integration tree

Consider a synthetic repository with a checkout package, a notification package, and a shared test fixture. Three agents are assigned to validation, notification copy, and fixture extension. The fixture is shared, so the plan gives its ownership to the validation agent and asks the notification agent to return a proposed fixture change instead of editing it.

Create separate worktrees for all three tasks. Each brief lists writable paths and requires a diff plus focused test output. The notification agent can still investigate the fixture and suggest a change, but its branch does not write the shared file.

After the agents finish, merge the validation branch first because it owns the fixture. Merge the notification code second, then apply or reconcile its fixture proposal in the integration tree. Run the focused package tests, then the cross-package regression check.

This order is a safe test, not a benchmark. It demonstrates how ownership removes a known collision before execution. If the notification change needs a different fixture shape, the integration review catches the semantic conflict instead of allowing one agent’s diff to silently replace another’s.

Derived collision check: three parallel tasks with one shared writable file create three possible pairwise overlaps if every task can edit that file. Assigning the file to one owner reduces those pairwise overlaps involving that file to zero during execution. The calculation is 3 choose 2 = 3 possible task pairs, not a measured Claude Code conflict rate.

The cost per verified change framework is the right place to count the extra integration review. Worktrees can reduce emergency recovery while adding routine merge effort. Compare total verified cost, not just the number of simultaneous agents.

Merge review

Merge review is where separate intent becomes one behavior. Read the combined diff for assumptions that were reasonable in isolation but incompatible together. Pay special attention to shared types, configuration defaults, error handling, and generated outputs.

Run tests in dependency order when practical. A package test can pass against its own branch while a consumer fails after integration. The generated-test oracle bias discussion explains why tests derived from the implementation may miss a requirement. Define acceptance criteria independently of the agents’ diffs.

Merge check Question to answer Evidence
Ownership Did each branch stay inside its writable paths? Changed-file lists and combined diff
Generated output Was one owner responsible for regeneration? Generator command and resulting diff
Shared contracts Do types, defaults, and errors still agree? Consumer tests and interface review
Behavior Does the combined change meet the original requirement? Acceptance test or manual scenario
Side effects Were external actions serialized? Deployment or migration record
Cleanup Is every useful result preserved before worktree removal? Branch status and task log

The legacy-code characterization workflow matters when a merge touches undocumented behavior. Parallel isolation does not recover business rules that were never written down. Preserve known behavior before modernizing a shared module.

A merge conflict is useful information. It marks the place where two changes compete for the same text. A semantic conflict is harder because Git may merge cleanly while behavior breaks. Inspect both instead of treating a clean merge as proof of correctness.

Merge branches in dependency order when one change establishes a contract that another consumes. Merging the consumer first can make a failure look like a defect in the consumer when the required interface has not landed yet. Note the intended order in the task log so a reviewer does not have to infer it from branch names.

A clean diff also deserves a short assumption check. Ask whether each agent saw the same baseline, whether a shared default changed, and whether a test passed only because another branch was absent. These questions catch integration mistakes that file-level conflict markers cannot show, especially when each branch was verified alone against a repository state that no longer exists after the first merge.

Claude Code Parallel Agents tradeoffs among shared-directory collisions, separate worktrees and unresolved merge review
Claude Code Parallel Agents tradeoffs. Separate worktrees reduce shared-file collisions during execution, while documented sharing and merge review remain; no universal conflict reduction is claimed.

A concurrency checklist

Use this checklist before starting a parallel batch. It keeps file isolation, context, and review in the same plan.

Check Pass condition
Repository support The project is a Git repository without a blocking worktree limitation
Task boundaries Each task has a distinct objective and writable surface
Worktree mapping Each active editor has a named worktree and branch
Shared files One owner is assigned for each shared or generated file
External effects Deployments and other state changes are serialized
Context handoff Each brief contains constraints and relevant repository pointers
Return contract Each task provides diff, tests, and unresolved questions
Integration order Branch merge order follows dependencies
Cleanup gate Output is preserved before any worktree is removed

The monorepo search and token-budget guide helps with the scouting phase. Scope discovery before reading so parallel agents do not all inherit the same broad search problem.

Use the context-retention test for compaction when a long session hands work between agents. Critical ownership rules should live in the task brief, not only in a summary that may drop an exact path.

Maintain an external task log. The context-portable migration guide explains why a workflow should not depend on one interface’s memory. Save branch names, ownership, merge status, and verification results where a new session can read them.

Practical response: start with two bounded tasks

A small parallel batch is easier to reason about than a large one. Pick two tasks with separate modules, create two worktrees, and require structured reports. Inspect the combined change before adding more concurrency.

  1. Confirm the repository and worktree limitations.
  2. Write one ownership brief per task.
  3. Assign shared and generated files to a single owner.
  4. Create separate worktrees and branches.
  5. Run read-only scouting before implementation if boundaries are uncertain.
  6. Leave the main checkout stable for integration.
  7. Collect diffs, test results, and open questions from each branch.
  8. Merge in dependency order and review the combined behavior.
  9. Run focused and regression checks.
  10. Preserve results before cleaning up worktrees.

If a task appears stuck, use the subagent hang and timeout controls rather than launching a replacement on the same branch. If the running count looks wrong, use the background running-count diagnosis before canceling completed work. Before stopping an active branch task, check the subagent stop and resume semantics so a fresh dispatch does not accidentally assume completed history.

For long-running batches, keep budget controls separate from file isolation. The task budgets versus hard stops guide explains enforceable loop controls. The compaction cost worksheet helps estimate a long session, but it does not assign file ownership.

Claude Code Parallel Agents control checklist for separate worktrees, file ownership, main-checkout stability and merge gates
Claude Code Parallel Agents control checklist. The checklist applies documented worktree behavior with conservative ownership and review controls; it is not a guarantee against every merge or external-state conflict.

Honest loss and data gaps

The win is execution isolation. Separate worktrees prevent agents from writing over the same working files at the same time, and active sessions protect the main checkout from targeted edits and commands. That is a concrete improvement over blind shared-directory parallelism.

The loss is coordination. Worktrees add branches, merge order, duplicated setup, and integration review. They share repository data and some configuration, so a shared plugin or permission change can still affect multiple sessions. Symlinks, LFS pointers, non-Git repositories, and locked directories remain documented limitations.

Unknown: the frozen sources provide no controlled measurement of conflict reduction, token savings, or faster delivery from Claude Code worktrees. The large-codebase guidance supports scoped exploration, but it does not establish a fixed token-reduction percentage.

Future updates should compare a repeatable task set with and without worktrees while holding model, repository, and acceptance criteria constant. Record collisions, merge effort, test results, and human review time. A branch count alone is not a success metric.

Cost and latency still need separate measurement. The prompt-caching break-even math can explain prefix reuse, while the long-context prefill latency test separates waiting stages. Neither proves that more parallel agents produce more verified work.

Claude Code Parallel Agents verdict requiring separate worktrees and branch ownership while retaining merge review
Claude Code Parallel Agents verdict. Official documentation supports worktree isolation and names its limits; the frozen evidence does not quantify a universal reduction in conflicts or delivery time.

A limited OpenAI-format test route

To test a similar ownership workflow in another harness, One AI API Key provides an OpenAI-format lane. On 2026-11-27, its catalogue showed 76 listed models and 46 available-now free IDs across 22 families. The free IDs share 100 requests and 5,000,000 tokens per day per account, resetting at 05:30 IST / 00:00 UTC. Accounts can have up to three keys, with one request in flight per key on free models.

The free IDs are OpenAI-format only. They are not a Claude Code route. Claude Code uses the Anthropic-format endpoint, and all four Claude IDs were marked unavailable on 2026-11-27. Do not place a free ID into Claude Code or imply that another agent inherits Claude Code worktree behavior.

For OpenCode, Cline, Cursor, or another OpenAI-format agent, the endpoint quickstart shows the base URL and first request. The prepaid pricing page documents signup credit and billing without a subscription or seat fee. Use the LLM cost calculator for a separate estimate and review the privacy and retention policy before sharing repository material.

The loss is harness difference. Another agent may use different isolation and merge controls, so the smoke test validates routing rather than Claude Code semantics. The coding-agent model selection guide can help choose a model while keeping the workflow comparison honest.

FAQ

Do worktrees prevent all parallel-agent conflicts?

No. They reduce shared-working-directory collisions during execution. Semantic conflicts, generated-file overlap, duplicated discovery, and external side effects can still require coordination and merge review.

Can two agents use the same branch safely?

Do not plan on it. Separate worktrees create new branches, and the safe pattern assigns one active editor to each branch. Same-branch parallelism removes the branch boundary that makes ownership and review easier to reason about.

What do worktrees share?

Official: they share .git, project plugins, permission approvals, and some local skills. Treat those as shared state rather than assuming complete independence.

Check the documented limitations before relying on worktrees. Symlinked paths and Git Large File Storage pointers are listed constraints, and non-interactive runs can leave locked directories. Test the workflow on the actual repository.

When should I avoid parallel agents?

Avoid parallel edits when ownership cannot be divided, an external action must be serialized, or the change is too small to justify integration review. Read-only scouting can still be parallel when the reports have clear boundaries.

More Claude Code troubleshooting

Sources

More in Blog

Try it

One API key for GPT, Grok, DeepSeek, Kimi, GLM, MiniMax, Qwen, Step, Beam, Nemotron, ERNIE, Hunyuan, Gemma, Laguna, LFM, LongCat, Llama, Solar, Jais, Mistral, K2 and Roleplay.

One AI API Key speaks the OpenAI and Anthropic formats, so you change the base URL and the key, not your code. Credit packs start at $10, and every model has a published per-token rate.

New accounts$10 credit on sign-up
  • 100requests
    per day
  • 3Mtokens
    per day
  • 47free
    models
  • $0per
    token
  • No card
  • No end date
Claim $10 credit →