01

Parallel Claude Code sessions in VS Code with git worktrees

A practical guide to running parallel Claude Code sessions with git worktrees in VS Code: create each worktree from a fresh origin/main, copy the files git ignores, give every session its own port, open them side by side, write the rules into AGENTS.md, and clean up without killing the wrong process. Real lessons from building SpaceCare.

By Federico Blundo

The problem: two agents, one folder

Two AI coding sessions in one folder will overwrite each other. The fix is a git worktree per task: its own folder, branch and port, sharing one history. This is how I set them up for SpaceCare.

Once an AI agent does the typing, the bottleneck moves. It is no longer how fast code gets written. It is how many well-briefed tasks you can keep moving at once. So the obvious next step is two or three sessions in parallel: one on a feature, one on a bug, one on a review.

The first time I tried that in a single folder, it went wrong in an instructive way. One session was translating about 30 files into Italian while another refactored the design system in the same checkout.

Files I had never touched turned dirty mid-task. The shared branch label got moved, so my first push sent the wrong commits. And the pre-push type check failed on the other session's half-finished work, blocking a clean change.

Two agents in one working directory are like two people typing into one document with one cursor.

What a worktree is

A normal clone has one working directory attached to one .git folder. git worktree add attaches extra working directories to the same repository.

Each worktree has its own checked-out branch and its own files on disk. Commits, branches and remotes are shared, so a commit made in one worktree is visible from the others. Git also refuses to check out the same branch in two worktrees, which is exactly the guard you want.

"The new worktree is linked to the current repository, sharing everything except per-worktree files such as HEAD, index, etc." - Git, git-worktree documentation

Shell
git worktree list          # every checkout attached to this repo
git worktree add ../app-billing -b feat/billing origin/main
git worktree remove ../app-billing
git worktree prune         # forget folders you deleted by hand

Step 1: Create the worktree from a fresh origin/main

Shell
git fetch origin main
git worktree add ../myapp-feat-x -b feat/x origin/main

The fetch and the origin/main are the important part. Branching from your local main gives you whatever main was the last time you pulled, which can be days old.

I learned this when a session spent an hour editing a dialog that had already been rewritten on the remote. In the end, 6 out of 9 edits targeted code that no longer existed. My own shell helper had the same bug for months, because it branched from main.

Step 2: Bootstrap what git does not copy

A new worktree contains only tracked files. Your .env.local, local secrets and anything else in .gitignore are missing, so the app will not boot. And if every worktree runs a dev server on port 3000, only one of them can.

I use a small zsh function called wt that does all of it in one command. It creates the worktree, copies the env files, picks the lowest free port and opens the folder in VS Code. This is a cleaned-up version, with the fetch fix from step 1:

~/.zshrc
wt() {
  local name="$1"
  [[ -z "$name" ]] && { echo "usage: wt <branch-name>"; return 1; }
  local top; top=$(git rev-parse --show-toplevel) || return 1
  local dest="${top:h}/${top:t}-${name}"   # sibling folder: myapp-feat-x

  git fetch origin main || return 1
  git worktree add "$dest" -b "$name" origin/main || return 1

  # Copy the gitignored env files so the new checkout boots.
  setopt local_options null_glob
  for f in "$top"/.env.local "$top"/.env.*.local; do cp "$f" "$dest/"; done

  # Lowest port not claimed by another worktree's .env.local (main = 3000).
  local -a used; local wt_path p
  while read -r wt_path; do
    [[ "$wt_path" == "$dest" ]] && continue
    p=$(grep '^PORT=' "$wt_path/.env.local" 2>/dev/null | tail -1 | cut -d= -f2)
    used+=("${p:-3000}")
  done < <(git worktree list --porcelain | awk '/^worktree /{print $2}')
  local port=3000
  while (( ${used[(Ie)$port]} )); do ((port++)); done

  grep -v '^PORT=' "$dest/.env.local" > "$dest/.env.tmp" && mv "$dest/.env.tmp" "$dest/.env.local"
  echo "PORT=$port" >> "$dest/.env.local"
  echo "worktree $dest on port $port"
  code --add "$dest"   # add to the current VS Code window
}

One trap the script does not cover by itself: any setting that contains the port. SpaceCare scopes its sign-in cookie to a root domain set in an env variable, which locally is localhost:3000.

In a worktree on port 3001 the browser silently rejected that cookie. Sign-in bounced straight back to the sign-in page with no error, and it cost several failed test runs to find. If a copied value mentions the port, rewrite it in the same script.

If you let Claude Code create worktrees for you, it reads a .worktreeinclude file at the repository root. The file uses .gitignore syntax. Only files that match a pattern and are also gitignored get copied, so tracked files are never duplicated. That covers the env files; the port still needs a line of script.

.worktreeinclude
.env.local
.env.*.local

Step 3: Open the sessions side by side in VS Code

I keep every worktree in one VS Code window as a multi-root workspace. code --add <folder> adds a folder to the window you already have open. The file explorer, search and source control then show all sessions at once, each under its own folder name.

Then I open one Claude Code tab per worktree from the command palette and rename each tab after its task. Each session works inside its own folder, with its own dev server on its own port.

