Skip to main content
Running Parallel AI Coding Agents with Git Worktrees: How We Isolate Checkouts, Ports, Databases and Merges

Running Parallel AI Coding Agents with Git Worktrees: How We Isolate Checkouts, Ports, Databases and Merges

November 15, 2026
Developer Tooling
9 min read

Headline: A git worktree gives each AI coding agent its own working directory, staging index and branch while every agent shares one object database, so several agents can edit the same repository at once without overwriting each other. Git isolates only files, so dev-server ports, localhost cookies, the local database, migration numbers and untracked .env files still collide until a setup script separates them.

Once our team started running several Claude Code sessions against the same repository, a single checkout stopped working. Two agents in one directory edit the same files, restart the same dev server and fight over git switch. Worktrees fixed the file problem with one command. Everything that broke afterwards lived in the parts of the stack that git knows nothing about.

Key takeaways

• One agent, one worktree, one branch: git worktree add, available since Git 2.5, creates an extra working directory backed by the same repository, and Git refuses to check out one branch in two worktrees.

• Untracked files never follow: .env.local, node_modules and .next do not exist in a new worktree, so a setup script has to copy or rebuild them.

• Git isolates files, not runtime: parallel dev servers still share ports, localhost cookies and the local database unless each worktree gets its own hostname and database.

• Keep worktrees outside the repository root: a nested worktree gets type-checked, tested and linted as if it were part of the main project.

• Parallel branches conflict in predictable hotspots: lockfiles, sequentially numbered migrations and shared registries, so we split agent tasks along those lines.

What does a git worktree share, and what does it isolate?

A git worktree shares the repository's commits, branches, tags, stash, hooks and config, and isolates the checked-out files, the staging index and HEAD. The main checkout keeps the real .git directory; each linked worktree contains a one-line .git file that points back to a folder under .git/worktrees/ in the main checkout.

That split matters for agents. A commit made in one worktree is visible from every other worktree immediately, with no push or fetch, because all of them read the same object database. Hooks in .git/hooks or a shared core.hooksPath run in every worktree. The stash is shared too, so an agent that runs git stash pop can apply a stash that a different session created. Our CLAUDE.md files tell agents to commit work in progress instead of stashing it.

Creating a worktree is a single command: git worktree add -b agent/search-filters ../app.worktrees/search-filters main creates the branch agent/search-filters and checks it out in a sibling directory. git worktree list prints one line per worktree with its path, HEAD commit and branch.

Why use worktrees instead of extra clones or branch switching?

Worktrees are the cheapest way to get parallel, file-isolated checkouts of one repository: they add a working directory without copying history, and new commits are shared instantly. Switching branches in a single checkout gives no parallelism at all, and separate clones duplicate the object database and drift apart until each one fetches.

• git switch in one checkout: no parallel agents, one copy of history, nothing isolated.

• One git clone per agent: parallel agents, one copy of history per clone, other agents' commits visible only after push and fetch, files and all git metadata isolated.

• One git worktree per agent: parallel agents, one shared copy of history, other agents' commits visible immediately, files, index and HEAD isolated.

• One container or cloud sandbox per agent: parallel agents, one copy per sandbox, commits visible only after push, files, processes and network isolated.

We use worktrees for agents running on our own machines and keep sandboxes for code that should not touch them.

How do we create a worktree an agent can actually run?

A runnable worktree needs four things that a bare git worktree add does not provide: a fresh branch from the latest main, the untracked environment files, installed dependencies and its own runtime settings. We wrap all four in one script so every agent starts from the same state.

The script takes a task name, fetches origin main and runs git worktree add --no-track -b agent/<name> into a sibling directory named <repo>.worktrees/<name>. It then copies .env.local from the main checkout, writes a per-worktree DATABASE_URL into .env.development.local, creates a matching Postgres database with createdb and finishes with pnpm install --frozen-lockfile.

Three of those steps came from mistakes. The --no-track flag stops the new branch from adopting origin/main as its upstream, so git status and git pull in that worktree do not treat main as the branch's remote; the first git push -u origin agent/<name> sets the real upstream. The override goes into .env.development.local because Next.js gives that file priority over .env.local during next dev, so the copied file stays untouched. And pnpm keeps one content-addressable store and hard-links packages into each worktree's node_modules, so a second install is mostly linking rather than downloading; npm copies every package again.

