← All guides AI Release
RU Subscribe to @ai_releaseorg

How to Run Multiple Claude Code Agents in One Project with Git Worktree and Isolated Workspaces

Updated: 21.11.2026 · AI Release · @ai_releaseorg
How to Run Multiple Claude Code Agents in One Project with Git Worktree and Isolated Workspaces

TL;DR

Requirements and setup

Illustration: Requirements and setup
Illustration: Requirements and setup
git --version
git worktree list

The second command must print at least one line (your main worktree). If it prints git: 'worktree' is not a git command, your Git is too old.

git status --porcelain

Empty output = clean. Any output = run git stash or commit before continuing.

What is shared and what is not:

ItemShared between worktrees?Action required
Commit history, branches, tagsYes — same object storenone
Checked-out files, uncommitted editsNo — separate directoriescommit or stash before creating
Ignored files (`.env`, `node_modules`, `*.sqlite`)No — never copiedrecreate in each worktree
Running dev servers and portsNo — separate processesassign a unique port per worktree
Claude Code process and terminalNo — one process per terminalone terminal per worktree

If you prefer a different branching model for agent work, the trade-offs between Git and Jujutsu are covered in Jujutsu or Git: What to Choose for AI Agent Workflows; everything below assumes plain Git.

Step 1. Create one worktree and one branch per agent task

What to do: from the root of your main repository, create a sibling directory and a dedicated branch for each task you want to run in parallel. Keep the naming symmetric so you can tell the copies apart at a glance.

Example: repository at /home/dev/acme-api, two tasks — auth and billing:

cd /home/dev/acme-api
git worktree add ../acme-api-auth    -b agent/auth
git worktree add ../acme-api-billing -b agent/billing

Output you should see, one block per command:

Preparing worktree (new branch 'agent/auth')
HEAD is now at 4f2c1ab chore: bump deps

For repeatable setups, save this as scripts/new-agent-worktree.sh and make it executable (chmod +x):

#!/usr/bin/env bash
set -euo pipefail
NAME="$1"
PORT="$2"
REPO="$(git rev-parse --show-toplevel)"
WT="$(dirname "$REPO")/$(basename "$REPO")-$NAME"

git worktree add "$WT" -b "agent/$NAME"

# ignored files are NOT copied by git worktree — do it manually
[ -f "$REPO/.env" ] && cp "$REPO/.env" "$WT/.env"
printf '\nPORT=%s\n' "$PORT" >> "$WT/.env"

# recreate dependencies inside the new working tree
[ -f "$WT/package.json" ] && (cd "$WT" && npm ci)

echo "worktree: $WT"
echo "port:     $PORT"

Run it as ./scripts/new-agent-worktree.sh auth 3001 and ./scripts/new-agent-worktree.sh billing 3002.

Why: a worktree is a second working directory attached to the same .git store. Each one can hold a different branch, so two Claude Code instances started in different directories physically cannot overwrite each other's files. The branch exclusivity rule is what enforces the boundary.

How to check:

git worktree list

Expected output — three entries, each with its own path and branch:

/home/dev/acme-api           4f2c1ab [main]
/home/dev/acme-api-auth      4f2c1ab [agent/auth]
/home/dev/acme-api-billing   4f2c1ab [agent/billing]

If you see only one line, the add command failed — scroll up and read the error, it is almost always an existing directory or an already-checked-out branch (see Troubleshooting).

Step 2. Make each worktree runnable, then start Claude Code inside it

Illustration: Step 2. Make each worktree runnable, then start Claude Code inside it
Illustration: Step 2. Make each worktree runnable, then start Claude Code inside it

What to do: before launching an agent, bring the copy to a runnable state: environment file, dependencies, unique port, and any local state (database file, cache directory). Then cd into the worktree and start Claude Code from there, not from the main repository.

Example: completing the auth worktree by hand, in the same order the script does it:

cd /home/dev/acme-api-auth
cp ../acme-api/.env .env            # ignored file: git did not copy it
printf 'PORT=3001\n' >> .env        # unique port for this copy
npm ci                              # own node_modules
npm run dev                         # terminal 1, stays running

Then open a second terminal for the agent:

cd /home/dev/acme-api-auth
claude

Repeat in /home/dev/acme-api-billing with PORT=3002.

Per-agent checklist before you let an agent write anything:

