Claude Code

Running several Claude Code agents on one repo with worktrees

How to run several Claude Code sessions on one repo without collisions: the --⁠worktree flag, .env files, cleanup, and what a worktree doesn't isolate.

Orchestrated by Jon Phillips

Researched and written by Claude

Published 11 min read

On this page

To run several Claude Code agents on one repository, give each one its own git worktree: a second folder checked out from the same repository, on its own branch. Start one with claude --worktree <name>, and Claude Code creates the folder, makes the branch, and starts the session inside it. Two sessions in two worktrees can't edit each other's files or commit onto each other's branch.

That's the short version. The longer one covers the parts that trip people up: getting your .env file into the new folder, which branch a worktree starts from, what Claude Code cleans up and what it leaves behind, and the things a worktree doesn't isolate at all, like your database and your dev server's port. Everything here comes from Anthropic's worktrees guide and git's own documentation, checked against Claude Code 2.1.286 on September 30, 2026, and we ran the commands in a test repository before writing them down.

I run several Claude Code sessions on client sites every day, often alongside Codex. Worktrees are what let that happen without one session's work landing in another's.

What is a git worktree?

A git repository normally has one working folder, the one you cloned. A worktree is an extra working folder attached to the same repository. Git's documentation puts it in one line: "A git repository can support multiple working trees, allowing you to check out more than one branch at a time."

Each worktree has its own files and its own checked-out branch. They all share one history, so a commit made in one worktree is visible from every other one straight away, with no push or pull between them. It's much lighter than cloning the repository twice.

Why does each agent need its own worktree?

Because the current branch belongs to the folder, not to the session. Two Claude Code sessions opened in the same folder share one set of files and one current branch, so:

  • Their edits collide. Both sessions edit the same files on disk, and each one's changes appear in the other's working tree halfway through its task.
  • Their commits land on the same branch. When session A switches to feature-a and session B then switches to feature-b, session A's next commit goes on feature-b. Nothing warns either of them.
  • Their tests run against a mix of both. A test run in one session picks up the other's half-finished edits.

Anthropic's summary, from its guide to running agents in parallel: "Worktrees give each session a separate git checkout, so parallel sessions never edit the same files."

How do you start Claude Code in a worktree?

Pass --worktree, or -w for short, with a name:

bash
claude --worktree feature-auth

Claude Code creates the folder .claude/worktrees/feature-auth/ at the root of your repository, on a new branch named worktree-feature-auth, and starts the session inside it. Leave the name out and it makes one up, such as bright-running-fox. For a second agent, open another terminal and run the same command with a different name.

Two setup steps are worth doing once per repository:

  • Add .claude/worktrees/ to your .gitignore. Anthropic recommends it "so worktree contents don't appear as untracked files in your main checkout."
  • Run claude in the repository once first. An interactive --worktree run needs the folder's trust dialog accepted, and exits with an error until it is.

You can also switch mid-session: ask Claude to "work in a worktree," and it creates one with its EnterWorktree tool. To start from a pull request, pass its number in quotes, as in claude --worktree "#1234", and Claude Code creates .claude/worktrees/pr-1234 from that pull request's latest commit. The quotes keep your shell from reading the # as the start of a comment.

The --worktree flag arrived in Claude Code 2.1.49 on February 19, 2026, so guides written before then show only the manual git commands. Those still work, and they're further down.

How do you get .env and node_modules into a worktree?

A new worktree is a fresh checkout, so it holds only files that git tracks. Your .env, your node_modules and your build output aren't there. In Anthropic's words, "untracked files like .env or .env.local from your main repository are not present."

For secrets and local config, add a .worktreeinclude file to the root of your project. It uses .gitignore syntax, and Claude Code copies every file it names into each worktree it creates:

.worktreeinclude
.env
.env.local
config/secrets.json

Only files that match a pattern and are also gitignored get copied, so tracked files are never duplicated. We tested this: with .env listed, claude --worktree put a copy of .env in the new folder before the session started.

For node_modules, symlink it or reinstall. A setting in .claude/settings.json links large folders from the main checkout instead of copying them:

.claude/settings.json
{
  "worktree": {
    "symlinkDirectories": ["node_modules"]
  }
}

That saves disk space and install time, but every worktree then shares the same packages, so a session that installs a new dependency changes them for all of them. When a branch changes package.json, run npm install inside its worktree instead, or ask Claude to set up the environment there.

