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

> AI Release · @ai_releaseorg · https://ai-release.org/guides/kak-zapustit-neskolko-agentov-claude-code-odnovremenno_en.html

## TL;DR

- **Time to complete:** 25 minutes
- **Difficulty:** Intermediate
- **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.
- **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.
- **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.

## Requirements and setup
![Illustration: Requirements and setup](https://ai-release.org/guides/img/kak-zapustit-neskolko-agentov-claude-code-odnovremenno-en-1.jpg?v=1795250658)


- **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:
```bash
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.
- **A clean repo.** Uncommitted changes stay in the main worktree and are invisible to the new one, so commit or stash first:
```bash
git status --porcelain
```
Empty output = clean. Any output = run `git stash` or commit before continuing.
- **Claude Code CLI:** installed and logged in. Run `claude --version`; if the binary is missing, follow the official install instructions — the exact package name and flags differ per release, so check the documentation rather than copying a command from an old blog post.
- **Disk space:** each worktree is a full copy of the working files. With `node_modules`, budget several hundred MB per worktree; the `.git` object store itself is shared and does not duplicate history.
- **A second terminal window** (or tmux/split panes) — one terminal per agent, otherwise you will type into the wrong session.

What is shared and what is not:

| Item | Shared between worktrees? | Action required |
|---|---|---|
| Commit history, branches, tags | Yes — same object store | none |
| Checked-out files, uncommitted edits | No — separate directories | commit or stash before creating |
| Ignored files (`.env`, `node_modules`, `*.sqlite`) | No — never copied | recreate in each worktree |
| Running dev servers and ports | No — separate processes | assign a unique port per worktree |
| Claude Code process and terminal | No — one process per terminal | one 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](https://ai-release.org/guides/jujutsu-ili-git-chto-vybrat-dlya-raboty-s-ii-agentami-i.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide); 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`:

```bash
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`):

```bash
#!/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:**

```bash
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](https://ai-release.org/guides/img/kak-zapustit-neskolko-agentov-claude-code-odnovremenno-en-2.jpg?v=1795250662)


**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:

```bash
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:

```bash
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:

```text
- [ ] 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:

```bash
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:

```bash
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](https://ai-release.org/guides/img/kak-zapustit-neskolko-agentov-claude-code-odnovremenno-en-3.jpg?v=1795250668)


**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:

```bash
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:

```bash
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:

```bash
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:**

```bash
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**

- Error: `fatal: 'agent/auth' is already checked out at '/home/dev/acme-api-auth'`
- Cause: Git allows a branch in exactly one worktree. You either reused a name or tried to run two agents on the same branch.
- Solution: list what exists, then pick a new branch name:
```bash
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**

- Error: `Error: listen EADDRINUSE: address already in use :::3000`
- Cause: two copies are binding the same port, usually because the `.env` in the new worktree still contains the original `PORT`.
- Solution: find the process and give each copy its own port:
```bash
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**

- Error: `Error: Cannot find module 'dotenv'` or `Error: Missing required environment variable: DATABASE_URL`
- Cause: `.env` and `node_modules` are gitignored, so `git worktree add` did not bring them along. The files exist in the main worktree and nowhere else.
- Solution: copy the env file and reinstall dependencies inside the new directory:
```bash
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](https://ai-release.org/guides/claude-code-agent-teams-komanda-agentov.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide) and [Claude Code for Teams: Setting Up Subagents and a Shared AI Superagent](https://ai-release.org/guides/claude-code-dlya-komandy-kak-nastroit-subagentov-i-obsc.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide).

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