Git Worktrees for Parallel AI Coding Agents: The Complete 2026 Workflow
How to use Git worktrees to run multiple AI coding agents in parallel. Claude Code's worktree flag, common pitfalls, and a clear decision framework.
On this page
You open a terminal, point your AI coding agent at a feature branch, and wait. While it works through one task, your second agent sits idle because both agents would be editing the same files in the same checkout. You're running a million-dollar brain in a single-threaded workflow.
Git worktrees solve this by giving each agent its own working directory, all backed by the same repository. No cloning, no duplicate object databases, no drift between copies. In 2026, this pattern has gone from power-user trick to essential infrastructure for anyone running parallel AI agents.
This tutorial walks through everything: what worktrees are, how to set them up, how to use Claude Code's built-in --worktree flag, and how to avoid the pitfalls that trip up every team in the first week. If you already use Claude Code daily, the Claude Code cheatsheet covers the broader command surface.
What Is a Git Worktree
A git worktree is an additional working directory linked to an existing repository. Your main checkout stays where it is. Each worktree gets its own directory on disk with its own checked-out branch, its own staging area, and its own HEAD. Under the hood, all worktrees share a single .git object database, so there's no duplication of commit history, packfiles, or remote tracking info.
Think of it like having multiple browser tabs open on the same website. Each tab shows a different page, but they all share the same session. Worktrees show different branches, but they all share the same repository.
~/projects/
├── my-app/ # Main checkout (branch: main)
│ ├── .git/ # Full object database lives here
│ ├── src/
│ └── package.json
│
├── my-app-feature-auth/ # Worktree 1 (branch: feature/auth)
│ ├── .git # Tiny file pointing back to main .git
│ ├── src/
│ └── package.json
│
└── my-app-fix-nav/ # Worktree 2 (branch: fix/nav-crash)
├── .git # Tiny file pointing back to main .git
├── src/
└── package.jsonEach worktree directory looks like a full project. You can cd into it, run npm install, start a dev server, and work normally. The key difference: the .git entry in a worktree is a small text file (not a directory) that points back to the main repository's .git folder. This pointer is what keeps everything in sync.
Commits made in any worktree are immediately visible from any other worktree. Push from worktree 2, and worktree 1 sees the new remote state on the next git fetch. There's no merging between clones, no rebasing to catch up, and no risk of divergent object databases.
Why Worktrees Matter for AI Coding Agents
Human developers can context-switch between branches with git stash and git checkout. It's annoying, but it works because you only have one pair of hands. AI coding agents are different. You want multiple agents running simultaneously, each modifying files, running tests, and staging commits. If they share a single checkout, they'll destroy each other's work.
The conflict problem shows up in three specific ways when agents share a working directory. If you're already running multi-agent workflows (like the CrewAI pipeline covered here), worktrees are the filesystem layer that makes parallel execution safe.
- <strong>File overwrites.</strong> Agent A edits
src/auth.tswhile Agent B edits the same file. One write clobbers the other. Neither agent knows it happened. - <strong>Package manifest races.</strong> Agent A adds a dependency to
package.jsonand runsnpm install. Agent B does the same thing a second later. The lockfile is now a merge conflict waiting to happen, andnode_modulesis in an undefined state. - <strong>Context pollution.</strong> Agent A's half-finished changes appear in Agent B's file reads. Agent B starts "fixing" code that was intentionally mid-refactor, creating a feedback loop of corrections to non-problems.
With worktrees, each agent operates in complete filesystem isolation. Agent A's worktree has its own node_modules, its own .env, and its own set of modified files. Agent B can't see or interfere with any of it. Both agents commit to the same repository, so their work converges naturally when you merge their branches.
Setting Up Worktrees Step by Step
This walkthrough creates two parallel worktrees from an existing repository, one for a feature branch and one for a bugfix. By the end, you'll have three working directories (main plus two worktrees) ready for three separate agents or terminals. If you want to skip the manual steps and generate the right commands instantly, try the Worktree Command Generator.
- 1
Create the Branches You Want to Work On
Worktrees check out an existing branch (or create a new one on the fly). Start by making sure the branches exist. If they don't yet, create them from
main.bashcd ~/projects/my-app # Create two branches from main git branch feature/auth git branch fix/nav-crash - 2
Add a Worktree for Each Branch
The
git worktree addcommand takes a path and a branch name. The path is where the new working directory will live on disk. Convention: put worktrees next to (not inside) the main checkout, using a naming pattern that includes the project name.bash# From the main checkout directory git worktree add ../my-app-feature-auth feature/auth git worktree add ../my-app-fix-nav fix/nav-crashEach command creates a new directory, checks out the specified branch, and links it back to the main repository's object database. Git will refuse if the branch is already checked out somewhere (including in the main checkout). If you hit that, see the troubleshooting table below.
To create a new branch and worktree in one shot, use the
-bflag.bash# Create a new branch AND its worktree in one command git worktree add -b feature/payments ../my-app-payments - 3
Verify Your Worktrees Are Active
List all active worktrees to confirm everything is linked correctly. The output shows the path, the HEAD commit, and the branch for each worktree.
bashgit worktree listtext — Expected output/Users/you/projects/my-app a1b2c3d [main] /Users/you/projects/my-app-feature-auth a1b2c3d [feature/auth] /Users/you/projects/my-app-fix-nav a1b2c3d [fix/nav-crash]All three point to the same commit because the branches were just created from
main. As each branch accumulates commits, the HEAD hashes will diverge, but the underlying object database remains shared. - 4
Install Dependencies in Each Worktree
Each worktree has its own filesystem, which means its own
node_modules(or.venv,vendor/, etc.). You need to install dependencies separately in each one. This is the main disk cost of worktrees, but it's also what guarantees isolation.bashcd ../my-app-feature-auth && npm install cd ../my-app-fix-nav && npm install - 5
Point a Separate Agent at Each Worktree
Open a terminal for each worktree and start your AI agent in that directory. Each agent sees only its own branch's files. Here's how that looks with Claude Code.
bash — Terminal 1cd ~/projects/my-app-feature-auth claude "Add JWT authentication to the login endpoint"bash — Terminal 2cd ~/projects/my-app-fix-nav claude "Fix the navigation crash when the user array is empty"Both agents run simultaneously. Agent 1 edits files in
my-app-feature-auth/, Agent 2 edits files inmy-app-fix-nav/. No file conflicts, no lockfile races, no context bleed. - 6
Clean Up Worktrees After Merging
Once a branch is merged (or abandoned), remove its worktree. This deletes the working directory and unlinks it from the repository. The branch itself stays in git history; only the filesystem checkout is removed.
bash# Remove a specific worktree git worktree remove ../my-app-feature-auth # Or, if you already deleted the directory manually: git worktree pruneRun
git worktree pruneperiodically to clean up stale references from worktrees whose directories were deleted outside of git. This is harmless to run even if nothing needs pruning.
Using Claude Code's Native Worktree Support
Claude Code (version 1.0.20+) has a built-in --worktree flag that automates the entire worktree lifecycle. Instead of manually running git worktree add, installing dependencies, and navigating to the directory, you pass a single flag and Claude handles the rest.
The flag creates a new worktree, sets up the branch, changes into the worktree directory, and starts the agent session there. When the session ends, the worktree persists so you can review the changes, merge the branch, or continue working on it later.
# From your main checkout
claude --worktree "Add rate limiting to the API endpoints"Claude Code generates a branch name from the task description (something like feature/add-rate-limiting-api-endpoints), creates the worktree in a sibling directory, and starts the session inside it. You can run multiple of these in parallel, each in its own terminal.
# Terminal 1
claude --worktree "Add rate limiting to the API endpoints"
# Terminal 2
claude --worktree "Migrate user table to use UUIDs"
# Terminal 3
claude --worktree "Write integration tests for the payment flow"Each session is fully isolated. Agent 1 can install packages, run tests, and modify config files without any interference from Agent 2 or 3. When all three finish, you review each branch independently and merge them through your normal PR workflow.
Reviewing and Merging Worktree Branches
After an agent finishes in a worktree, the branch is ready for review like any other feature branch. You can open a PR from it, diff it against main, or inspect the changes locally.
# From the main checkout, see what the agent changed
git diff main..feature/add-rate-limiting-api-endpoints
# Or push and open a PR
cd ~/projects/my-app-rate-limiting
git push -u origin feature/add-rate-limiting-api-endpointsOnce merged, remove the worktree with git worktree remove and delete the remote branch. The object data stays in the shared .git database (it's part of the merged history now), and the only thing that disappears is the directory on disk.
Common Problems and Fixes
Most worktree issues fall into a small set of predictable problems. This table covers what you'll hit in the first week and how to fix each one.
| Problem | Cause | Fix |
|---|---|---|
| "fatal: branch is already checked out" | Git prevents the same branch from being checked out in two worktrees simultaneously to avoid conflicting index states. | Check out a different branch in the main worktree first (<code>git checkout main</code>), then retry. Or create the worktree with <code>-b</code> to make a new branch. |
| Stale <code>.git/index.lock</code> | A crashed git process (or a killed agent) left a lock file behind. No git operations work until it's removed. | Delete the lock file: <code>rm .git/index.lock</code> (in the affected worktree). Verify no git process is actually running first with <code>ps aux | grep git</code>. |
| <code>.env</code> files missing in worktrees | Worktrees create a fresh checkout from the branch. <code>.env</code> files are gitignored, so they don't exist in the new directory. | Copy them manually: <code>cp ~/projects/my-app/.env ~/projects/my-app-feature-auth/.env</code>. Or use a symlink if all worktrees should share the same config. |
| <code>node_modules</code> reinstall required | Each worktree has its own filesystem. There's no shared <code>node_modules</code> across worktrees. | Run <code>npm install</code> (or <code>pnpm install</code>) in each worktree after creation. Use pnpm's content-addressable store to reduce disk usage. |
| IDE doesn't recognize the worktree | Some editors (VS Code, JetBrains) don't auto-detect worktree relationships. They treat each directory as an unrelated project. | Open the worktree directory directly as a project root. VS Code's multi-root workspaces can group worktrees, but most developers find separate windows simpler. |
| Worktree directory deleted but git still tracks it | Deleting a worktree's directory with <code>rm -rf</code> doesn't clean up git's internal references in <code>.git/worktrees/</code>. | Run <code>git worktree prune</code> from the main checkout. This cleans up stale worktree metadata. |
When Worktrees Help vs When They Add Overhead
Worktrees are not always the right call. They add disk usage (one node_modules per worktree), require dependency installation per directory, and introduce a mental model that not every teammate will be familiar with. Here's a framework for deciding.
| Use worktrees when | Skip worktrees when | |
|---|---|---|
| Parallel agents | You're running 2+ AI agents simultaneously on different tasks in the same repo | You only run one agent at a time, sequentially |
| Task isolation | Tasks touch overlapping files (shared components, config, dependencies) | Tasks are in completely separate repos or microservices |
| Review workflow | You want each agent's work on a separate branch for independent PR review | All changes should land in a single commit on one branch |
| Project size | Repo is large and a full git clone takes minutes (monorepo, heavy history) | Repo is small and cloning takes seconds |
| Disk budget | You can afford the disk space for one node_modules per worktree (or use pnpm) | Disk space is extremely constrained (small VM, CI runner with limited storage) |
| Branch lifetime | Feature branches live for hours to days, then merge and get cleaned up | You're doing throwaway experiments you'll never merge |
Worktrees vs Alternatives
Worktrees aren't the only way to give agents isolated environments. Here's how the main options compare across the dimensions that matter most for parallel AI agent workflows.
| Git Worktree (manual CLI) | Claude Code --worktree flag | |
|---|---|---|
| Setup effort | 3 to 4 commands per worktree (add, cd, install deps, copy .env) | One flag (--worktree) handles branch creation and directory setup |
| Branch naming | You choose the branch name manually | Auto-generates a descriptive branch name from your prompt |
| Dependency install | Manual per worktree | Manual per worktree (not automated by the flag) |
| Portability | Works with any tool, any editor, any agent | Claude Code only |
| Cleanup | Manual git worktree remove | Manual git worktree remove |
| Approach | Shared history | Disk cost | Setup time | Best for |
|---|---|---|---|---|
| Git worktree | Yes, single object database | Low (only working files + deps duplicated) | Seconds | Parallel agents in the same repo, fast branch switching |
| Git clone | No, full copy of object database | High (entire .git/ duplicated) | Seconds to minutes depending on repo size | Completely independent environments, CI runners |
| Git stash + checkout | Yes | None (single directory) | Seconds | Sequential work only, not parallel |
| Docker/container per agent | Depends on mount setup | High (full OS layer per container) | Minutes | Reproducible environments, complex dependency isolation |
Git Worktree Quick Reference Card
Keep this table handy. It covers every git worktree subcommand you'll use in a parallel agent workflow.
| Command | What it does |
|---|---|
| <code>git worktree add ../path branch-name</code> | Creates a new worktree directory and checks out the specified branch. |
| <code>git worktree add -b new-branch ../path</code> | Creates a new branch and a worktree for it in one command. |
| <code>git worktree add -b new-branch ../path origin/main</code> | Creates a new branch from a specific starting point with a worktree. |
| <code>git worktree list</code> | Lists all active worktrees with their paths, HEAD commits, and branches. |
| <code>git worktree remove ../path</code> | Deletes the worktree directory and unlinks it from the repository. |
| <code>git worktree remove --force ../path</code> | Force-removes a worktree even if it has uncommitted changes. |
| <code>git worktree prune</code> | Cleans up stale worktree metadata from manually deleted directories. |
| <code>git worktree lock ../path</code> | Prevents a worktree from being pruned (useful for worktrees on removable drives). |
| <code>git worktree unlock ../path</code> | Removes the prune lock from a previously locked worktree. |
| <code>git worktree move ../old-path ../new-path</code> | Moves a worktree to a different directory without unlinking it. |
Frequently Asked Questions
What is a git worktree?
A git worktree is an additional working directory attached to an existing repository. It lets you check out a different branch in a separate folder while sharing the same commit history, objects, and remote configuration as the main checkout. You create one with git worktree add and remove it with git worktree remove.
Worktrees have been part of git since version 2.5 (released in 2015), but they've become much more relevant in 2026 as developers run multiple AI coding agents in parallel, each needing its own isolated filesystem.
How do git worktrees differ from git clone?
The core difference is the object database. A git clone creates a completely independent copy of the entire repository, including all commit history, packfiles, and refs. A worktree creates only a new working directory and links it back to the original repository's .git folder. No history is duplicated.
| Worktree | Clone | |
|---|---|---|
| Object database | Shared with main checkout | Fully independent copy |
| Disk usage | Working files + deps only | Full .git/ + working files + deps |
| Commits visible across copies | Instantly | After push/pull |
| Setup time (large repo) | Seconds | Minutes |
| Can diverge from source | No, same repo | Yes, fully independent |
For parallel AI agents on the same project, worktrees are almost always the better choice. Clones make sense when you need a fully independent environment (different remotes, different hooks, different git config) or when you're working on a CI runner that shouldn't modify the source checkout.
How do I fix a stale worktree lock file?
If a git process crashes (or an AI agent is killed mid-operation), it can leave behind an index.lock file that blocks all subsequent git operations in that worktree. The fix is straightforward: delete the lock file. But first, confirm that no git process is actually running.
# Check for running git processes
ps aux | grep git
# If nothing is running, remove the lock
rm ~/projects/my-app-feature-auth/.git/index.lockCan I use worktrees with multiple AI agents at once?
Yes, and this is the primary use case driving worktree adoption in 2026. Create one worktree per agent, each on its own branch. Point each agent at its worktree directory and let them run in parallel. They can't interfere with each other because they have separate working directories, separate staging areas, and separate node_modules. For a deeper look at how to structure multi-agent workflows, see the multi-agent AI coding workflow guide.
# Create three worktrees for three agents
git worktree add -b agent/auth ../app-auth
git worktree add -b agent/api ../app-api
git worktree add -b agent/tests ../app-tests
# Start each agent in its own terminal
cd ../app-auth && claude "Implement OAuth2 login"
cd ../app-api && claude "Add pagination to the /users endpoint"
cd ../app-tests && claude "Write E2E tests for checkout flow"Each agent works independently. When they finish, review each branch and merge them separately through your normal PR process.
How do I handle .env files in worktrees?
Since .env files are typically gitignored, they don't exist in newly created worktrees. You have three options, depending on how your environment config works.
- <strong>Copy manually.</strong> Run
cp ~/projects/my-app/.env ~/projects/my-app-feature-auth/.envafter creating each worktree. Simple, but easy to forget. - <strong>Symlink.</strong> Create a symlink so all worktrees share the same
.env:ln -s ~/projects/my-app/.env ~/projects/my-app-feature-auth/.env. Good when all environments use the same config. - <strong>Automate with a script.</strong> Write a small shell function that wraps
git worktree addand copies your.env, installs dependencies, and any other per-worktree setup in one command.
# Add to your .zshrc or .bashrc
worktree-new() {
local branch=$1
local dir="../$(basename $(pwd))-${branch//\//-}"
git worktree add -b "$branch" "$dir"
cp .env "$dir/.env" 2>/dev/null
echo "Worktree created at $dir"
echo "Run: cd $dir && npm install"
}
# Usage: worktree-new feature/authThe helper function approach scales best. Once you've set it up, creating a fully configured worktree is a single command.
Is there a limit to how many worktrees I can create?
Git imposes no hard limit on the number of worktrees. The practical limit is your disk space (each worktree needs its own working files and dependencies) and your ability to manage them. Most developers working with parallel AI agents find 2 to 5 concurrent worktrees comfortable. Beyond that, tracking which worktree has which task becomes harder than the parallelism is worth.
Run git worktree list regularly and prune finished worktrees with git worktree remove. Leftover worktrees that nobody remembers creating are the most common source of "why is this branch locked?" errors.
Related Articles
Claude Code Cheatsheet: Commands, Hooks & Subagents
The complete Claude Code reference: every slash command, keyboard shortcut, hook, subagent, and CLAUDE.md tip, with real examples for developers.
Multi-Agent AI Coding Workflow: Step-by-Step (2026)
Build a 3-agent AI coding workflow with CrewAI and Python. One agent writes, one reviews, one writes tests. Full code included.