Dev Encyclopedia
ArticlesToolsAbout

Get notified when new content drops

No spam. Just new articles, tools, and updates straight to your inbox.

Dev Encyclopedia

A reference for builders

Content

  • Articles
  • Tools
  • About
  • Contact

Connect

  • support@devencyclopedia.com
  • RSS Feed

Legal

  • Privacy Policy
  • Terms of Service
  • Disclaimer

© 2026 Dev Encyclopedia

Back to top ↑
  1. Home
  2. /Blog
  3. /Git Worktrees for Parallel AI Coding Agents: The Complete 2026 Workflow
devops14 min read

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.

Zeeshan Tofiq
Zeeshan Tofiq
June 26, 2026
On this page

On this page

  • What Is a Git Worktree
  • Why Worktrees Matter for AI Coding Agents
  • Setting Up Worktrees Step by Step
  • Using Claude Code's Native Worktree Support
  • Common Problems and Fixes
  • When Worktrees Help vs When They Add Overhead
  • Worktrees vs Alternatives
  • Git Worktree Quick Reference Card
  • Frequently Asked Questions

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.

💡 TL;DR

Run git worktree add ../my-feature feature-branch to create an isolated working directory for any branch. Point a separate AI agent at each worktree. They share history and objects but never touch each other's files. Claude Code's --worktree flag automates this entire setup.

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.

text — Directory structure with two worktrees
~/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.json

Each 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.ts while 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.json and runs npm install. Agent B does the same thing a second later. The lockfile is now a merge conflict waiting to happen, and node_modules is 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.

⚠ Stashing is not a solution

Some workflows try to solve this with git stash before switching agents. This breaks down immediately: stashing is a blocking, sequential operation that defeats the purpose of parallel execution. Worktrees are the only built-in git mechanism that gives you truly concurrent branch access.

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. 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.

    bash
    cd ~/projects/my-app
    
    # Create two branches from main
    git branch feature/auth
    git branch fix/nav-crash

    ℹ Info

    You can also create a branch and a worktree in one command (shown in step 2). Creating the branches first just makes the example clearer.

  2. 2

    Add a Worktree for Each Branch

    The git worktree add command 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-crash

    Each 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 -b flag.

    bash
    # Create a new branch AND its worktree in one command
    git worktree add -b feature/payments ../my-app-payments
  3. 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.

    bash
    git worktree list
    text — 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. 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.

    bash
    cd ../my-app-feature-auth && npm install
    cd ../my-app-fix-nav && npm install

    💡 Tip

    If disk space is a concern, tools like pnpm use a content-addressable store that deduplicates packages across directories. Worktrees with pnpm share most of the actual package bytes on disk.

  5. 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 1
    cd ~/projects/my-app-feature-auth
    claude "Add JWT authentication to the login endpoint"
    bash — Terminal 2
    cd ~/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 in my-app-fix-nav/. No file conflicts, no lockfile races, no context bleed.

  6. 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 prune

    Run git worktree prune periodically 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.

bash — Start a Claude Code session in a new worktree
# 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.

bash — Running three agents in parallel with worktrees
# 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.

ℹ How the worktree flag differs from manual setup

The --worktree flag does three things the manual approach doesn't: it auto-generates a descriptive branch name from your prompt, it copies your CLAUDE.md project instructions into the worktree, and it sets the worktree as the session's working directory without you needing to cd. You still need to install dependencies manually if your project requires it.

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.

bash
# 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-endpoints

Once 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.

ProblemCauseFix
"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 worktreesWorktrees 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 requiredEach 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 worktreeSome 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 itDeleting 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 whenSkip worktrees when
Parallel agentsYou're running 2+ AI agents simultaneously on different tasks in the same repoYou only run one agent at a time, sequentially
Task isolationTasks touch overlapping files (shared components, config, dependencies)Tasks are in completely separate repos or microservices
Review workflowYou want each agent's work on a separate branch for independent PR reviewAll changes should land in a single commit on one branch
Project sizeRepo is large and a full git clone takes minutes (monorepo, heavy history)Repo is small and cloning takes seconds
Disk budgetYou 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 lifetimeFeature branches live for hours to days, then merge and get cleaned upYou'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 effort3 to 4 commands per worktree (add, cd, install deps, copy .env)One flag (--worktree) handles branch creation and directory setup
Branch namingYou choose the branch name manuallyAuto-generates a descriptive branch name from your prompt
Dependency installManual per worktreeManual per worktree (not automated by the flag)
PortabilityWorks with any tool, any editor, any agentClaude Code only
CleanupManual git worktree removeManual git worktree remove
Comparison of isolation strategies for parallel AI coding agents
ApproachShared historyDisk costSetup timeBest for
Git worktreeYes, single object databaseLow (only working files + deps duplicated)SecondsParallel agents in the same repo, fast branch switching
Git cloneNo, full copy of object databaseHigh (entire .git/ duplicated)Seconds to minutes depending on repo sizeCompletely independent environments, CI runners
Git stash + checkoutYesNone (single directory)SecondsSequential work only, not parallel
Docker/container per agentDepends on mount setupHigh (full OS layer per container)MinutesReproducible 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.

CommandWhat 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.

WorktreeClone
Object databaseShared with main checkoutFully independent copy
Disk usageWorking files + deps onlyFull .git/ + working files + deps
Commits visible across copiesInstantlyAfter push/pull
Setup time (large repo)SecondsMinutes
Can diverge from sourceNo, same repoYes, 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.

bash
# Check for running git processes
ps aux | grep git

# If nothing is running, remove the lock
rm ~/projects/my-app-feature-auth/.git/index.lock

⚠ Warning

Never delete index.lock while a git process is genuinely running. The lock exists to prevent concurrent writes to the index. Removing it from under an active process can corrupt your staging area.

Do worktrees share the same git history?

Yes. All worktrees linked to the same repository share a single object database, which means they share all commits, trees, blobs, and tags. A commit made in one worktree is immediately visible in the git log of any other worktree (once you check out or reference the branch it was made on).

This shared history is why worktrees are so much faster to create than clones and why they use far less disk space. The only things that are per-worktree are the working files, the staging area (index), and the checked-out branch pointer (HEAD).

Can 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.

bash
# 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/.env after 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 add and copies your .env, installs dependencies, and any other per-worktree setup in one command.
bash — Example: worktree helper function
# 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/auth

The 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.

Zeeshan Tofiq

Zeeshan Tofiq

Full Stack Developer

Full stack developer with over 6 years of experience building production applications. Writes practical guides on JavaScript, TypeScript, React, Node.js, and cloud infrastructure. Focused on helping developers solve real problems with clean, maintainable code.

Enjoyed this article?

Get practical dev guides, tool updates, and new articles delivered straight to your inbox. No spam, unsubscribe anytime.

Related Articles

ai tools

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.

Jun 6, 2026·10 min read
ai tools

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.

Jun 7, 2026·10 min read

On this page

  • What Is a Git Worktree
  • Why Worktrees Matter for AI Coding Agents
  • Setting Up Worktrees Step by Step
  • Using Claude Code's Native Worktree Support
  • Common Problems and Fixes
  • When Worktrees Help vs When They Add Overhead
  • Worktrees vs Alternatives
  • Git Worktree Quick Reference Card
  • Frequently Asked Questions
Advertisement