Aident AI

How to Run Parallel Claude Code Agents With Git Worktrees
The safest way to run parallel Claude Code agents in one repository is to give each coding task its own Git worktree. Start each session with claude --worktree <name>, verify that its repository root and branch are different from the others, initialize its local environment, and let one human or coordinator own integration. The worktrees isolate file edits and staging areas, but they do not automatically isolate ports, databases, external services, or merge conflicts.
This guide gives you a reproducible setup, observable checks, and fixes for the failures that make parallel sessions write to the wrong checkout or interfere with each other.
Prerequisites
You need:
a Git repository with an
originremote;a current Claude Code installation with
--worktreesupport;workspace trust accepted by running
claudeonce in the main checkout;a clean main checkout or a deliberate plan for uncommitted work;
two tasks that can be completed and reviewed independently.
Choose separate tasks, not two halves that constantly edit the same files. A feature and an unrelated bug fix are good candidates. Two agents rewriting the same dependency graph or schema are not.
Step 1: Check the Main Checkout
Fetch the remote and inspect your starting state:
Expected result: git status --short is empty, and git worktree list shows the main checkout plus any worktrees you already recognize.
If the checkout is dirty, commit the intended work or stop. Do not ask an agent to clean up files it does not own. Claude Code normally creates a fresh worktree from origin/HEAD; if you need your current unpushed branch state instead, configure worktree.baseRef as "head" before creating the worktree.
Step 2: Start One Claude Code Session per Task
Open separate terminals from the repository root and give each worktree a descriptive name:
Claude Code creates each checkout under .claude/worktrees/<name>/ by default and starts the session there. Add the generated directory to .gitignore if your repository does not already ignore it:
Expected result: each session has its own directory and branch. Neither session should report untracked files from the other.
You can also create worktrees manually when you need an explicit path or starting ref:
The native Claude Code command is simpler for routine parallel sessions. Manual git worktree add is useful when a repository has custom branch or directory conventions.
Step 3: Prove Each Agent Is in the Right Worktree
Before either agent edits a file, ask it to run:
Compare the output across terminals.
Check | Expected result |
|---|---|
| A different worktree directory in each session |
Repository root | Matches that session's worktree, not the main checkout |
Branch | A different branch for each task |
Status | Clean before the task starts |
Then put the boundary in each prompt:
This check catches stale instructions or absolute paths before they cause damage. If a CLAUDE.md, memory file, script, or task description contains a path to the main checkout, replace it with a repository-relative path or the current worktree root.
Step 4: Initialize Dependencies and Local Configuration
A worktree contains tracked files, not the untracked or ignored files from your main checkout. Missing .env.local, virtual environments, generated files, and installed dependencies are expected.
Claude Code can copy selected ignored files with a root-level .worktreeinclude file. It uses .gitignore patterns, and a file must also be ignored by Git to qualify:
Copy only local development configuration. Do not copy production credentials into every worktree. For repeatable setup, use a WorktreeCreate hook to install dependencies or generate safe local files, and make the hook fail fast when setup fails.
Expected result: each worktree can run the task's targeted test command without reading files from the main checkout.
When an agent needs an external API, prefer a managed, scoped connection over duplicating raw keys into every checkout. Aident Loadout lets the agent discover a connected Action, inspect its current schema, and run it without putting the provider credential in the prompt or repository.
Step 5: Isolate Runtime State, Not Just Files
Git worktrees isolate checked-out files and branches. They can still collide through shared runtime state.
Assign separate values where the task starts local services:
Use your project's real commands and supported configuration. Do not invent a second database if the test suite cannot safely create one.
Check these shared resources before running tasks concurrently:
application and debugger ports;
test databases, schemas, queues, and local object storage;
Docker container and Compose project names;
browser profiles and test accounts;
generated caches outside the repository;
cloud sandboxes and mutable integration fixtures.
Expected result: stopping or resetting one task does not interrupt or erase the other task's test state.
Step 6: Give Each Agent an Independent Contract
Write one task contract per worktree:
The contract should define the outcome, allowed surface, validation, and handoff. If two contracts own the same file, either sequence the tasks or assign one integrator. A worktree prevents simultaneous filesystem writes; it cannot make incompatible changes merge cleanly.
For one Claude Code session delegating to subagents, request worktree isolation or set isolation: worktree in the custom subagent frontmatter. Use subagents for bounded side work. Use separate top-level sessions when you want to supervise each conversation directly.
Step 7: Review and Integrate One Branch at a Time
When a task finishes, review it from that worktree:
Run the repository's focused tests, then push or open a pull request through the normal project workflow. Integrate the lower-risk or foundational branch first. Update the other branch onto the new base, rerun its tests, and resolve conflicts with full context.
Expected result: each pull request contains only its task, each validation result can be reproduced from a clean checkout, and the second branch still passes after the first lands.
Do not let multiple agents independently resolve the same merge conflict. One integrator should decide which behavior survives.
Step 8: Remove Finished Worktrees Safely
List the worktrees before cleanup:
Remove a clean, finished worktree through Git:
Use the exact path reported by git worktree list. Do not delete the directory manually, and do not use --force until you have confirmed there are no uncommitted files or commits to preserve.
Expected result: the finished checkout disappears from git worktree list, while the main checkout and active task remain untouched.
Common Parallel Worktree Failures
The Agent Writes to the Main Checkout
Stop the session before moving files. Compare pwd, git rev-parse --show-toplevel, and the paths in project instructions or memory. Restart Claude Code from the intended worktree. Avoid absolute paths that point to the main checkout.
.env.local or Dependencies Are Missing
That is normal for a fresh checkout. Put safe ignored files in .worktreeinclude, automate deterministic initialization with a WorktreeCreate hook, or use a managed external connection. Do not fix the error by committing a secret.
Both Apps Try to Use the Same Port
Give every session a distinct port and any related callback URL. Check child services too; a frontend port can differ while both instances still target the same backend or test database.
The Worktree Starts From the Wrong Commit
Claude Code defaults to a fresh base from origin/HEAD when available. Fetch the remote first. Set worktree.baseRef to "head" only when the task intentionally needs current local commits. For a specific pull request, use claude --worktree "#1234".
Two Branches Produce a Lockfile or Migration Conflict
Worktrees isolate edits, not intent. Sequence dependency or schema changes under one owner. Rebase or restack the later branch after the first lands, regenerate the shared artifact once, and rerun both targeted and integration tests.
The Worktree Cannot Be Removed
Run git status --short inside it. Git refuses to remove a dirty worktree without force. Preserve the changes, finish the branch, or explicitly discard them only after review.
Why This Pattern Works
A branch separates histories. A worktree also separates the checked-out files and index, which is the boundary a coding agent actually edits. One task per worktree makes ownership observable: the directory, branch, diff, tests, and pull request all point to the same unit of work.
The remaining failures come from state Git does not isolate, so the setup handles those explicitly: local configuration, processes, databases, external credentials, task ownership, and integration order.
The pattern follows the evidence-backed structure behind Aident's Ollama networking guide: name the exact problem, show the fix early, provide commands and expected results, explain why the fix works, and cover concrete failure modes. For additional agent safeguards, see how to prevent Codex from deleting files and how to audit an Agent Skill before installing it.
After your worktrees are isolated, verify one external Action without copying a raw credential into either checkout:
Use Aident Loadout to complete the check. Measure success as two isolated worktrees with distinct roots and branches, plus one schema-inspected read-only Action that succeeds without a provider key in the prompt.
Sources
Run parallel sessions with worktrees, Claude Code documentation, accessed July 25, 2026
Run agents in parallel, Claude Code documentation, accessed July 25, 2026
Claude Code power user tips, Claude Help Center, accessed July 25, 2026
Git worktree documentation, Git, accessed July 25, 2026
Refresh this guide when Claude Code changes --worktree, .worktreeinclude, worktree.baseRef, isolation frontmatter, or cleanup behavior.