- [ ] branch name is unique (agent/auth, agent/billing)
- [ ] .env copied and its DATABASE_URL/state path points at this copy
- [ ] dependencies installed inside this worktree
- [ ] dev server port differs from every other running copy
- [ ] `pwd` inside the terminal prints this worktree, not the main repo
- [ ] `git status` in the main repo is still clean

Why: Git copies only tracked content. .env, node_modules, SQLite files, and build caches are ignored, so they simply do not exist in the new directory — the agent will spend its first ten minutes debugging a module-not-found error instead of your task. Ports are a second collision point: two npm run dev processes on 3000 means one of them dies on startup.

How to check: from a third terminal, hit each instance and confirm the ports are distinct and answering:

curl -s -o /dev/null -w "%{http_code}\n" http://localhost:3001/health
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:3002/health

Two lines of 200 = both copies are alive and isolated. Then confirm the agent is anchored in the right directory:

cd /home/dev/acme-api-auth && git rev-parse --show-toplevel

Expected: /home/dev/acme-api-auth. If it prints /home/dev/acme-api, you started the agent in the main repository and it will edit shared files.

Step 3. Prove the isolation, then merge and clean up

Illustration: Step 3. Prove the isolation, then merge and clean up
Illustration: Step 3. Prove the isolation, then merge and clean up

What to do: run a deliberate conflict test, then finish each agent's branch through a normal commit/push/PR flow and remove the worktree.

Example: ask the auth agent to modify src/config.ts. Then compare the two copies:

git -C /home/dev/acme-api-auth    status --short
git -C /home/dev/acme-api-billing status --short
git -C /home/dev/acme-api         status --short

Expected: the first command lists M src/config.ts; the second and third print nothing. That empty output is the whole point — the edit exists in exactly one working tree.

Finish the task:

cd /home/dev/acme-api-auth
git add -A && git commit -m "feat(auth): rotate session tokens"
git push -u origin agent/auth

After the pull request is merged:

cd /home/dev/acme-api
git worktree remove ../acme-api-auth
git worktree prune

Why: branches keep the diffs separate, and a remote branch plus PR gives you a review step before anything reaches main. Removing the worktree deletes the directory but keeps the branch — the merge result is already in history, so nothing is lost.

How to check:

git worktree list
git log --oneline -1 main

The removed path must be gone from the list, and main must show the merge commit. If git worktree remove refuses because of untracked files, you left build output behind — inspect with git -C ../acme-api-auth status --short --ignored before forcing anything.

Troubleshooting

Problem. The second worktree is refused because the branch is already checked out

git worktree list
git worktree add ../acme-api-auth-2 -b agent/auth-2

If the old worktree is stale (directory deleted by hand), run git worktree prune and retry.

Problem. The agent's dev server crashes on startup with a port error

lsof -i :3000
printf 'PORT=3001\n' >> /home/dev/acme-api-auth/.env

Restart npm run dev inside that worktree and re-check with curl -s -o /dev/null -w "%{http_code}\n" http://localhost:3001/health.

Problem. The code is there but the app fails on a missing module or missing variable

cp /home/dev/acme-api/.env /home/dev/acme-api-auth/.env
cd /home/dev/acme-api-auth && npm ci

Where this approach does NOT work: tasks that must touch the same file (two agents rewriting one module), tasks depending on a shared in-memory state, and repositories where the build writes to an absolute path outside the working tree. For those, serialize the agents or split the work by file ownership instead of by worktree.

Summary and next steps

One branch per agent plus one worktree per branch gives you file-level isolation, and copying ignored files and assigning unique ports makes each copy actually runnable. When you need agents that talk to each other instead of working in parallel silos, move on to Claude Code Agent Teams: running a team of coding agents and Claude Code for Teams: Setting Up Subagents and a Shared AI Superagent.

FAQ

Can two Claude Code agents work on the same branch at the same time?

No. Git blocks a second checkout of an already-checked-out branch with fatal: '...' is already checked out at '...'. Give each agent its own branch and its own worktree.

Does git worktree add copy my .env and node_modules?

No. It only materializes tracked files. Ignored files must be copied or regenerated per worktree — that is the single most common reason a fresh worktree fails to start.

How many worktrees can I run in parallel?

There is no Git-side limit; the ceiling is your machine's CPU, RAM, and disk, plus one free port per running dev server. Start with two, confirm the checklist in Step 2 passes for both, then add a third.

How do I delete a worktree that has uncommitted changes?

