How to Run Parallel Claude Code Agents With Git Worktrees

How to Run Parallel Claude Code Agents With Git Worktrees

Aident AI

Three luminous paths run through separate translucent workspaces from one shared repository hub.

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 origin remote;

  • a current Claude Code installation with --worktree support;

  • workspace trust accepted by running claude once 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:

git fetch origin
git status --short
git worktree list

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 --worktree feature-auth
claude --worktree fix-upload-timeout

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:

.claude/worktrees

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:

git worktree add ../project-feature-auth -b feature-auth origin/main
cd ../project-feature-auth
claude

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:

pwd
git rev-parse --show-toplevel
git branch --show-current
git status --short

Compare the output across terminals.

Check

Expected result

pwd

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:

Work only in the current worktree. Before editing, show pwd, the Git repository
root, the current branch, and git status. Stop if any path resolves to the main
checkout or if the worktree contains changes you did not create

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:

.env.local
config/local-dev.json

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:

# Worktree A
PORT=3101 TEST_DATABASE_NAME=app_feature_auth pnpm dev

# Worktree B
PORT=3102 TEST_DATABASE_NAME=app_upload_timeout pnpm dev

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:

Goal: fix the upload timeout without changing authentication behavior.
Owned files: upload service and its focused tests.
Do not edit: auth, database migrations, lockfiles, or deployment config.
Validation: run the upload service unit tests and reproduce the timeout case.
Handoff: report changed files, test results, risks, and the branch name

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:

git status --short
git diff --check
git diff origin/main...HEAD

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:

git worktree list

Remove a clean, finished worktree through Git:

git worktree remove .claude/worktrees/feature-auth
git worktree prune --dry-run

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:

Follow https://aident.ai/SETUP.md
Confirm my Aident Loadout account and Vault status.
Find one connected read-only Action, inspect its current input schema, and run it
once from this worktree with a harmless input. Do not perform writes

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

Refresh this guide when Claude Code changes --worktree, .worktreeinclude, worktree.baseRef, isolation frontmatter, or cleanup behavior.

Home

Home

Home

Integrations

Integrations

Integrations

Vault

Vault

Vault

Audit

Audit

Audit

Arana Grande

Arana Grande

Arana Grande

Free

Free

Free

30-day audit summary

30-day audit summary

30-day audit summary

Daily action-call volume and the latest receipts from the Loadout audit trail.

Daily action-call volume and the latest receipts from the Loadout audit trail.

Daily action-call volume and the latest receipts from the Loadout audit trail.

View Audit

View Audit

View Audit

Loadout usage

Loadout usage

Loadout usage

617 action calls in the last 30 days

617 action calls in the last 30 days

617 action calls in the last 30 days

May 19 - Jun 17

May 19 - Jun 17

May 19 - Jun 17

10 active days

10 active days

10 active days

Less

Less

Less

More

More

More

Recent activity

Recent activity

Recent activity

Latest action-call receipts from connected agents

Latest action-call receipts from connected agents

Latest action-call receipts from connected agents

Apr 23, 09:23 AM

Apr 23, 09:23 AM

Apr 23, 09:23 AM

Shopify

Shopify

Shopify

Creates Or Updates An Asset For A Theme

Creates Or Updates An Asset For A Theme

Creates Or Updates An Asset For A Theme

Success

Success

Success

Apr 23, 09:21 AM

Apr 23, 09:21 AM

Apr 23, 09:21 AM

Shopify

Shopify

Shopify

Update Products Param Product Id

Update Products Param Product Id

Update Products Param Product Id

Success

Success

Success

Apr 23, 08:53 AM

Apr 23, 08:53 AM

Apr 23, 08:53 AM

Shopify

Shopify

Shopify

Update Products Param Product Id

Update Products Param Product Id

Update Products Param Product Id

Failed

Failed

Failed

Apr 22, 22:13 PM

Apr 22, 22:13 PM

Apr 22, 22:13 PM

Shopify

Shopify

Shopify

Create Product Image

Create Product Image

Create Product Image

Success

Success

Success

Apr 22, 22:12 PM

Apr 22, 22:12 PM

Apr 22, 22:12 PM

Shopify

Shopify

Shopify

Create Product Image

Create Product Image

Create Product Image

Success

Success

Success

Connected integration coverage

Connected integration coverage

Connected integration coverage

162

162

162

of 753 accessible connected

of 753 accessible connected

of 753 accessible connected

Callable actions

Callable actions

Callable actions

1,126

1,126

1,126

Vault credentials

Vault credentials

Vault credentials

8

8

8

Explore what's possible

Explore what's possible

Explore what's possible

See all Integrations

See all Integrations

See all Integrations

Google Ads

Google Ads

Google Ads

All available Goolge Ads tools via...

All available Goolge Ads tools via...

All available Goolge Ads tools via...

X (twitter)

X (twitter)

X (twitter)

All available X tools via...

All available X tools via...

All available X tools via...

Github

Github

Github

All available Github tools via...

All available Github tools via...

All available Github tools via...

Notion

Notion

Notion

All available Notion tools via...

All available Notion tools via...

All available Notion tools via...

Slack

Slack

Slack

All available Slack tools via...

All available Slack tools via...

All available Slack tools via...

Firecrawl

Firecrawl

Firecrawl

All available Firecrawl tools via...

All available Firecrawl tools via...

All available Firecrawl tools via...

753 integrations are available for loadouts.

753 integrations are available for loadouts.

753 integrations are available for loadouts.

Plug your entire stack into your AI agents.

Plug your entire stack into your AI agents.

Plug your entire stack into your AI agents.

Skip the integration headache. Plug 750+ tools into Claude Code, Codex, and OpenClaw in one go, and let your agents execute today.

Skip the integration headache. Plug 750+ tools into Claude Code, Codex, and OpenClaw in one go, and let your agents execute today.