How do we stop parallel dev servers and databases from colliding?

Parallel dev servers collide on three shared resources: TCP ports, browser cookies and the local database. Git isolates none of them, so each one needs an explicit per-worktree rule.

• Ports: next dev moves to the next free port when port 3000 is taken, but a port hardcoded in a NestJS main.ts or a Docker Compose mapping fails outright. We never hardcode ports in dev scripts; a PORT environment variable decides.

• Cookies: browsers do not isolate cookies by port, so localhost:3000 and localhost:3001 share one cookie jar and two agents' login sessions overwrite each other. A distinct hostname per worktree, such as search-filters.localhost, gives each one separate cookies, and Chrome and Firefox resolve any *.localhost name to the loopback address. We start every dev server through portless, a local proxy that maps a stable name to whichever port the server picked.

• Databases: two branches running migrations against one database leave its schema matching neither branch. One Postgres server with one database per worktree, created by the setup script, is enough. Docker Compose already derives its project name from the directory name, so containers and volumes stay separate per worktree, but a fixed host mapping such as 5432:5432 still collides.

Where should worktrees live so other tools ignore them?

Worktrees belong in a sibling directory such as ../app.worktrees/, not inside the repository. A worktree nested under the repository root is a full second copy of the source tree, and tools that glob from the root pick it up: a tsconfig.json without an include list type-checks it, Vitest and Jest collect its test files a second time, and ESLint v9 flat config lints it because ESLint does not read .gitignore by default.

If a nested location is unavoidable, the directory has to go into .gitignore, the exclude list in tsconfig.json, the test runner's exclude patterns and the ESLint ignores array. A sibling directory needs none of that.

How do we merge parallel agent branches without a conflict pileup?

Parallel agent branches conflict mostly in a few predictable files, so we split tasks to avoid those files and merge one branch at a time, rebasing the remaining branches onto the new main.

• Lockfiles: two agents adding dependencies both rewrite pnpm-lock.yaml. We give dependency changes to one agent; otherwise we resolve package.json by hand and rerun pnpm install to regenerate the lockfile instead of merging it line by line.

• Sequential migrations: Drizzle Kit numbers migration files and records them in a journal, so two branches can both generate migration 0007. Only one branch owns schema changes at a time, or the second branch regenerates its migration after rebasing.

• Shared registries: route lists, barrel files and i18n JSON files all get appended at the same spot. One entry per file, or appending at different points, avoids most textual conflicts.

Every agent runs the project's full checks inside its own worktree before opening a pull request, so a red build points at one branch. Cleanup is three commands: git worktree remove <path>, which refuses while changes are uncommitted; git branch -D agent/<name>; and git worktree prune, which drops records of directories deleted by hand.

Deleting a worktree folder with rm -rf leaves a stale record, and Git keeps treating the branch as checked out until git worktree prune runs. Squash merges put a new commit on main, so git branch -d reports the agent branch as unmerged; we confirm the pull request merged before forcing deletion with -D.

FAQ

Q: Can two git worktrees check out the same branch?

A: No. Git refuses to check out a branch that is already checked out in another worktree, which stops two agents from moving the same branch. git worktree add --force overrides the check, but a commit in one worktree then leaves the other with an out-of-date index and working tree.

Q: Do git worktrees share node_modules?

A: No. node_modules is untracked, so each worktree needs its own install. pnpm hard-links packages from one global store, which keeps repeated installs fast and disk use low, while npm copies every package into each worktree.

Q: Does a worktree protect the repository from an agent's destructive git commands?

A: Only partly. A worktree isolates working files, but branches, tags and the object database are shared, so deleting a branch, deleting a tag or force-pushing from any worktree affects all of them. Hooks or permission rules that block those commands are still needed.

Q: Does Claude Code work with git worktrees?

A: Yes. A Claude Code session started inside a worktree directory treats it as a normal checkout, and Claude Code's subagents can run in an isolated worktree that is cleaned up automatically when the subagent makes no changes.