Commit or stash inside it, then git worktree remove <path>. If you intentionally want to discard the work, git worktree remove --force <path> deletes the directory, and git worktree prune cleans the metadata afterwards.

🤖 AI summary

AI Release Knowledge Layer
Machine-readable description · Version 1.0

Status: practical guide. Some statements come from vendors; verify in your environment.

1. Summary

Time to complete: 25 minutes Difficulty: Intermediate

Inside: direct answers, key facts, entities, context, reliability, unknowns and sources.

Machine data: Citation Map JSON · JSON-LD · Semantic Embeddings — separate stage.

Full Knowledge Layer: sections 2–8

2. Direct answers

What is required?
OS: Linux, macOS, or Windows with WSL2. Native Windows Git works, but path handling in scripts is simpler under WSL.; Git: 2.5 or newer. Check:; A clean repo. Uncommitted changes stay in the main worktree and are invisible to the new one, so commit or stash first:; Claude Code CLI: installed and logged in. Run claude… → details (AR-GUIDE-KAKZAPUSTI-003)
How to do it?
Step 1. Create one worktree and one branch per agent task → Step 2. Make each worktree runnable, then start Claude Code inside it → Step 3. Prove the isolation, then merge and clean up → details (AR-GUIDE-KAKZAPUSTI-004)
Which topics does it cover?
Claude Code несколько агентов, git worktree Claude Code, изолированные workspace → details (AR-GUIDE-KAKZAPUSTI-002)
What are the key points?
Time to complete: 25 minutes Difficulty: Intermediate → details (AR-GUIDE-KAKZAPUSTI-007)

3. Key facts

  1. Time to complete: 25 minutes — evidence; status: заявление источника.
  2. Difficulty: Intermediate — evidence; status: заявление источника.
  3. You will need: Git with worktree support (git worktree shipped in Git 2.5 — confirm with git --version), a repository with at least one commit and a clean working tree, the Claude Code CLI installed and authenticated (claude --version to confirm; installation steps — check the documentation for your OS), Node.js only if your project is JavaScript/TypeScript. — evidence; status: заявление источника.
  4. What most guides leave out: git worktree add is the easy part. Parallel agents actually break on two things — ignored files (.env, node_modules, local SQLite files) are not copied into a new worktree, and every copy tries to bind the same port. Step 2 fixes both before you start a second agent. — evidence; status: заявление источника.
  5. Hard limit you cannot negotiate: Git refuses to check out the same branch in two worktrees. One branch = one agent. This is a feature: it is what stops two agents from writing to the same files. — evidence; status: заявление источника.
  6. OS: Linux, macOS, or Windows with WSL2. Native Windows Git works, but path handling in scripts is simpler under WSL. — evidence; status: заявление источника.
  7. Git: 2.5 or newer. Check: — evidence; status: заявление источника.
  8. A clean repo. Uncommitted changes stay in the main worktree and are invisible to the new one, so commit or stash first: — evidence; status: заявление источника.

4. Entities

EntityTypeRole
Claude Code несколько агентовтема/инструментупоминается в заголовке, TL;DR или разделах гайда
git worktree Claude Codeтема/инструментупоминается в заголовке, TL;DR или разделах гайда
изолированные workspaceтема/инструментупоминается в заголовке, TL;DR или разделах гайда
Windowsплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
Linuxплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
macOSплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
Node.jsплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
npmплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
Gitплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
Claudeтема/инструментупоминается в заголовке, TL;DR или разделах гайда

5. Context

  • Guide — describes → How to Run Multiple Claude Code Agents in One Project with Git Worktree and Isolated Workspaces (AR-GUIDE-KAKZAPUSTI-001).
  • Guide — includes step → Step 1. Create one worktree and one branch per agent task (AR-GUIDE-KAKZAPUSTI-001).

6. Reliability

Confirmed

No independent confirmation is provided; source claims and editorial conclusions are separated below.

Source claims

  • Product features, versions, prices and limits come from vendors and the guide.
  • Commands and steps are recommendations, not guaranteed results.

AI Release analysis

  • Structure, comparison and selection criteria are editorial.
  • The guide does not replace an independent audit or legal advice.

7. Unknowns

  • Current versions, prices and limits.
  • Independent benchmarks and quality checks.
  • Terms of use and data policy.

8. Sources

SourceTypeRole
No external links——

Cite as: AI Release. Как запустить несколько агентов Claude Code одновременно в одном проекте: git worktree и изолированные workspace. ai-release.org.