Which branch does a new worktree start from?

By default, from the remote copy of your main branch, not from where you are now. The worktree.baseRef setting has two values (settings reference):

  • "fresh", the default, "branches from origin/<default-branch> for a clean tree matching the remote."
  • "head" branches from the commit you're on, "so unpushed commits and feature-branch state are present in the worktree."

The default surprises people: commits you haven't pushed yet aren't in the new worktree. Push first, or set "baseRef": "head" in your settings. The setting can't name a particular branch; to start from one, use git directly, as shown further down.

How do you run several agents at once?

There are three ways, depending on who's driving:

  • Sessions you run yourself: one terminal per task, each with its own claude --worktree <name>. This is the simplest and the one I use most.
  • Subagents: add isolation: worktree to a custom subagent's frontmatter, and each time Claude starts it, it works in a temporary worktree of its own. You can also ask Claude to "use worktrees for your agents" for a single task.
  • Agent teams: these don't get worktrees. Anthropic says "Agent teams don't isolate teammates in worktrees, so partition the work so each teammate owns a different set of files."

To make a subagent always work in its own worktree, save a file like this in .claude/agents/ in your project:

.claude/agents/refactorer.md
---
name: refactorer
description: Applies mechanical refactors across many files
isolation: worktree
---

Apply the requested refactor across every affected file, then run the tests
and report the results.

One cost to plan for: "Running several sessions or subagents at once multiplies token usage." Three agents working for an hour use about three times the tokens of one. Keep parallel work for tasks that are truly separate.

What does a worktree not isolate?

A worktree separates files and branches. Everything outside git is still shared, and this is where parallel agents actually collide.

Separate per worktree?
Files on diskYes
Current branchYes
Git history and the .git folderNo, shared by design
Permission approvals ("don't ask again")No, saved to the main checkout
Project plugins, and untracked skills and agentsNo, read from the main checkout
Dev server portsNo
Your local database, Redis, Docker containersNo
A browser profile used for testingNo
Disk spaceNo, each worktree adds to it

The approvals and plugins are shared on purpose, so you don't set each worktree up again. The rest is on you. Trigger.dev's engineering team stopped using worktrees for parallel agents over exactly this, and their write-up describes the database case: "Both worktrees point at the same PostgreSQL database. Agent A runs a migration. Agent B's schema is now out of sync."

What works on the sites I build:

  • Give each worktree its own port. Start the dev server with npm run dev -- --port 3001 in the second worktree, or whatever your framework's port option is.
  • Don't let two agents migrate one database. Use a separate local database per worktree, or keep schema work to one agent at a time.
  • Watch disk use. Each worktree is a full checkout plus its dependencies; symlink node_modules where you can, and remove worktrees you've finished with.

How does Claude Code keep a session inside its worktree?

It checks the session's actions. While a session is isolated in a worktree, Claude Code blocks file edits aimed at the main checkout, commands whose working directory is the main checkout, and git commands pointed back at it through git -C, GIT_DIR or a cd. It also refuses a command when it "can't verify from the command text that any git the command runs stays inside the worktree," and tells Claude to rewrite it as plain, separate commands.

The same checks cover every subagent the session starts. If you see Claude splitting a long shell one-liner into several steps inside a worktree, this is why.

One detail for anyone who writes Claude Code hooks: inside a worktree, $CLAUDE_PROJECT_DIR still points at the main checkout, while the cwd field in the hook's input is the worktree. A hook that checks the current branch should read the cwd field instead.

How do you merge the work and clean up?

The branch is an ordinary git branch. Push it and open a pull request, or merge it locally, the same as any other.

What happens to the folder depends on how the session ends:

  • You exit, and nothing changed: for an unnamed session, Claude Code removes the worktree and its branch. A named session asks first.
  • You exit, and there's work in it: Claude Code asks whether to keep or remove it. Keep it, and claude --worktree <name> --resume picks it up again later.
  • A scripted run with claude -p: there's no exit prompt, so nothing is cleaned up, and the worktree stays locked.

That last one catches people. In our test, a claude -p --worktree run left its worktree marked locked in git worktree list, so a plain remove fails until you unlock it:

bash
git worktree list
git worktree unlock .claude/worktrees/feature-auth
git worktree remove .claude/worktrees/feature-auth
git branch -d worktree-feature-auth