If you prefer the terminal, claude --worktree <name> does steps 1 to 3 in one go. By default it creates the worktree under .claude/worktrees/<name>/ at the repository root, on a new branch called worktree-<name>.

It branches from the remote's default branch rather than your current checkout, which sidesteps the stale-main trap. Leave out the name and Claude makes one up. For an unnamed session it also removes the worktree and its branch when you exit, while a named session asks first.

Anthropic's Claude Code guide recommends the same shape, and adds a use I lean on:

"When you have separate pieces of work going at once, give each its own checkout so the edits can't collide. A second session is also the easiest independent reviewer you can get." - Anthropic, Best practices for Claude Code

How many sessions? For me, three is the comfortable number. Beyond that the limit is not the machine, it is my attention. Every session needs a clear brief at the start and a careful review at the end.

Step 4: Put the rules where every session will read them

A session only knows what it is told. Every session reads the repository's AGENTS.md (Claude Code reads it through CLAUDE.md), so the worktree rules live there, short and imperative:

AGENTS.md
### Working in a git worktree

- Branch from a freshly fetched `origin/main`, not from a local `main`.
  `git fetch origin main` first, every time.
- `.env*` files are gitignored, so a new worktree starts without them.
  Copy them across and give each worktree its own `PORT`.
- Use `git -C <path>` rather than `cd`, so a command can't silently act
  on whichever worktree the shell happened to be in.

The third rule came from a real accident. The shell's working directory can drift between commands, and a commit meant for one worktree landed on a branch in another. git -C /path/to/worktree commit cannot drift. Afterwards, git -C <path> log --oneline -1 --stat confirms the right files went in.

When I fan work out to sub-agents in their own worktrees, every brief starts with a location check:

Plain text
Before any file operation, run `pwd` and `git rev-parse --show-toplevel`
and confirm you are in your worktree. Never run commands in the main checkout.

In my first multi-agent rollout, one agent wandered into the main checkout. It created a stray branch and scaffolded files there before it noticed.

Step 5: Clean up without collateral damage

Worktrees are cheap to create and expensive to forget. Each of mine carries its own node_modules and build cache, around 1.6 GB.

At one point roughly 25 of them had pushed my laptop down to 3.2 GB of free disk, under 1% of the drive. The cleanup got it back to 30 GB and taught me three things.

Kill orphan dev servers first, by port. Several old worktrees still had a dev server running days later. They held deleted cache files open, so du could not even see the space. Killing them freed about 10 GB before I removed a single folder.

Never kill by name pattern (pkill -f "next dev"). On a machine with many sessions and a CI runner, that takes down all of them.

Shell
PID=$(lsof -nP -iTCP:3004 -sTCP:LISTEN -t | head -1)
ps -o pid,command -p "$PID"     # confirm it is the one you mean
lsof -a -p "$PID" -d cwd        # and that its folder is the stale worktree
kill "$PID"

Check merges by content, not by branch. If your team squash-merges pull requests, a merged branch's commits never become ancestors of main. So git branch --merged reports it as unmerged. Compare the files instead:

Shell
git -C ../myapp-feat-x fetch origin main
git -C ../myapp-feat-x diff --stat origin/main HEAD -- .   # empty = all of it is on main

Remove one at a time, without --force. A plain git worktree remove <path> only removes clean worktrees, with no untracked or modified files. That protects work another session may still be doing. Re-check right before removing: other sessions create and reuse worktrees while you tidy.

What else went wrong

  • A "clean" worktree that was not free. I picked a worktree with no uncommitted changes for a new task. Halfway through, files I never touched went dirty: another live session was using it. The fastest liveness check is a running dev server whose working directory is that worktree.
  • Docker Compose named after the folder. Compose uses the directory name as the project name. A docker compose down from the wrong worktree stopped nothing, and the end-to-end tests ran against an old database. Every Compose command now starts with cd <worktree> && pwd && on the same line.
  • A corrupted build cache. In a fresh worktree the dev server returned 404 for routes whose files plainly existed. Deleting the framework's cache folder (.next) and restarting fixed it. When a route 404s in one checkout but not another, suspect the environment before the code.

Copy this: a parallel-session checklist

  • One task per worktree, one branch per worktree, one port per worktree.
  • git fetch origin main then branch from origin/main.
  • Script the bootstrap: env files, unique PORT, any setting that embeds the port.
  • One VS Code window, worktrees added with code --add, one renamed Claude Code tab each.
  • Worktree rules in AGENTS.md; git -C <path> for every git command.
  • Sub-agent briefs start with a pwd check.
  • Before reusing a worktree, check nothing is running in it.
  • Clean up: kill dev servers by port, check merges by content, remove without --force.

Sources

About the author

Federico Blundo

AI Product Manager | NHS CEP | Toptal | Ex-Bain

AI product manager and founder of SpaceCare, a creator platform I build hands-on with AI coding agents. Before that I led product at 0-to-1 startups, scale-ups and public companies, including B2B SaaS at Fresha and B2C at lastminute.com, and ran transformation projects at Bain & Company.

You reached the end.

1 / 2