Git Worktrees for AI Coding: How to Run Multiple Agents Without Conflicts
Git worktrees give each AI coding agent its own isolated codebase so parallel sessions never overwrite each other's changes. Here's how to set it up.
Why Running Two AI Agents on the Same Codebase Breaks Everything
You spin up two AI coding sessions to work in parallel. One is building a new auth flow. The other is refactoring the API layer. Sounds productive. Then they both edit utils.ts at the same time, and now you have a mess that neither agent created intentionally.
Git worktrees fix this. They let each AI agent work in a completely isolated copy of your codebase — same repository, different working directories — so parallel sessions never step on each other’s changes. If you’re running multiple AI coding agents and not using worktrees, you’re managing conflicts manually. That’s the wrong job for a human in 2026.
This guide covers exactly how to set up git worktrees for parallel AI coding, how to structure the workflow, and what to watch out for.
What Git Worktrees Actually Are
Git worktrees are a built-in Git feature that lets you check out multiple branches from a single repository into separate directories on your filesystem — simultaneously.
Normally, one Git repository equals one working directory. If you want to work on a different branch, you stash your changes, switch branches, and context-switch mentally too. Worktrees break that constraint.
With worktrees, you can have:
my-project/ ← main worktree (main branch)
my-project-feat-auth/ ← linked worktree (feat/auth branch)
my-project-refactor-api/ ← linked worktree (refactor/api branch)
All three directories point to the same .git folder. They share history and objects. But each has its own checked-out branch, its own working state, and its own file system presence. An agent editing files in my-project-feat-auth/ cannot touch files in my-project-refactor-api/. They’re physically separate directories.
This is the key property that makes worktrees so useful for parallel agentic development: each agent gets its own sandbox without any extra infrastructure.
The Problem With Shared Working Directories
Before getting into setup, it’s worth being specific about why shared directories fail for multi-agent work.
When two AI agents run in the same working directory:
- File collisions — Both agents may read the same file, generate edits independently, then write back. The second write wins and erases the first agent’s changes. Neither agent knows this happened.
- Branch confusion — If one agent switches branches mid-task (common during planning steps), it changes the filesystem state for the other agent too.
- Context contamination — An agent analyzing the codebase will read uncommitted changes from the other agent’s in-progress work. This creates confusing, inconsistent context that leads to bad decisions.
- Lock conflicts — Some tools (language servers, test runners, build tools) hold file locks. Two agents running the same toolchain in the same directory will fail unpredictably.
None of these are edge cases. They happen regularly and the failures are often silent — the agent just produces wrong output based on corrupted context. Context rot in AI coding agents is already a real problem in single-agent sessions. Shared directories make it dramatically worse.
Setting Up Git Worktrees: Step-by-Step
Prerequisites
- Git 2.5 or later (worktrees have been stable since then)
- A Git repository with at least one commit
- Your AI coding tool of choice (Claude Code, Cursor, etc.)
Step 1: Create Your First Linked Worktree
From your main repository directory, run:
git worktree add ../my-project-feat-auth feat/auth
This creates a new directory (../my-project-feat-auth) and checks out the feat/auth branch into it. If the branch doesn’t exist yet, add -b to create it:
git worktree add -b feat/auth ../my-project-feat-auth main
The -b feat/auth flag creates the new branch starting from main.
Step 2: Add More Worktrees for Additional Agents
Each agent gets its own worktree:
git worktree add -b refactor/api ../my-project-refactor-api main
git worktree add -b fix/payment-bug ../my-project-payment-fix main
Now you have four separate directories — the original plus three linked worktrees — each on a different branch.
Step 3: Verify Your Worktrees
git worktree list
Output:
/home/user/my-project abc1234 [main]
/home/user/my-project-feat-auth def5678 [feat/auth]
/home/user/my-project-refactor-api ghi9012 [refactor/api]
/home/user/my-project-payment-fix ghi9012 [fix/payment-bug]
Each entry shows the directory, the current commit hash, and the branch. This is your at-a-glance view of what’s running where.
Step 4: Launch an Agent in Each Worktree
Open separate terminal windows (or use a terminal multiplexer like tmux) and navigate to each worktree directory. Then launch your AI agent from that directory.
For Claude Code:
# Terminal 1
cd ~/my-project-feat-auth && claude
# Terminal 2
cd ~/my-project-refactor-api && claude
# Terminal 3
cd ~/my-project-payment-fix && claude
Each Claude Code session will see only its own worktree. It can’t see changes being made in other sessions. It can’t accidentally switch branches. It has a clean, isolated working environment.
This is the foundation of running multiple Claude Code sessions simultaneously without interference.
Step 5: Clean Up When Done
When a task is complete, merge the branch and remove the worktree:
# Merge the branch
git checkout main
git merge feat/auth
# Remove the worktree
git worktree remove ../my-project-feat-auth
# Optionally delete the branch
git branch -d feat/auth
Worktrees don’t clean themselves up. Make removal part of your workflow.
How to Structure Tasks Across Multiple Agents
Setting up the worktrees is the easy part. The harder part is deciding how to split work across agents so they’re genuinely parallel — not tangled in the same logic.
Assign Work by Domain, Not by File
The best decomposition for parallel agents is by domain or feature boundary. Avoid splitting work that touches the same files from different directions.
Good splits:
- Agent 1: Authentication module
- Agent 2: Payment processing
- Agent 3: Dashboard UI
Bad splits:
- Agent 1: Add validation to
utils.ts - Agent 2: Refactor error handling in
utils.ts
The second pair will create merge conflicts and possibly confuse each other’s intent. Even with isolated worktrees, you’ll have to resolve conflicts manually when merging.
Use a Shared Task List
One pattern that works well at scale is having a shared task document — a markdown file, a Notion page, a simple todo list — that all agents read from. Each agent picks up a task, marks it in-progress, and marks it done when complete. This prevents duplication of effort.
Claude Code agent teams implement exactly this kind of shared coordination model. The worktree setup handles isolation at the filesystem level; the shared task list handles coordination at the work-allocation level. You need both.
Start Branches From a Clean State
Always create new worktrees from main (or your stable base branch), not from other feature branches. Starting from an in-progress branch makes merge conflicts significantly harder to resolve later, and the agent will have context that’s polluted with half-finished work.
Managing Shared Dependencies Across Worktrees
Each worktree has its own working directory, but it shares the .git folder. This has implications for dependencies.
Node Modules
node_modules is per-worktree by default since each worktree is a separate directory. This means you need to run npm install (or your package manager equivalent) in each worktree separately. It also means more disk space.
For monorepos or large projects, consider symlinking node_modules if your dependencies are identical across branches and you’re confident they won’t conflict. But generally, separate installs are safer.
Environment Files
.env files are typically gitignored, which means they’re not shared automatically across worktrees. Copy your .env to each new worktree directory when you set it up:
cp ~/my-project/.env ~/my-project-feat-auth/.env
Or better, use a .env.shared pattern and symlink it. The key point: don’t assume your environment is available in a new worktree.
Databases and External Services
AI agents often run tests or hit local services. If multiple agents are hitting the same local database simultaneously, you’ll get race conditions and corrupted test results.
Options:
- Use separate test database names per agent (e.g.,
mydb_auth,mydb_api) - Run each agent against a separate Docker container
- Use in-memory databases for test runs
- Separate ports for local dev servers (e.g., 3001, 3002, 3003)
This is the infrastructure layer that most guides skip. Get it right and your agents can truly run in parallel. Skip it and you’ll see flaky tests that have nothing to do with the code.
Worktrees and the Operator Pattern
Some teams go further than just launching independent agents. They use an orchestrator — a “supervisor” agent or script — that spins up worker agents, assigns them tasks, monitors their progress, and collects results.
This is sometimes called the Claude Code operator pattern: one process manages multiple parallel terminals, each running an agent in a separate worktree.
A basic version of this looks like:
#!/bin/bash
# spin-up-agents.sh
TASKS=("feat/auth" "refactor/api" "fix/payment-bug")
for task in "${TASKS[@]}"; do
dir="../my-project-${task//\//-}"
git worktree add -b "$task" "$dir" main
cp .env "$dir/.env"
cd "$dir" && npm install --silent &
cd -
done
echo "Worktrees ready. Launch agents in each directory."
From there, you can automate agent invocation as well. The important thing is that the directory isolation is already handled by the worktree setup. The orchestration layer doesn’t need to solve that problem.
For teams building more complex multi-agent systems, building an AI command center for managing multiple agents covers how to structure the oversight layer on top of the worktree pattern.
Merging Changes Back: The Part That Matters
Running agents in parallel creates value only if you can cleanly integrate their output. Here’s a practical merge workflow.
Review Each Branch Before Merging
Don’t merge agent output blindly. Review the diff:
git diff main..feat/auth
Look for:
- Changes that contradict work happening in other branches
- Unexpected file changes (agents sometimes edit files outside their assigned scope)
- Half-finished implementations the agent didn’t complete
Merge in Dependency Order
If Agent A’s work depends on Agent B’s output, merge B first:
- Review and merge
refactor/api→main - Pull
mainintofeat/authworktree:git pull origin mainfrom that directory - Review and merge
feat/auth→main
This minimizes conflict surface.
Use a Staging Branch for Integration
For larger parallel efforts, create a staging or integration branch. Merge all feature branches there first, run tests, fix conflicts, then merge the clean result to main. This keeps main stable throughout.
git checkout -b integration main
git merge feat/auth
git merge refactor/api
git merge fix/payment-bug
# Run tests here
git checkout main && git merge integration
This approach is common in teams doing split-and-merge patterns with sub-agents, where work fans out and then converges back to a single output.
Common Mistakes and How to Avoid Them
Forgetting to Remove Old Worktrees
Worktrees accumulate. After a few weeks, you may have a dozen stale directories. Run git worktree list periodically and clean up with git worktree remove. Stale worktrees can cause confusing errors when you try to check out the same branch in a new worktree.
Launching Agents Without Confirming the Working Directory
An agent launched from the wrong directory will work on the wrong branch. Always confirm the current directory and branch before starting an agent:
pwd && git branch --show-current
Make this a habit. It takes two seconds and prevents a common failure mode.
Assigning Overlapping Tasks
If two agents are both touching the authentication layer — even if they’re on different branches — you’ll get merge conflicts and possibly conflicting design decisions that are harder to reconcile than conflicts. Task decomposition happens before the agents start, not after.
Ignoring Context Window Health
Long-running agent sessions accumulate context. Eventually the agent’s effective reasoning degrades — a phenomenon covered in detail in what is context rot and how sub-agents fix it. Worktrees solve isolation but not context health. Keep sessions focused on bounded tasks, and don’t let a single agent run indefinitely on an unbounded scope.
How This Fits Into Larger Multi-Agent Architectures
Worktrees are infrastructure — they’re the foundation for more sophisticated patterns. Once you’ve got isolated environments working reliably, you can layer on more complexity.
Agentic coding levels range from single-agent autocomplete all the way up to fully autonomous agent networks. Worktrees become relevant starting around the level where you’re running multiple independent agents on the same project. They’re not the ceiling — they’re the floor.
At higher levels, teams like Stripe (reportedly running thousands of AI-generated pull requests per week) use full AI agent harnesses that include automated code review, test gating, and deployment pipelines. Worktrees are one component of that infrastructure — the part that handles filesystem isolation at the development stage.
The parallel agentic development playbook goes deeper on how to scale from two-agent setups to larger teams, including how to handle task queues, agent monitoring, and output validation.
How Remy Approaches Parallel Development
Remy takes a different angle on this problem. Rather than having developers manage worktrees, branches, and agent coordination manually, Remy’s source of truth is the spec — a structured markdown document that defines what the app does. The code is compiled from that.
This matters for parallel development because coordination happens at the spec level, not the code level. If you’re building auth and someone else is building the payment module, both definitions live in the same spec document. The agent can see both contexts without stepping on either implementation.
You’re not managing which directory to launch an agent from, or which branch to merge first, or whether two agents are touching the same file. The spec is the shared contract. The code is derived output.
If you’re already deep in a worktree-based workflow, that’s a solid setup. But if you’re building a new project and want to avoid the coordination overhead entirely, Remy handles isolation at a higher level of abstraction. Try Remy at mindstudio.ai/remy.
Frequently Asked Questions
What is a git worktree and how does it differ from cloning the repo?
A git worktree is a linked working directory that shares the same .git folder as your main repository. Cloning creates an entirely separate repository copy with its own .git directory and independent history. Worktrees share history, objects, and configuration — they’re just separate checkouts of different branches. This means changes committed in one worktree are immediately visible across all linked worktrees, which is what makes them useful for coordination.
Can two git worktrees check out the same branch at the same time?
No. Git prevents two worktrees from checking out the same branch simultaneously. If you try, you’ll get an error: fatal: 'branch-name' is already checked out at '/path/to/other-worktree'. This is a safety feature — it prevents two agents from working on identical branch state and creating conflicting commits. You must create a new branch for each worktree.
How many AI agents can I realistically run in parallel?
The practical limit depends on your machine’s memory and CPU, your rate limits with the AI provider, and the complexity of your tasks. Most developers find 2–4 parallel agents manageable. Beyond that, the overhead of coordinating tasks, reviewing outputs, and managing merges starts to outweigh the parallelism benefit. Running multiple Claude Code sessions simultaneously offers guidance on staying in the productive range.
Do worktrees work with tools like Cursor or VS Code?
Yes, with caveats. You can open each worktree directory as a separate VS Code workspace or Cursor project. Language servers (TypeScript, ESLint, etc.) will spin up independently for each window. Be aware that some extensions assume a single workspace and may behave unexpectedly when you have multiple instances of the same project open. Test your tooling setup before committing to a large parallel session.
What’s the difference between git worktrees and git stash for managing parallel work?
Git stash lets you temporarily store uncommitted changes and restore them later — but only one state at a time, and only in a single working directory. It’s designed for brief context switching, not parallel work. Worktrees let multiple states exist simultaneously in separate directories. There’s no switching involved; all branches are live and accessible at once. For AI agent parallelism, stash is the wrong tool. Worktrees are the right one.
How do I handle package.json changes across worktrees?
If you update package.json in one worktree (e.g., adding a new dependency), that change lives on that branch. When you merge the branch to main, the change becomes part of main. Other worktrees won’t automatically get the update until they pull from main. Run git pull origin main && npm install in each active worktree after merging significant dependency changes.
Key Takeaways
- Git worktrees give each AI agent a physically isolated directory with its own branch, preventing file collisions and context contamination.
- Create a worktree with
git worktree add -b branch-name ../directory-name base-branchand clean up withgit worktree remove. - Decompose tasks by domain or feature boundary — not by file — to minimize merge conflicts.
- Handle per-worktree dependencies: run
npm installseparately and copy.envfiles manually. - Review agent output before merging; use an integration branch for larger parallel efforts.
- Worktrees solve filesystem isolation but not context window health or task coordination — you need processes for both.
- If you want to skip worktree management entirely, Remy handles coordination at the spec level, where the source of truth is a structured document rather than parallel code branches.