Skip to main content

Claude Code Worktree Complete Guide

AI-assisted

Master Claude Code's Worktree feature - run multiple parallel Agents without conflicts for true parallel development workflows

Introduction

Worktrees are our #1 productivity tip. Run up to 5 parallel terminal instances plus additional web sessions.

When handling complex tasks with Claude Code, you might have encountered this dilemma: you have three independent tasks to work on, but running multiple Claude instances in the same directory causes code conflicts — one Agent is modifying files while another is touching the same files, resulting in a mess when merging.

In February 2025, Anthropic released the --worktree command, completely changing this situation. Now you can run claude -w feature-1, claude -w feature-2, and claude -w bugfix-1 in three terminals, with each Agent working in an isolated environment without interfering with each other.

Understanding Worktree

Git Worktree

A Git feature that allows creating multiple independent working directories from the same repository, each with its own branch and files, but sharing the same .git database. This saves more space than cloning the repository multiple times.

Source: Git DocumentationVisit

Imagine you're an architect designing three different rooms simultaneously. The traditional way is to draw on the same blueprint, which can get messy with constant changes. Worktree gives you three separate blueprints, each dedicated to one room's design, to be merged into the main blueprint later.

Technically, Worktree is a native Git feature. Claude Code's --worktree command wraps this feature to be simpler — one command creates an isolated environment, starts a Claude instance, and auto-cleans up when done.

Why Not Just Clone Multiple Times

You might ask: why not just clone multiple copies?

ApproachDisk UsageSync DifficultyCleanup Complexity
Multiple ClonesFull repo eachManual pull/push neededManual directory deletion
Git WorktreeOnly working files, shared .gitAuto-shared historygit worktree remove
Claude --worktreeSame as aboveSame as aboveAuto-cleanup on exit

Worktrees share the same .git database, so all commit history and branch information is shared. This means commits created in one worktree are immediately visible in others.

Core Usage

Prerequisites

Before using worktree, ensure these conditions are met:

RequirementDescription
Git initializedMust be in a Git repository (has .git directory)
At least one commitCannot create worktree from empty repository
Remote branch availableDefaults to checkout from remote (e.g., origin/main)

Basic Command

Start Claude with the -w or --worktree parameter:

# Create a worktree named "feature-auth" and start Claude
claude -w feature-auth

# Auto-generate a random name (e.g., "bright-running-fox")
claude -w

This command actually does four things:

  1. Creates a new working directory at <repo>/.claude/worktrees/feature-auth/
  2. Creates a new branch named worktree-feature-auth
  3. Checks out code from the default remote branch
  4. Starts Claude Code in the new directory

Directory Structure

your-project/
├── .claude/
│   └── worktrees/
│       ├── feature-auth/      ← First worktree
│       ├── bugfix-123/        ← Second worktree
│       └── refactor-api/      ← Third worktree
├── src/
└── package.json

All worktrees are under .claude/worktrees/. It's recommended to add this path to .gitignore:

# .gitignore
.claude/worktrees/

Creating Worktree During Session

You can also ask Claude to create a worktree during conversation:

> work in a worktree
> start a worktree

Claude will automatically create a worktree and switch to it.

Parallel Development in Practice

Multi-Terminal Workflow

The most common use is running simultaneously in multiple terminal tabs:

# Terminal 1: Handle user authentication feature
claude -w feature-auth

# Terminal 2: Fix payment bug
claude -w bugfix-payment

# Terminal 3: Refactor API module
claude -w refactor-api

Each Claude instance works in its own worktree, with changes not affecting each other. You can:

  • Have Claude develop a new feature in one terminal
  • Have Claude fix bugs in another terminal
  • Continue your own code review in the third

IDE Integration

If you use VS Code or Cursor, the source control panel automatically recognizes all worktrees:

  • Main repo shows as one repository
  • Each worktree shows as an independent repo
  • Can switch, commit, push directly in the IDE

This means you can manage all worktree code changes in the same IDE window without leaving.

Using Tmux

Combine with --tmux parameter to automatically start in a new Tmux session:

claude -w feature-auth --tmux

This way Claude continues running in the background even if you close the terminal.

Environment Initialization

Important: Each new worktree is an independent directory that may need development environment setup:

Project TypeInitialization Steps
Node.jsnpm install or yarn
Pythonpip install -r requirements.txt or activate virtual environment
Gogo mod download
GeneralCopy .env files, set environment variables

You can configure WorktreeCreate Hook to automate these steps (detailed later).

Subagent and Worktree

Worktree applies not only to the main Claude instance but also to Subagents. This enables true parallel task processing.

Configure Subagent to Use Worktree

Add isolation: worktree in the custom Subagent's frontmatter:

---
name: code-migrator
description: Handles large-scale code migrations. Use for batch refactoring.
tools: Read, Write, Edit, Bash, Grep, Glob
isolation: worktree
---

You are a code migration specialist...

Or tell Claude directly in conversation:

> use worktrees for your agents

How It Works

When a Subagent is configured with worktree isolation:

Main Agent (main directory)

├── Start Migration Agent 1 ──→ worktree-migration-1/
│   └── Process src/auth/ directory