Use git branch -d, which refuses to delete a branch that hasn't been merged, rather than -D, which deletes it anyway. A squash merge on GitHub looks unmerged to git, so check the pull request before you reach for -D. Claude Code also sweeps away old worktrees it created for subagents and background sessions, but never one that still holds uncommitted or unpushed work.

How do you do it with plain git?

Use git directly when you want a particular existing branch, a folder outside the repository, or a tool other than Claude Code:

bash
git worktree add ../project-feature-a -b feature-a
cd ../project-feature-a
claude

The first line creates the folder ../project-feature-a next to your repository, on a new branch feature-a. To check out a branch that already exists, leave out -b, as in git worktree add ../project-hotfix hotfix. Git refuses to check out one branch in two worktrees at once, which is the protection you want.

A worktree you make this way doesn't get .worktreeinclude processing, so copy .env across yourself. It still shares permission approvals and plugins with the main checkout, and Claude Code never sweeps it away.

Do Codex, Cursor and Gemini CLI have worktrees?

All three do now, each a little differently:

ToolHow to start oneWhere it goesStatus
Claude Codeclaude --worktree <name>.claude/worktrees/<name>Stable since February 2026
Codex--worktree, or /worktree in a sessionManaged by CodexExperimental, since September 9, 2026
Gemini CLIgemini --worktree <name>, once turned on.gemini/worktrees/<name>Experimental
CursorAutomatic for parallel agentsManaged by CursorSetup commands in .cursor/worktrees.json

Two differences matter day to day. Gemini CLI "does not automatically delete your worktree or branch," so you clean up by hand. Cursor keeps at most 25 worktrees per machine by default and cleans up older ones past that. Codex's support landed in release 0.154.0.

Whatever the tool, a worktree made with plain git worktree add works for all of them, and it's what I use when a Claude Code session and a Codex session share one repository.

A worktree is a habit, so back it with a guard

A worktree only helps if every session actually uses one, and the day you forget is the day two agents commit onto one branch. Two guards close that gap:

  • A hook that refuses a commit on main. The Claude Code hooks guide has one you can paste in.
  • A git pre-commit hook, which git runs whoever makes the commit, including Codex and Gemini CLI.

The Agent Setup Pack packages both, plus a detector that names the other AI sessions working in the same repository, whichever tool they're in, before you commit. The verification skill is free if you'd like to try one of our skills first.

Troubleshooting Claude Code worktrees

Failed to resolve base branch "HEAD". The repository has no commits yet. A worktree is created from an existing commit, so make one first.

My .env isn't in the worktree. Check the file is listed in .worktreeinclude at the project root and is gitignored; only files that are both get copied. A WorktreeCreate hook replaces git's worktree creation, and .worktreeinclude isn't processed at all then.

My unpushed commits are missing. The default base is origin/<default-branch>. Push first, or set worktree.baseRef to "head" in your settings.

--worktree exits with a trust error. Run claude in the repository once and accept the trust dialog.

git worktree remove refuses. Either the worktree has uncommitted changes (commit them, or add --force if you really mean to delete them) or it's locked (run git worktree unlock first).

is already checked out. Git allows one branch in one worktree at a time. Check git worktree list to see which folder has it.

Project skills don't load in the worktree. If your .claude/skills folder is gitignored, Claude Code 2.1.277 or later reads it from the main checkout. Update Claude Code.

Frequently asked questions

What is a worktree in Claude Code?

A separate folder with its own branch, created from your repository by claude --worktree, so one session's edits and commits stay apart from another's.

Where does Claude Code put worktrees?

In the .claude/worktrees/ folder at the root of your repository. Each worktree gets its own folder there, and a branch named worktree- plus its name.

How do I run Claude Code in parallel?

Open a terminal per task and start each with claude --worktree <name>, or give a subagent isolation: worktree in its frontmatter.

Does a worktree copy node_modules?

No. Install dependencies in the worktree, or list node_modules in the worktree.symlinkDirectories setting to link the main checkout's copy.

Do worktrees cost extra?

Not in git terms; a worktree is cheap. Running several agents at once does multiply token usage, since each one is a full session.

Can I use worktrees with Codex too?

Yes. Codex has its own experimental --worktree, and a worktree made with git worktree add works with any tool. For Codex's skills, see the Codex skills guide.

Every claim checked against its source on

From Heavy Artillery Skills

Agent Setup Pack

Give Claude Code, Codex and Gemini CLI one set of rules and check what each loads, run several agents on one repo, and keep API keys out of the chat.

More guides