Git worktrees let you check out several branches of one repository into separate folders at once, so each AI coding agent edits its own copy and none of them overwrite each other. This guide covers the git commands, Claude Code's built-in --worktree flag, environment files, ports, merging the results and cleaning up.
- One agent per worktree, one branch per task:
git worktree add ../app-auth -b feat/authgives an agent its own folder and branch that share one repository history. - Claude Code creates worktrees for you with
claude --worktree <name>, under.claude/worktrees/, on a branch namedworktree-<name>. - A worktree is a fresh checkout: install dependencies there and copy gitignored files such as
.env, which Claude Code automates with a.worktreeincludefile. - Give parallel agents tasks that touch different files, merge one pull request at a time, and remove worktrees with
git worktree removewhen the branch is merged.
What are git worktrees for AI agents?
A git worktree is an extra working directory attached to the same repository, with its own checked-out branch. For AI agents, that means each agent gets its own folder of files to edit while all of them share one history, so you can run three agents on three tasks without them overwriting each other's changes.
Without worktrees, parallel agents in one folder step on each other constantly. Agent A edits auth.ts while agent B runs the tests, which now fail because of A's half-finished change. Agent B "fixes" the failure by reverting A's work. Both commit to whatever branch happens to be checked out. Worktrees remove that whole class of problem.
The git documentation describes the split precisely: a new worktree is linked to the repository, "sharing everything except per-worktree files such as HEAD, index, etc." In practice:
| Shared across worktrees | Separate per worktree |
|---|---|
Commits, branches and tags (refs under refs/) | The checked-out files |
| Remotes and repository config | HEAD (which branch is checked out) |
| Stashes and fetch results | The index (staged changes) |
Untracked and gitignored files such as .env, node_modules, build output |
That last row is where most first-time setups break, and it gets its own section below.
How do you run parallel agents with plain git worktrees?
You create one worktree per task with git worktree add, start an agent inside each folder, and let each one commit to its own branch. This works with any coding agent: Claude Code, Codex CLI, Gemini CLI, Aider or anything else that runs in a directory.
Commit or stash your current work so the main checkout is clean.
Create a worktree per task, each on a new branch, next to the main folder:
terminal cd ~/code/appgit worktree add ../app-auth -b feat/authgit worktree add ../app-billing -b fix/billing-roundinggit worktree listSet up each worktree: install dependencies and copy local config (see the next section).
Start one agent per worktree, each in its own terminal or tmux window:
terminal cd ../app-auth && claude # terminal 1cd ../app-billing && claude # terminal 2Give each agent a self-contained task with clear acceptance criteria, then let them work.
Review each branch separately, push it and open a pull request.
Remove the worktree once its branch is merged:
terminal git worktree remove ../app-authgit branch -d feat/auth
Git adds a safety net for free: by default, git worktree add refuses to check out a branch that is already checked out in another worktree. Two agents cannot end up committing to the same branch by accident unless you pass --force.
Put worktrees next to the repository (../app-auth) or in a gitignored folder inside it. A worktree nested in the main checkout without a gitignore rule shows up as a pile of untracked files.
How does Claude Code's --worktree flag work?
Claude Code can create and manage worktrees itself: claude --worktree <name> (or -w) makes a new worktree and starts the session inside it. According to the Claude Code worktree docs, the worktree goes under .claude/worktrees/<name>/ at the repository root, on a new branch named worktree-<name>.
claude --worktree feature-auth # terminal 1claude --worktree fix-billing # terminal 2claude --worktree "#1234" # or start from an open pull requestDetails worth knowing, as of October 2026:
- Base branch. New worktrees branch from the repository's default branch on the remote by default. Set
worktree.baseRefto"head"in settings to branch from your current localHEADinstead, for example when agents must build on unpushed work. - The repository needs at least one commit, because a worktree is created from an existing commit.
- Cleanup on exit. When you leave an interactive worktree session, Claude Code checks for changes and new commits. A clean, unnamed worktree is removed with its branch; one with work in it triggers a prompt to keep or remove it, and keeping it prints a
claude --worktree <name> --resumecommand to come back later. - Non-interactive runs (
claude -p --worktree ...) are not cleaned up automatically; remove those worktrees withgit worktree remove. - Isolation is enforced. While a session runs in a worktree, Claude Code blocks file edits and git commands that target the main checkout.
- Gitignore it. The docs recommend adding
.claude/worktrees/to.gitignore.
You can also ask Claude mid-session to "work in a worktree", and it creates one with its own worktree tool.
Worktrees for subagents
Subagents that edit files in parallel can each get a temporary worktree. Ask Claude to "use worktrees for your agents", or make it permanent for a custom subagent with isolation: worktree in its frontmatter:
---name: refactorerdescription: Applies mechanical refactors across many filesisolation: worktree---Apply the requested refactor across every affected file, then run the testsand report the results.Claude Code removes a subagent's worktree automatically when it finishes without changes. More on designing subagents is in our Claude Code subagents guide.
Other tools have their own built-in worktree modes; the Codex app and Cursor both offer ways to run agents in isolated worktrees. Check each tool's current documentation, because these features change often.
How do you set up dependencies and .env files in a new worktree?
A new worktree contains only tracked files, so anything gitignored (.env, node_modules, virtual environments, build caches, local databases) is missing until you create or copy it. This is the most common reason an agent in a fresh worktree reports that "the tests are broken" when nothing is wrong with the code.
Handle it in one of three ways.
Copy env files automatically with .worktreeinclude
Claude Code reads a .worktreeinclude file at the project root, written in .gitignore syntax. Files that match a pattern and are gitignored get copied into every worktree Claude Code creates, including subagent worktrees:
.env.env.localconfig/secrets.jsonTracked files are never duplicated by this, because only gitignored matches are copied.
Use a setup script for everything else
For plain git worktrees, or for steps that copying can't cover, keep a small script in the repository:
#!/usr/bin/env bashset -euo pipefailname="$1"root="$(git rev-parse --show-toplevel)"path="$root/../$(basename "$root")-$name"git worktree add "$path" -b "agent/$name"cp "$root/.env" "$path/.env" 2>/dev/null || truecd "$path"npm ciecho "Worktree ready: $path"Tell the agent in CLAUDE.md or AGENTS.md
Add a line to your instructions file such as "In a fresh worktree, run npm ci before running tests." Agents follow this reliably, and it also covers worktrees created by tools you don't control.
Copying .env into every worktree multiplies the places your secrets live. Use development credentials with limited scope, never production keys, for agent work.
How do you avoid port and database conflicts between agents?
Parallel agents share one machine, so anything that binds a fixed port or uses a single local database will collide even though the files are separate. Two dev servers both want port 3000; two test runs both reset the same Postgres database.
Practical fixes:
| Conflict | Fix |
|---|---|
| Dev server ports | Read the port from an env variable and give each worktree its own value (PORT=3001, 3002) in its .env |
| Shared local database | One database per worktree (app_auth, app_billing), or a per-worktree SQLite file |
| Docker Compose projects | Set a distinct COMPOSE_PROJECT_NAME per worktree so container names don't clash |
| Test runners with fixed ports | Configure them to use random free ports |
| Shared caches (build tools) | Usually fine to share; isolate only if you see corrupted or stale results |
If your project can't run two instances side by side, say so in the task: "Don't start the dev server; run only unit tests." Agents respect constraints they are told about.
How do you split work so parallel agents don't conflict?
Worktrees prevent agents from editing the same files at the same time, but they don't prevent merge conflicts later. Splitting tasks well is what makes parallel work pay off.
Good parallel tasks:
- Touch different parts of the codebase (an API endpoint, a UI page, a migration script).
- Have clear acceptance criteria the agent can check itself, such as "all tests in
billing/pass and a new test covers rounding to cents." - Are independent: neither needs the other's result to start.
Bad parallel tasks:
- Two features that both rewrite the same central module or shared types.
- A refactor running alongside feature work in the same files.
- A task that depends on another task's unmerged branch (run these in sequence, or use
worktree.baseRef: "head"deliberately).
A task brief that works well for a worktree agent:
You are working in your own git worktree on branch fix/billing-rounding.Task: invoice totals are rounded per line item instead of on the total.Fix it in src/billing/ only. Don't change public function signatures.Done when: npm test -- billing passes, a new test covers a 3-line invoicewith fractional cents, and you've committed with a clear message.Don't push and don't open a PR; I'll review the branch first.Our guide on how to write tasks for AI coding agents has more templates.
How do you merge the work and clean up worktrees?
Merge parallel branches one at a time through normal pull requests, updating each remaining branch against the new main before merging it. Treat every agent branch like a pull request from a new colleague: review the diff, run the tests, then merge.
A routine that keeps things tidy:
- Review the first finished branch, push it and open a pull request. Use AI code review as a first pass if you like, but read the diff yourself.
- Merge it into main.
- Update the next branch: in its worktree, run
git fetchandgit rebase origin/main(or merge main), or ask the agent in that worktree to do it and fix any conflicts. - Repeat for each remaining branch.
- Clean up merged worktrees and branches.
Useful cleanup commands:
git worktree list # see every worktree and its branchgit worktree remove ../app-auth # remove a clean worktreegit worktree remove --force ../app-auth # also discards uncommitted changesgit worktree prune # forget worktrees whose folders were deletedgit branch --merged main # branches safe to deletePer the git docs, git worktree remove refuses to remove a worktree with uncommitted changes or untracked files unless you add --force. If you deleted a worktree folder by hand, git worktree prune clears the stale record. A locked worktree (Claude Code locks the worktrees of running agents) needs --force twice to remove, so wait until the agent has finished.
Where should parallel agents run?
Parallel agents run fine on a laptop for an hour, but they compete for memory and CPU with everything else you do, and they all stop when the laptop sleeps. Each agent also runs installs, builds and test suites, so four agents can mean four parallel npm ci runs.
Options, from lightest to most hands-off:
- Your laptop with tmux, for short sessions you watch.
- A remote dev server or VPS, where agents keep running after you disconnect; see our guide to background coding agents.
- A hosted box such as Orkio, which keeps agents like Claude Code running on an always-on, isolated cloud server, clones your repositories, and opens pull requests you review later from your phone or the web.
Wherever they run, the rules stay the same: one task per agent, one branch per worktree, and a human review before anything merges.
A checklist for your first parallel run
Try this with two agents before scaling up:
- Add
.claude/worktrees/(or your worktree folder) to.gitignore. - Create a
.worktreeincludeor setup script for.envand dependencies. - Make dev ports and database names configurable per worktree.
- Pick two tasks that touch different directories and write a brief for each.
- Start each agent in its own worktree with
claude --worktree <name>orgit worktree add. - Review, merge one, rebase the other, merge it.
- Run
git worktree listand remove everything that's merged.
If both merges went smoothly, add a third agent. If you spent the time untangling conflicts, improve the task split before adding more parallelism.
Frequently asked questions
How many AI agents can I run in parallel with worktrees?
Git itself has no practical limit; the limits are your machine's memory and CPU, your model usage limits, and how many diffs you can review. Most people find two to four parallel agents manageable, because each finished task still needs a human review.
Do git worktrees use a lot of disk space?
Each worktree has its own copy of the working files but shares the repository's history and objects, so the checkout itself is cheap. Dependencies are the real cost: a separate node_modules or virtual environment per worktree can take far more space than the code, so a package manager with a shared store helps.
Can two worktrees use the same branch?
No, not by default. Git refuses to check out a branch that is already checked out in another worktree, unless you pass --force. This is a useful safety net that stops two agents from committing to the same branch.
What is the difference between a worktree and a clone?
A clone is a fully separate repository with its own history and remotes. A worktree is an extra working folder attached to an existing repository, sharing its refs and objects, so a commit made in one worktree is instantly visible as a branch in all the others.
Do subagents need their own worktrees?
Only if they edit files in parallel. Read-only subagents that research or review can share a checkout. In Claude Code you can give a custom subagent its own temporary worktree by adding isolation: worktree to its frontmatter.