├── Start Migration Agent 2 ──→ worktree-migration-2/
│   └── Process src/api/ directory

└── Start Migration Agent 3 ──→ worktree-migration-3/
    └── Process src/utils/ directory

Each Subagent works independently in its own worktree without interference. After completion, the worktree is automatically cleaned up (if there are no uncommitted changes).

Use Cases

ScenarioEffect
Large-scale code migrationMultiple Agents process different modules in parallel
Batch refactoringEach Agent handles one type of file
Competitive implementationMultiple Agents independently implement the same feature, choose the best

This is especially powerful for large batched changes and code migrations.

Cleanup and Management

Auto Cleanup

When exiting a worktree session, Claude handles it based on the situation:

StateHandling
No changesAuto-delete worktree and branch
Changes or commits existPrompt you to keep or delete

Kept worktrees persist for you to continue working later.

Manual Management

For manual worktree management, use standard Git commands:

# List all worktrees
git worktree list

# Manually delete a worktree
git worktree remove .claude/worktrees/feature-auth

# Clean up stale worktree references
git worktree prune

Automating with Hooks

Claude Code provides WorktreeCreate and WorktreeRemove Hooks to automate environment setup and cleanup:

{
  "hooks": {
    "WorktreeCreate": [
      {
        "command": "npm install && cp ../.env .env"
      }
    ],
    "WorktreeRemove": [
      {
        "command": "echo 'Worktree cleaned up'"
      }
    ]
  }
}

This way dependencies are auto-installed and environment files are auto-copied when creating worktrees.

Best Practices

Quantity Control

For best results, stick to 3-4 active worktrees per team. Too many worktrees can become hard to manage, cause memory bloat in Claude sessions, and reduce focus.

Claude Code Best PracticesClaude Code Worktree Guide

Don't be greedy. While you can technically open many worktrees:

  • Each Claude instance consumes API quota
  • Too many parallel tasks are hard to track
  • Merging may have more complex conflicts

Task Suitability

Good for WorktreeNot Ideal
Independent feature developmentQuick changes under 10 minutes
Parallel refactoring of different modulesTasks requiring frequent interaction
Long-running tasksStrong dependency on ongoing changes
Isolated experimental changesSimple bug fixes

Context Preservation

Run /init at the start of each worktree session to ensure Claude properly understands the current working directory context:

/init

This makes Claude re-read the project structure and CLAUDE.md configuration.

Naming Conventions

Develop good naming habits for easier management:

# Good naming
claude -w feature-user-auth
claude -w bugfix-payment-123
claude -w refactor-api-v2

# Bad naming
claude -w test
claude -w temp
claude -w 1

Non-Git Version Control

If you use SVN, Perforce, or Mercurial, you can configure Hooks to achieve similar isolation:

{
  "hooks": {
    "WorktreeCreate": [
      {
        "command": "your-vcs-checkout-command"
      }
    ],
    "WorktreeRemove": [
      {
        "command": "your-vcs-cleanup-command"
      }
    ]
  }
}

After configuring these Hooks, using --worktree will call your custom commands instead of default Git behavior.

My Experience

When to Use Worktree

My rule of thumb: If a task takes more than 30 minutes, consider using worktree.

Short tasks waste time with worktree — creating environment, installing dependencies, and merging at the end might take longer than the task itself. But for tasks requiring deep work, worktree's isolation becomes valuable.

Combining with Ralph

Worktree and Ralph are natural partners:

# Run Ralph loop in worktree
claude -w feature-x
# Then start Ralph loop in the session

Each Ralph loop runs in its own worktree, so even if the loop fails, it won't affect the main branch.

Competitive Implementation

An interesting use case is having multiple Agents independently implement the same feature:

# Run in three terminals separately
claude -w feature-search-v1
claude -w feature-search-v2
claude -w feature-search-v3

Give them the same requirements and let them implement independently. Compare the three solutions at the end and merge the best one. This leverages LLM non-determinism — the same input can produce different outputs, sometimes the second version is better.

UI Design Comparison

Another practical scenario is UI design exploration. Suppose you want to redesign your app's interface but aren't sure which style works best:

# Let three Agents implement different styles
claude -w ui-minimal        # Minimalist style
claude -w ui-colorful       # Vibrant colors
claude -w ui-glassmorphism  # Glass morphism style

Each Agent develops independently in its own worktree. When finished, you can:

  1. Run all three versions simultaneously (different ports)
  2. Compare effects side by side
  3. Merge the most satisfying solution to main branch

This is much more efficient than the traditional "change, review, unsatisfied, change again" workflow.

Conclusion

Worktree is a feature the Claude Code team uses every day, with Boris Cherny calling it "the #1 productivity tip".

The core value is simple: Let multiple Agents work in parallel without interfering with each other. You no longer need to wait for one task to complete before starting the next, no longer worry about conflicts from parallel modifications.

Remember three key points:

PointDescription
IsolationEach worktree is an independent working directory
SharingAll worktrees share the same Git history
AutomaticClaude auto-handles creation and cleanup

Getting started is simple:

claude -w your-task-name

Related Reading:

References:

Video Tutorials:

Comments

Table of Contents