Git Worktrees & Claude Code: Complete Guide
Master git worktrees for parallel development with Claude Code. Learn worktree lifecycle, subagent isolation, batch processing, and hook configurations for AI-assisted multi-branch workflows.
Contents: 1. Worktree Fundamentals • 2. Claude Code Integration • 3. Parallel Workflows • 4. Subagent Isolation • 5. Session Management • 6. Lifecycle • 7. VCS Hooks • 8. Best Practices • 9. Troubleshooting • 10. Challenges
🌳 1. What Are Git Worktrees?
Git worktrees are a native Git feature that allows you to have multiple working directories attached to a single repository. Each worktree has its own working directory with a separate set of files, is checked out to its own branch, shares the same Git history, objects, and remote connections, and operates independently of other worktrees.
Key Benefit: No more git stash and context switching. Work on a feature, hotfix, and docs update simultaneously in separate directories.
Native Git Worktree Commands
These are the core git commands for managing worktrees:
# Native Git Worktree Commands# Create a new worktree with existing branchgit worktree add ../feature-branch feature-branch# Create a new worktree with NEW branch from current HEADgit worktree add -b feature-branch ../feature-branch# List all worktreesgit worktree list# /home/user/project abc1234 [main]# /home/user/feature-branch def5678 [feature-branch]# Remove a worktree (directory must be clean)git worktree remove ../feature-branch# Prune stale worktree referencesgit worktree prune
🤖 2. How Claude Code Uses Worktrees
Claude Code provides a managed worktree experience that abstracts away the complexity of manual worktree management. Worktrees are automatically created in .claude/worktrees/<name>/, branches are named worktree-<name>, and unchanged worktrees are automatically cleaned up on session exit.
Integration Points:
• Automatic Creation: Creates worktrees in .claude/worktrees/<name>/
• Branch Naming: Branches automatically named worktree-<name>
• Base Branch: Worktrees branch from your default remote branch (usually main)
• Cleanup: Automatic cleanup of unchanged worktrees on session exit
• Session Isolation: Each worktree maintains its own Claude session state
Getting Started
Start Claude Code in a worktree with a single command:
# Claude Code Worktree Integration# Create and enter a named worktreeclaude --worktree feature-auth# Create with auto-generated nameclaude --worktree# Short formclaude -w feature-auth# What happens on creation:# 1. Directory created: .claude/worktrees/feature-auth/# 2. Branch created: worktree-feature-auth (from main)# 3. Working directory set to the worktree# 4. Claude session starts in isolated environment
.claude/worktrees/ to your .gitignore to prevent worktree contents from appearing as untracked files.⚡ 3. Parallel Development Workflows
The primary use case for worktrees is running multiple Claude sessions simultaneously. Each session works on isolated files, makes commits to its own branch, can create its own PR, and doesn't interfere with other sessions.
Multiple Terminal Sessions
# Terminal 1: Authentication featureclaude --worktree feature-auth> "Implement OAuth2 login flow"# Terminal 2: Bug fix (separate terminal window)claude --worktree bugfix-memory-leak> "Find and fix the memory leak in the cache module"# Terminal 3: Documentationclaude --worktree docs-api> "Generate API documentation for all endpoints"# Each session:# - Works on isolated files# - Makes commits to its own branch# - Can create its own PR# - Doesn't interfere with other sessions
Sequential vs Parallel Time Savings
Worktrees let you run tasks in parallel, dramatically reducing total development time:
🔒 4. Subagent Isolation
Claude Code subagents can use worktree isolation for parallel operations. When an agent spawns in a fresh worktree, all changes are isolated from the main session. On completion, unchanged worktrees are auto-deleted while worktrees with changes return their path and branch in the result.
Agent Definition with Isolation
Create an agent file with isolation: worktree in the frontmatter:
---name: parallel-refactordescription: Refactor code in isolated worktreeisolation: worktree---Refactor the specified module following the project's coding standards.Apply consistent naming conventions and extract reusable utilities.
Batch Processing Pattern: For processing many files or modules, spawn multiple agents — each in its own worktree — handling a subset of files. This scales linearly with the number of available worktrees.
📋 5. Session Management
Sessions in worktrees can be resumed like any other session. The session picker is worktree-aware and groups sessions by their context. Each worktree maintains its own conversation history, file edit history, tool permission states, and working directory context.
# Resuming Worktree Sessions# List available sessionsclaude --resume# Resume specific session by ID or descriptionclaude --resume feature-auth# Resume with interactive pickerclaude --resume# Switching Between Worktrees# Option 1: Open new terminalcd .claude/worktrees/feature-b && claude --resume# Option 2: Exit current, enter another# (In Claude session)> "Exit this worktree, keep it"# Then start new sessionclaude --worktree feature-b
In-Session Tools:
• EnterWorktree: Creates a worktree and switches the session into it. Optional name parameter.
• ExitWorktree: Exits a worktree session. Requires action: "keep" or "remove". Use discard_changes: true when removing with uncommitted changes.
🔄 6. Worktree Lifecycle
Understanding the full worktree lifecycle helps you manage them effectively. From creation to cleanup, each stage has specific behaviors and options.
Exit Behavior:
• No changes: Worktree and branch are automatically deleted
• Has changes: You're prompted to keep or remove the worktree
• Keep: Preserves the directory and branch for later resumption
• Remove: Deletes everything (requires confirmation if uncommitted changes exist)
Merging Worktree Changes
After completing work in a worktree, merge changes back into the main branch:
# Merging Worktree Changes# Option 1: Create PR from worktree branchcd .claude/worktrees/my-featuregh pr create --base main --head worktree-my-feature# Option 2: Merge locallycd ~/your-project # Main directorygit merge worktree-my-feature# Option 3: Cherry-pick specific commitsgit cherry-pick <commit-hash># Cleanup after mergegit worktree remove .claude/worktrees/my-featuregit branch -d worktree-my-feature
🪝 7. Hooks for Custom VCS
If you use a non-Git version control system (SVN, Perforce, Mercurial), configure custom hooks in settings.json. The WorktreeCreate hook fires when creating a worktree and must output JSON with the worktree path. The WorktreeRemove hook handles cleanup.
Hook Configuration (settings.json)
{"hooks": {"WorktreeCreate": [{"command": "scripts/create-workspace.sh $WORKTREE_NAME","timeout": 30000}],"WorktreeRemove": [{"command": "scripts/remove-workspace.sh $WORKTREE_PATH","timeout": 30000}]}}
Custom Hook Script Example
#!/bin/bash# create-workspace.sh — Custom VCS worktree hookWORKTREE_NAME=$1WORKTREE_PATH="/path/to/workspaces/$WORKTREE_NAME"# Create isolated workspace (your VCS-specific logic)# Example for Perforce:p4 client -o | sed "s/Root:.*/Root: $WORKTREE_PATH/" | p4 client -ip4 sync //depot/...@head# Output JSON (required by Claude Code)echo "{\"path\": \"$WORKTREE_PATH\"}"
Environment Variables Available: $WORKTREE_NAME, $WORKTREE_PATH, $WORKTREE_BRANCH, and $PROJECT_ROOT are available in hook commands.
✅ 8. Best Practices
Follow these guidelines to get the most out of git worktrees with Claude Code. From naming conventions to dependency management, these patterns keep your workflow clean and efficient.
# ✅ Good: Descriptive, lowercase names with hyphensclaude --worktree feature-user-authclaude --worktree bugfix-memory-leakclaude --worktree refactor-api-layer# ❌ Avoid: Vague or non-standard namesclaude --worktree tempclaude --worktree test123claude --worktree FEATURE_AUTH# ✅ One worktree = one task/PRclaude --worktree add-login-buttonclaude --worktree fix-password-validation# ❌ Avoid: Kitchen sink worktreeclaude --worktree various-improvements# Dependency management per worktreecd .claude/worktrees/my-featurenpm install # Each worktree needs its own node_modules# Git aliases for convenience# In ~/.gitconfig:# [alias]# wt = worktree# wtl = worktree list# wta = worktree add# wtr = worktree remove
Quick Checklist:
• Add .claude/worktrees/ to .gitignore
• Run npm install in each worktree
• One worktree = one focused task
• Clean up unused worktrees regularly with git worktree prune
• Use different ports for dev servers across worktrees
Limitations & Watch Outs:
• Running multiple dev servers requires different ports per worktree
• Local databases may conflict — use separate DBs or schemas
• Lock files may need cleanup between worktrees
• Each worktree needs its own dependency installation
🔧 9. Troubleshooting
Common issues and their solutions when working with git worktrees. From branch conflicts to cleanup problems, here are the diagnostic commands and fixes you need.
# Diagnostic Commands for Troubleshooting# List all worktrees with detailsgit worktree list --porcelain# Check worktree statuscd .claude/worktrees/my-feature && git status# View worktree branch commitsgit log worktree-my-feature --oneline -10# Compare worktree to maingit diff main...worktree-my-feature# Clean up all stale referencesgit worktree prune --verbose# Fix: "fatal: '<path>' is already checked out"git worktree list # Find where branch is checked outgit worktree remove <path> # Remove stale worktree# Fix: Worktree path already existsgit worktree prunerm -rf .claude/worktrees/my-feature # Manual cleanupclaude --worktree my-feature # Try again
🎯 10. Use Cases
Worktrees shine in many real-world scenarios. Here are the most impactful use cases with Claude Code.
1. Parallel Feature Development: Build multiple independent features simultaneously. Start three feature branches, each Claude session works independently, create PRs from each when ready.
2. Urgent Bug Fix During Feature Work: Production bug discovered while deep in feature development? Create an isolated worktree for the hotfix — no stashing, no lost context. Fix the bug, create PR, merge, and return to your feature work.
3. Exploratory Refactoring: Try multiple approaches to a refactor in separate worktrees. Compare results with git diff worktree-approach-a worktree-approach-b, keep the better approach. No risk, easy cleanup.
4. Large-Scale Code Migrations: Divide work across multiple worktrees or use subagents with isolation. Each processes a subset in parallel, dramatically reducing migration time.
5. Learning & Experimentation: Try new libraries or patterns without risk. If it works, merge or create a PR. If it fails, delete the worktree — no cleanup needed.
🏆 11. Hands-On Challenges
Test your understanding of git worktrees and Claude Code integration. Complete these challenges in the editor below — try writing the commands yourself before revealing the solution!
Write your commands in the editor below. When you're ready, click the solution toggle to compare your answer. The progress bar above tracks your completion. Challenges progress from beginner to advanced.
# Challenge 1: Basic Worktree Operations## You're working on the main branch and get three tasks:# - Feature: add search functionality# - Bugfix: fix login timeout# - Docs: update API documentation## Write git commands to:# 1. Create a worktree for each task (from main)# 2. List all active worktrees# 3. Check branches in each worktree# 4. Remove the docs worktree after it's done# 5. Prune stale references## Write your commands below:
# Challenge 2: Claude Code Parallel Development## You need to use Claude Code worktrees to:# 1. Start 3 parallel Claude sessions for:# - Implementing a REST API endpoint# - Writing integration tests# - Creating a database migration# 2. Each should use short-form flag# 3. After work is done, create PRs from each# 4. Clean up worktrees that had no changes## Write your commands below:
# Challenge 3: Subagent Isolation & Batch Processing## You have a large codebase migration:# - 40 files need updating from API v1 to v2# - You want to split across 4 agents# - Each agent works in isolation## Create an agent definition file (.claude/agents/batch-migrate.md)# that uses worktree isolation, then write the commands to:# 1. Define the agent with proper frontmatter# 2. Spawn 4 agents, each handling 10 files# 3. Describe how results are merged## Write your agent definition and commands below:
If you've completed all 3 challenges, you have a solid understanding of git worktrees with Claude Code! You can now manage parallel development workflows, use subagent isolation for batch processing, and troubleshoot common worktree issues. Keep practicing with real projects to master the workflow.
🎯 Conclusion
Git worktrees combined with Claude Code create a powerful parallel development workflow. Instead of context-switching between branches, you maintain multiple isolated working directories — each with its own Claude session — working simultaneously on different tasks.
The key insights are: worktrees eliminate stashing and branch switching overhead, Claude Code's managed worktree experience handles the complexity for you, subagent isolation enables batch processing at scale, and the worktree lifecycle ensures clean resource management with automatic cleanup.
Key Takeaways:
• Worktrees enable truly parallel development — no more sequential context switching
• Claude Code manages worktree lifecycle automatically
• Subagent isolation scales batch processing across multiple worktrees
• Custom hooks support non-Git VCS workflows
• One worktree per task keeps work focused and PRs clean
• Automatic cleanup prevents worktree sprawl