Parallel agents with git worktrees in Claude Code, Codex and Cursor
Originally published on KitQuarry. Written by Eliran Kotzero for KitQuarry. In short: two agents in one checkout overwrite each other's work. Give each agent its own git worktree: a separate folder on its own branch tha
Originally published on KitQuarry. Written by Eliran Kotzero for KitQuarry.
In short: two agents in one checkout overwrite each other's work. Give each agent its own git worktree: a separate folder on its own branch that shares one history. Claude Code, Codex and Cursor can all create worktrees for you. What they don't do is make a fresh checkout runnable or decide how the work fits back together, so set up .env and dependencies per worktree, split tasks so they touch different files, and run the full test suite on the merged result.
Why parallel agents in one folder go wrong
An agent that edits files, runs the build and reads the test output assumes nobody else is changing the folder. Run a second agent in the same checkout and each one sees the other's half-finished edits. Tests fail for reasons neither agent caused, and one agent "fixes" the other's work. Separate terminals or chat tabs don't help, because the files are still shared.
A git worktree fixes the file problem. In the Codex docs' words, each worktree "has its own copy of every file in your repo but they all share the same metadata (.git folder) about commits, branches, etc." Commits made in one worktree are visible from the others straight away, because they live in the same repository. The working files are not shared.
What a worktree does and doesn't isolate
| Separate per worktree | Still shared |
|---|---|
| Tracked files and uncommitted edits | Commits, branches and remotes (one .git) |
| The checked-out branch: git allows a branch in only one worktree at a time | Anything outside the folder: ports, local databases, caches, services |
| Build output and installed dependencies, once you install them there | Nothing in the repo is copied that git ignores, so .env and node_modules start missing |
Two things on the right trip people up in the first week:
-
Ignored files. A new worktree is a fresh checkout. The Claude Code docs say untracked files like
.env"are not present", and the Codex troubleshooting page lists "code doesn't run on a worktree" with the same cause. Each tool has a fix, covered below. - Things outside the folder. Two dev servers still want the same port, and two agents running migrations still hit the same local database. The Codex docs suggest handing a chat back to your main checkout when you "can run only one instance of your app". Otherwise, give each worktree its own port or database in its environment file.
Claude Code: claude --worktree
From the worktrees guide: pass --worktree (or -w) with a name, and Claude Code creates the worktree under .claude/worktrees/<name>/ on a new branch called worktree-<name>. Run the same command with another name in a second terminal for a second isolated session. The repository needs at least one commit first (common workflows).
# terminal 1
claude --worktree feature-auth
# terminal 2
claude --worktree fix-billing-rounding
# start from a pull request instead (quote the #)
claude --worktree "#1234"
Set it up once per repo:
-
Ignore the folder. Add
.claude/worktrees/to.gitignoreso the worktrees don't show up as untracked files in your main checkout. -
Copy ignored files. Add a
.worktreeincludefile at the repo root, in.gitignoresyntax. Claude Code copies files that match a pattern and are gitignored into every worktree it creates, so tracked files are never duplicated. - Install dependencies. They aren't copied. Ask Claude to install them, or run your setup yourself in the worktree directory.
-
Pick the base. New worktrees branch from the remote's default branch, usually
main. To branch from your current localHEAD(unpushed commits included), set"worktree": {"baseRef": "head"}in settings. It doesn't accept a branch name; for a specific existing branch, create the worktree with git.
# .worktreeinclude
.env
.env.local
config/secrets.json
When you exit, Claude checks the worktree. If it's clean, an unnamed session's worktree and branch are removed automatically, and a named session asks first. If it has changes or new commits, Claude asks whether to keep or remove it. Keep it and you can come back with the claude --worktree <name> --resume command Claude Code prints on exit. Non-interactive -p runs aren't cleaned up, so remove those with git worktree remove.
Inside one session you can also isolate subagents. Ask Claude to "use worktrees for your agents", or add isolation: worktree to a custom subagent's frontmatter in .claude/agents/. Each subagent gets a temporary worktree, removed automatically if it finishes without changes. One detail from the docs: such a subagent takes its instruction files from the main conversation, not from its worktree, so a CLAUDE.md that differs on the worktree's branch doesn't apply to it.
Some things carry across worktrees of the same repository: on most setups, "Yes, and don't ask again" Bash approvals are saved to the main checkout's .claude/settings.local.json, and project-scope plugins load in every worktree. While a session is isolated, Claude Code blocks file edits and git commands aimed at the main checkout.
Codex: Worktree mode in the ChatGPT desktop app
The Codex worktrees docs describe this for Codex in the ChatGPT desktop app (and the mobile app controlling a connected computer):
- In a new chat, select Worktree under the composer, and optionally a local environment to run setup scripts.
- Choose the starting branch:
main, a feature branch, or your current branch with unstaged changes, which Codex applies to the worktree. - Submit the prompt. Codex creates the worktree in
$CODEX_HOME/worktreesin a detached HEAD state, so several worktrees don't create a pile of branches. - When it's done, either click Create branch here to commit, push and open a pull request from the worktree, or Hand off the chat to Local to test it in your usual checkout.
Setup works in two parts. Local environments hold setup scripts (for example npm install and npm run build) that run automatically when Codex creates a worktree. The configuration lives in the .codex folder at the project root, so you can commit it for your team. Ignored files go in the same .worktreeinclude file as above, and Codex copies an ignored AGENTS.override.md into managed worktrees on its own. Both copy rules apply to worktrees the desktop app manages, not to ones you create yourself.
By default Codex keeps your 15 most recent managed worktrees. It doesn't delete one tied to a pinned chat, a chat still in progress, or a permanent worktree, and it saves a snapshot before deleting one so you can restore it from the chat.
Using the Codex CLI? The docs above cover the app. In the terminal, make the worktree with git (next section) and start Codex in it, for example codex --cd ../app-auth. Your committed AGENTS.md is part of every worktree, so Codex loads the same instructions there.
Cursor: /worktree, /best-of-n and the Agents Window
Per Cursor's worktrees docs, the UI for worktrees is in the Agents Window: start or move an agent into a worktree there, then review, commit or open a PR from that checkout, or bring the result back into your main workspace. In the IDE you use commands:
-
/worktree fix the failing auth testsruns the rest of that chat in a separate checkout. -
/apply-worktreebrings the changes into your main checkout, and/delete-worktreeremoves the isolated one. -
/best-of-n sonnet,gpt,composer fix the flaky logout testruns the same task on several models, each in its own worktree. It doesn't merge anything; you pick the winner and apply it.
Setup goes in .cursor/worktrees.json, which Cursor checks when it creates a worktree from the Agents Window, the IDE or the Cursor CLI. setup-worktree takes an array of commands or a script path, with setup-worktree-unix and setup-worktree-windows as OS-specific overrides. $ROOT_WORKTREE_PATH points at your main checkout:
{
"setup-worktree": [
"npm ci",
"cp $ROOT_WORKTREE_PATH/.env .env"
]
}
Cursor advises against symlinking dependencies into the worktree and suggests a fast package manager such as pnpm, bun or uv instead. If setup fails, open the Output panel and select Worktrees Setup.
Watch the cleanup. Cursor keeps 25 worktrees per machine by default (cursor.worktreeMaxCount, checked every cursor.worktreeCleanupIntervalHours), and the docs say worktrees created outside its manager, for example with git worktree add, "are eligible for deletion". Commit or push anything you want to keep.
Any agent: plain git
For Codex CLI, Copilot, Windsurf or a mix of tools, create the worktrees yourself. Keeping them next to the repo rather than inside it means there's nothing to add to .gitignore:
git worktree add ../app-auth -b agent/auth
git worktree add ../app-billing -b agent/billing
cp .env ../app-auth/ && cp .env ../app-billing/
git worktree list
cd ../app-auth && claude # terminal 1
cd ../app-billing && codex # terminal 2
Install dependencies in each folder before you trust any test result there. Two errors you'll meet, both from git itself:
-
fatal: 'agent/auth' is already used by worktree at 'รขโฌยฆ/app-auth'when you try to check out a branch that another worktree has. Merge it from main instead (git merge agent/authdoesn't need it checked out), or switch that worktree to another branch first. -
git worktree removerefuses a worktree with modified or untracked files. Commit what you need, then add--force. Removing the folder keeps its branch; delete that separately withgit branch -d.
Split the work so it merges
Worktrees stop agents from overwriting each other's files. They don't stop two agents from making plans that can't both be true. Git merges text, so a rename on one branch and a new call to the old name on another can merge cleanly and then fail to build. A few habits help:
- Give each agent a different area. "Auth middleware" and "billing rounding" merge well. "Refactor the API" and "add an endpoint" don't.
-
Settle shared contracts first. If two tasks depend on the same type, schema or route, land that change on
mainbefore starting them, and base both worktrees on it. - Avoid one shared file that everyone appends to. Translation catalogs, route tables and changelogs are where parallel runs lose entries. Have each agent write its own fragment, then merge them in one step that fails on duplicate or missing keys.
- One integrator. You, or one designated session, merge the branches and resolve conflicts. Then run the full suite on the merged result, not just on each branch.
- Same rules everywhere. Every worktree reads the committed instruction files, so put the commands and a "done means" section in AGENTS.md, and import it from CLAUDE.md as described in one source of truth. Then a Claude Code worktree and a Codex worktree check their work the same way.
Each parallel task is still a normal session. A short plan file per worktree keeps it on track; see the plan-first workflow.
Cleanup at a glance
| Tool | Where worktrees go | Automatic cleanup |
|---|---|---|
| Claude Code | .claude/worktrees/<name>/ |
Clean unnamed sessions removed on exit; otherwise it asks. Subagent and background worktrees swept after cleanupPeriodDays unless they hold work |
| Codex (desktop app) |
$CODEX_HOME/worktrees (change in Settings > Worktrees) |
Keeps the 15 most recent managed worktrees by default; snapshot before deletion |
| Cursor | Cursor's worktree root | Keeps 25 per machine by default; the docs say worktrees made outside its manager can be deleted too |
| Plain git | Wherever you put them | None. git worktree remove, then git worktree prune for folders you deleted by hand |
Checklist
- Make sure the repo has at least one commit and your instruction files are committed.
- One task, one worktree, one branch per agent.
- List ignored files in
.worktreeinclude(Claude Code, Codex app) or copy them in.cursor/worktrees.json(Cursor). - Install dependencies in each worktree; give each dev server its own port.
- Split tasks by area, and land shared contracts on
mainfirst. - Merge through one integrator, then run the full test suite on the result.
- Remove finished worktrees and branches; know your tool's automatic cleanup limit.
Want every worktree to start with the same rules? The free sampler (no email) ships a shared AGENTS.md with a thin CLAUDE.md that imports it, plus /plan-feature and /review-changes for Claude Code, Codex, Cursor, Windsurf and Copilot. The AI Coding Rules Pack adds an agent-safe definition of done and local AGENTS.md examples for risky folders.
FAQ
Can two AI agents work in the same folder at the same time?
They can, but they edit the same files, so one agent's half-finished change lands in the other's build and tests. Give each agent its own git worktree: a separate checkout on its own branch that shares the repository's history. Claude Code (claude --worktree), Codex in the ChatGPT desktop app (Worktree mode) and Cursor (/worktree or the Agents Window) can each create one for you.
Why is my .env missing in the worktree?
A worktree is a fresh checkout, so it only contains tracked files. Gitignored files such as .env or node_modules aren't there. Claude Code and the Codex app copy ignored files listed in a .worktreeinclude file at the repo root; Cursor runs the setup commands in .cursor/worktrees.json, for example cp $ROOT_WORKTREE_PATH/.env .env. Install dependencies in each worktree too.
Why does git say a branch is already used by another worktree?
Git lets a branch be checked out in only one worktree at a time. Check out a different branch in one of them, merge the branch from your main checkout without checking it out, or in Codex use Hand off to move the chat to Local instead.
Does each worktree load my CLAUDE.md or AGENTS.md?
Yes, if the file is committed, because every worktree has its own copy of the tracked files. Edits you make in one worktree don't reach the others until you commit and merge them. One exception: a Claude Code subagent running in its own worktree takes its instruction files from the main conversation. Codex copies an ignored AGENTS.override.md into the worktrees it manages.
How do I clean up old worktrees?
Claude Code offers to remove a worktree when you exit the session and removes clean unnamed ones automatically. The Codex app keeps your 15 most recent managed worktrees by default, and Cursor keeps 25 per machine by default. For worktrees you made yourself, run git worktree list and git worktree remove <path>.
Sources
Official docs, checked 2026-10-22.
- Claude Code docs: Run parallel sessions with worktrees
- Claude Code docs: Common workflows (resume, parallel sessions)
- Codex docs (ChatGPT Learn): Worktrees
- Codex docs (ChatGPT Learn): Local environments (setup scripts)
- Codex docs (ChatGPT Learn): Troubleshooting (code doesn't run on a worktree)
- Codex docs (ChatGPT Learn): Custom instructions with AGENTS.md
- Cursor docs: Worktrees
- Git documentation: git-worktree
If you want a starting point, KitQuarry's free sampler is on GitHub: ai-coding-rules-sampler. It has a short CLAUDE.md/AGENTS.md, security rules and three skills (plan-feature, review-changes, record-decisions) for Claude Code, Cursor, Codex and Windsurf. MIT, free. (I made it.)
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes โ full credit and traffic to the original publisher.