DEV Community

Cover image for Supercharge Your AI Coding Workflow: A Complete Guide to Git Worktrees with Claude Code
Bilal Haidar
Bilal Haidar

Posted on

Supercharge Your AI Coding Workflow: A Complete Guide to Git Worktrees with Claude Code

In the age of AI assisted development, our workflows are evolving rapidly. Tools like Claude Code are transforming how we write, refactor, and debug code. But with this power comes a new challenge: how do we safely let an AI agent make substantial changes to our codebase while maintaining control and continuing our own work? Enter Git worktrees, a powerful yet underutilized feature that pairs exceptionally well with AI coding assistants.

This guide will take you from worktree basics to advanced workflows specifically designed for AI assisted development. Whether you're a seasoned developer or just starting to integrate AI into your workflow, you'll find practical strategies to boost your productivity while maintaining code quality.

What Are Git Worktrees?

Git worktrees allow you to have multiple working directories attached to the same repository simultaneously. Think of them as parallel universes for your codebase, each checked out to a different branch, but all sharing the same Git history and object database.

Unlike cloning a repository multiple times (which duplicates everything), worktrees are lightweight. They share the .git directory with your main working copy, meaning:

  • No duplicate repository data eating up disk space
  • All worktrees stay synchronized with the same remote
  • Commits made in any worktree are immediately visible to all others
  • Branch operations in one worktree affect the shared repository

The Traditional Problem

Before worktrees, if you needed to work on multiple branches simultaneously, you had limited options:

  1. Stash and switch: Constantly stashing your work, switching branches, then unstashing. This is error prone and disruptive.

  2. Multiple clones: Cloning the repository multiple times. This wastes disk space and creates synchronization headaches.

  3. Just deal with it: Finishing one task completely before starting another. This kills productivity when you're blocked or need to context switch.

The Worktree Solution

Worktrees eliminate these compromises. You can have your main branch checked out in one directory, your feature/authentication branch in another, and a bugfix/login-error branch in a third, all simultaneously accessible and all sharing the same repository.

my-project/                    # Main worktree (main branch)
my-project-feature-auth/       # Worktree for authentication feature
my-project-bugfix-login/       # Worktree for login bugfix
Enter fullscreen mode Exit fullscreen mode

Each directory is a fully functional working copy. You can open them in separate IDE windows, run different dev servers, and switch between them instantly by simply changing directories.

Git Worktree Commands: The Complete Reference

Before diving into AI specific workflows, let's master the worktree commands you'll use daily.

Creating Worktrees

Create a worktree for an existing branch:

git worktree add ../my-project-feature ../path/to/worktree branch-name
Enter fullscreen mode Exit fullscreen mode

Create a worktree with a new branch:

git worktree add -b new-branch-name ../path/to/worktree
Enter fullscreen mode Exit fullscreen mode

Create a worktree based on a specific commit or tag:

git worktree add ../path/to/worktree commit-hash
git worktree add ../path/to/worktree v1.2.3
Enter fullscreen mode Exit fullscreen mode

Create a detached HEAD worktree (useful for exploration):

git worktree add --detach ../path/to/worktree HEAD
Enter fullscreen mode Exit fullscreen mode

Listing Worktrees

View all worktrees:

git worktree list
Enter fullscreen mode Exit fullscreen mode

This outputs something like:

/home/user/projects/my-app           abc1234 [main]
/home/user/projects/my-app-feature   def5678 [feature/new-ui]
/home/user/projects/my-app-bugfix    ghi9012 [bugfix/login]
Enter fullscreen mode Exit fullscreen mode

Get detailed information:

git worktree list --porcelain
Enter fullscreen mode Exit fullscreen mode

Removing Worktrees

Remove a worktree (the safe way):

git worktree remove ../path/to/worktree
Enter fullscreen mode Exit fullscreen mode

Force remove (if there are uncommitted changes):

git worktree remove --force ../path/to/worktree
Enter fullscreen mode Exit fullscreen mode

Clean up stale worktree references:

If you manually delete a worktree directory, Git still tracks it. Clean up with:

git worktree prune
Enter fullscreen mode Exit fullscreen mode

Moving and Repairing Worktrees

Move a worktree to a new location:

git worktree move ../old/path ../new/path
Enter fullscreen mode Exit fullscreen mode

Repair worktree references after moving the main repository:

git worktree repair
Enter fullscreen mode Exit fullscreen mode

Locking Worktrees

Prevent a worktree from being pruned (useful for worktrees on removable drives):

git worktree lock ../path/to/worktree
git worktree lock --reason "On external backup drive" ../path/to/worktree
git worktree unlock ../path/to/worktree
Enter fullscreen mode Exit fullscreen mode

Why Worktrees Are Perfect for AI Assisted Development

Now let's explore why worktrees and AI coding assistants are a match made in developer heaven.

The AI Agent Challenge

When you're using an AI coding tool like Claude Code, you're essentially giving an intelligent agent access to modify your files. This creates unique challenges:

  1. Concurrent work: While the AI is refactoring your authentication module, you might want to continue working on the UI. Without worktrees, you're blocked.

  2. Experimentation safety: AI suggestions might be brilliant or they might break everything. You need a safe space to evaluate them.

  3. Context preservation: If the AI's changes don't work out, reverting shouldn't disrupt your other work.

  4. Multiple AI tasks: You might want to run multiple AI assisted tasks in parallel, each exploring different approaches.

The Worktree Advantage

Worktrees solve all these problems elegantly:

  • Isolation: AI changes happen in a separate directory. Your main work is untouched.
  • Parallelism: Run multiple AI tasks simultaneously in different worktrees.
  • Easy comparison: Diff between worktrees to evaluate AI suggestions against your original code.
  • Zero risk experimentation: Delete a worktree and its branch if the AI's approach doesn't pan out.
  • Continuous productivity: Keep working in your main worktree while AI processes in another.

Setting Up a Worktree Based AI Workflow

Let's build a practical workflow from the ground up.

Project Structure

I recommend organizing your worktrees in a consistent pattern. Here's a structure that works well:

~/projects/
├── my-app/                      # Main worktree (main/develop branch)
├── my-app-ai-refactor/          # AI working on refactoring task
├── my-app-ai-feature/           # AI implementing new feature
└── my-app-ai-experiment/        # AI exploring experimental approach
Enter fullscreen mode Exit fullscreen mode

Why Use Helper Scripts?

While you can create and remove worktrees manually with Git commands, helper scripts provide several important benefits when working with AI assistants:

Consistency: When you're creating multiple worktrees throughout the day for different AI tasks, it's easy to make typos or forget your naming convention. Scripts enforce a consistent pattern every time.

Reduced cognitive load: Instead of remembering the exact syntax for worktree commands, branch naming patterns, and directory paths, you just run one command with a task name.

Error prevention: The scripts include validation to prevent common mistakes like forgetting to specify a task name or accidentally deleting the wrong worktree.

Onboarding: If you work on a team, scripts make it easy for everyone to follow the same workflow without memorizing commands.

Documentation: The scripts themselves serve as documentation for your workflow. New team members can read them to understand the process.

Where to Save Your Scripts

You have several options for where to store these scripts:

Option 1: In your project repository (recommended for team workflows)

my-project/
├── scripts/
│   ├── create-ai-worktree.sh
│   └── cleanup-ai-worktree.sh
├── src/
└── ...
Enter fullscreen mode Exit fullscreen mode

Option 2: In your home directory (recommended for personal use across projects)

~/bin/
├── create-ai-worktree.sh
└── cleanup-ai-worktree.sh
Enter fullscreen mode Exit fullscreen mode

If using ~/bin/, make sure it's in your PATH by adding this to your .bashrc or .zshrc:

export PATH="$HOME/bin:$PATH"
Enter fullscreen mode Exit fullscreen mode

Option 3: As Git aliases (covered later in the Advanced section)

The Creation Script

This script automates the creation of a new worktree specifically for AI assisted tasks:

#!/bin/bash
# create-ai-worktree.sh
#
# Purpose: Creates a new Git worktree with a standardized naming convention
#          for AI assisted development tasks.
#
# Usage: ./create-ai-worktree.sh <task-name>
# Example: ./create-ai-worktree.sh refactor-auth

# Get the project name from the Git repository root directory name
PROJECT_NAME=$(basename $(git rev-parse --show-toplevel))

# Get the task name from the first argument
TASK_NAME=$1

# Build standardized names for the branch and worktree directory
BRANCH_NAME="ai/${TASK_NAME}"
WORKTREE_PATH="../${PROJECT_NAME}-ai-${TASK_NAME}"

# Validate that a task name was provided
if [ -z "$TASK_NAME" ]; then
    echo "Usage: create-ai-worktree.sh <task-name>"
    echo ""
    echo "Examples:"
    echo "  create-ai-worktree.sh payment-integration"
    echo "  create-ai-worktree.sh refactor-auth"
    echo "  create-ai-worktree.sh bug-fix-login"
    exit 1
fi

# Check if the branch already exists
if git show-ref --verify --quiet "refs/heads/${BRANCH_NAME}"; then
    echo "Error: Branch '${BRANCH_NAME}' already exists."
    echo "Either delete it first or choose a different task name."
    exit 1
fi

# Create the new branch and worktree simultaneously
git worktree add -b "$BRANCH_NAME" "$WORKTREE_PATH"

# Provide helpful output
echo ""
echo "=========================================="
echo "AI Worktree Created Successfully!"
echo "=========================================="
echo ""
echo "Worktree location: $WORKTREE_PATH"
echo "Branch name:       $BRANCH_NAME"
echo ""
echo "Next steps:"
echo "  1. cd $WORKTREE_PATH"
echo "  2. Install dependencies (composer install, npm install, etc.)"
echo "  3. Launch Claude Code: claude"
echo ""
echo "When finished:"
echo "  cleanup-ai-worktree.sh $TASK_NAME"
Enter fullscreen mode Exit fullscreen mode

The Cleanup Script

This companion script safely removes a worktree and its associated branch when you're done:

#!/bin/bash
# cleanup-ai-worktree.sh
#
# Purpose: Safely removes an AI worktree and its associated branch.
#          Includes confirmation to prevent accidental deletion.
#
# Usage: ./cleanup-ai-worktree.sh <task-name>
# Example: ./cleanup-ai-worktree.sh refactor-auth

PROJECT_NAME=$(basename $(git rev-parse --show-toplevel))
TASK_NAME=$1
BRANCH_NAME="ai/${TASK_NAME}"
WORKTREE_PATH="../${PROJECT_NAME}-ai-${TASK_NAME}"

# Validate that a task name was provided
if [ -z "$TASK_NAME" ]; then
    echo "Usage: cleanup-ai-worktree.sh <task-name>"
    echo ""
    echo "Current AI worktrees:"
    git worktree list | grep "\-ai\-"
    exit 1
fi

# Check if the worktree exists
if [ ! -d "$WORKTREE_PATH" ]; then
    echo "Error: Worktree not found at $WORKTREE_PATH"
    echo ""
    echo "Current worktrees:"
    git worktree list
    exit 1
fi

# Show what will be deleted and ask for confirmation
echo "This will remove:"
echo "  Worktree: $WORKTREE_PATH"
echo "  Branch:   $BRANCH_NAME"
echo ""

# Check for uncommitted changes
cd "$WORKTREE_PATH"
if [ -n "$(git status --porcelain)" ]; then
    echo "WARNING: This worktree has uncommitted changes!"
    git status --short
    echo ""
fi
cd - > /dev/null

read -p "Are you sure you want to continue? (y/n) " -n 1 -r
echo ""

if [[ $REPLY =~ ^[Yy]$ ]]; then
    # Remove the worktree
    git worktree remove "$WORKTREE_PATH" --force

    # Remove the branch
    git branch -D "$BRANCH_NAME"

    echo ""
    echo "Successfully cleaned up: $TASK_NAME"
else
    echo "Cleanup cancelled."
fi
Enter fullscreen mode Exit fullscreen mode

Installing and Using the Scripts

Follow these steps to set up the scripts on your system:

Step 1: Create the scripts

Create a bin directory in your home folder if it doesn't exist:

mkdir -p ~/bin
Enter fullscreen mode Exit fullscreen mode

Create the creation script:

nano ~/bin/create-ai-worktree.sh
# Paste the script content, save and exit (Ctrl+X, Y, Enter)
Enter fullscreen mode Exit fullscreen mode

Create the cleanup script:

nano ~/bin/cleanup-ai-worktree.sh
# Paste the script content, save and exit
Enter fullscreen mode Exit fullscreen mode

Step 2: Make them executable

chmod +x ~/bin/create-ai-worktree.sh
chmod +x ~/bin/cleanup-ai-worktree.sh
Enter fullscreen mode Exit fullscreen mode

Step 3: Add to your PATH (if not already done)

Add this line to your ~/.bashrc or ~/.zshrc:

export PATH="$HOME/bin:$PATH"
Enter fullscreen mode Exit fullscreen mode

Then reload your shell configuration:

source ~/.bashrc  # or source ~/.zshrc
Enter fullscreen mode Exit fullscreen mode

Step 4: Use them in any Git repository

# Navigate to any project
cd ~/projects/my-laravel-app

# Create an AI worktree for a payment feature
create-ai-worktree.sh payment-processing

# Output:
# ==========================================
# AI Worktree Created Successfully!
# ==========================================
#
# Worktree location: ../my-laravel-app-ai-payment-processing
# Branch name:       ai/payment-processing
# ...

# Navigate to the new worktree
cd ../my-laravel-app-ai-payment-processing

# Do your AI assisted work...

# When done, return to main project and clean up
cd ../my-laravel-app
cleanup-ai-worktree.sh payment-processing
Enter fullscreen mode Exit fullscreen mode

Practical Example: Complete Workflow

Here's a real world example showing the scripts in action:

# You're working on your Laravel project
cd ~/projects/invoice-app
git status
# On branch main, everything clean

# You want Claude Code to implement a PDF export feature
create-ai-worktree.sh pdf-export

# Output shows the worktree was created at ../invoice-app-ai-pdf-export

# Move to the AI worktree
cd ../invoice-app-ai-pdf-export

# Install dependencies (worktrees don't share node_modules or vendor)
composer install
npm install

# Start Claude Code and give it the task
claude

# ... Claude Code implements the PDF export feature ...
# ... You review the changes, run tests, make adjustments ...

# Happy with the result? Commit and merge
git add .
git commit -m "feat: implement PDF export for invoices"

# Return to main project
cd ../invoice-app

# Merge the AI's work
git merge ai/pdf-export

# Clean up the worktree and branch
cleanup-ai-worktree.sh pdf-export

# Done! The PDF export feature is now in your main branch
Enter fullscreen mode Exit fullscreen mode

This workflow keeps your main development environment clean, lets you experiment freely, and makes it trivial to discard failed experiments or merge successful ones.

Real World Workflow: AI Assisted Feature Development

Let's walk through a complete example of using worktrees with Claude Code to implement a new feature.

Scenario

You're building a Laravel application and need to implement a new payment processing feature. You want Claude Code to scaffold the initial implementation while you continue working on unrelated bug fixes.

Step 1: Create the AI Worktree

From your main project directory:

# Create a worktree for the AI to work in
git worktree add -b feature/payment-processing ../my-app-ai-payments

# Verify it was created
git worktree list
Enter fullscreen mode Exit fullscreen mode

Step 2: Set Up the AI Environment

Navigate to the new worktree and ensure it's ready:

cd ../my-app-ai-payments

# Install dependencies (they're not shared between worktrees)
composer install
npm install

# Copy environment file if needed
cp .env.example .env
php artisan key:generate
Enter fullscreen mode Exit fullscreen mode

Step 3: Launch Claude Code in the AI Worktree

Open Claude Code in the AI worktree directory:

claude
Enter fullscreen mode Exit fullscreen mode

Now give Claude Code your task:

I need you to implement a payment processing system for this Laravel application. 

Requirements:
* Create a PaymentService class that integrates with Stripe
* Add a PaymentController with endpoints for creating and confirming payments
* Create the necessary migrations for storing payment records
* Add appropriate form requests for validation
* Write feature tests for the payment flow

Please implement this step by step, creating each component and explaining your decisions.
Enter fullscreen mode Exit fullscreen mode

Step 4: Continue Your Own Work

While Claude Code works in the payment worktree, switch back to your main worktree:

cd ../my-app
Enter fullscreen mode Exit fullscreen mode

Continue your bug fixes, completely unaffected by whatever Claude Code is doing in the other directory.

Step 5: Review AI Changes

Once Claude Code completes its task, review what it created:

# See what files were changed/created
cd ../my-app-ai-payments
git status

# Review the diff
git diff main

# Or compare specific files
diff ../my-app/app/Services/ ./app/Services/
Enter fullscreen mode Exit fullscreen mode

Step 6: Test in Isolation

Run tests in the AI worktree to validate the implementation:

cd ../my-app-ai-payments
php artisan test --filter=Payment
Enter fullscreen mode Exit fullscreen mode

Step 7: Merge or Iterate

If you're satisfied with the AI's work:

# Switch to main worktree
cd ../my-app

# Merge the AI's branch
git merge feature/payment-processing

# Clean up
git worktree remove ../my-app-ai-payments
git branch -d feature/payment-processing
Enter fullscreen mode Exit fullscreen mode

If you need changes, either:

  • Return to the AI worktree and continue prompting Claude Code
  • Make manual adjustments in the AI worktree before merging
  • Discard and start fresh with a new approach

Advanced Workflow: Parallel AI Exploration

Sometimes you want the AI to explore multiple approaches simultaneously. Worktrees make this trivial.

The Multi Path Strategy

# Create three worktrees for different approaches
git worktree add -b ai/payments-stripe ../my-app-ai-stripe
git worktree add -b ai/payments-square ../my-app-ai-square
git worktree add -b ai/payments-braintree ../my-app-ai-braintree
Enter fullscreen mode Exit fullscreen mode

Open Claude Code in each worktree with different prompts:

Stripe worktree: "Implement payment processing using Stripe's Payment Intents API..."

Square worktree: "Implement payment processing using Square's Web Payments SDK..."

Braintree worktree: "Implement payment processing using Braintree's Drop-in UI..."

Comparing Results

After all three implementations are complete:

# Compare code structure
diff -r ../my-app-ai-stripe/app/Services ../my-app-ai-square/app/Services

# Compare test coverage
cd ../my-app-ai-stripe && php artisan test --coverage
cd ../my-app-ai-square && php artisan test --coverage
cd ../my-app-ai-braintree && php artisan test --coverage
Enter fullscreen mode Exit fullscreen mode

Selecting the Winner

Once you've evaluated all approaches:

# Merge your preferred implementation
cd ../my-app
git merge ai/payments-stripe

# Clean up all AI worktrees
git worktree remove ../my-app-ai-stripe
git worktree remove ../my-app-ai-square
git worktree remove ../my-app-ai-braintree

# Remove branches
git branch -D ai/payments-stripe ai/payments-square ai/payments-braintree
Enter fullscreen mode Exit fullscreen mode

Best Practices for AI Worktree Workflows

Naming Conventions

Establish clear naming patterns:

  • Worktree directories: {project}-ai-{task} or {project}-{branch-type}-{description}
  • Branch names: ai/{task-name} or ai/{date}/{task-name}

This makes it easy to identify AI related work and clean up when done.

Commit Hygiene in AI Worktrees

Instruct your AI to commit frequently with meaningful messages:

As you implement this feature, please commit your changes at logical 
checkpoints with clear commit messages that explain what was done and why. 
Use conventional commit format (feat:, fix:, refactor:, etc.).
Enter fullscreen mode Exit fullscreen mode

This gives you granular control when reviewing and the ability to cherry pick specific changes.

Regular Cleanup

AI experimentation can leave orphaned worktrees. Schedule regular cleanup:

# List all worktrees
git worktree list

# Prune any that were manually deleted
git worktree prune

# Remove stale AI branches
git branch --list 'ai/*' | xargs -n 1 git branch -d
Enter fullscreen mode Exit fullscreen mode

Environment Variables and Secrets

Never let AI worktrees contain real credentials:

  • Use .env.example files with placeholder values
  • Create a specific .env.ai template for AI worktrees
  • Add AI worktree patterns to .gitignore if they might contain sensitive data
# .gitignore
.env
.env.ai
**/my-app-ai-*/.env
Enter fullscreen mode Exit fullscreen mode

IDE Configuration

If you use VS Code, create a workspace file to manage multiple worktrees:

{
    "folders": [
        {
            "name": "Main Development",
            "path": "./my-app"
        },
        {
            "name": "AI: Payment Feature",
            "path": "./my-app-ai-payments"
        },
        {
            "name": "AI: Refactoring",
            "path": "./my-app-ai-refactor"
        }
    ],
    "settings": {
        "files.exclude": {
            "**/node_modules": true,
            "**/vendor": true
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Troubleshooting Common Issues

"fatal: 'branch-name' is already checked out"

Git prevents the same branch from being checked out in multiple worktrees. Solutions:

# Create a new branch instead
git worktree add -b new-branch-name ../path

# Or detach HEAD in the blocking worktree first
cd ../blocking-worktree
git checkout --detach
Enter fullscreen mode Exit fullscreen mode

Worktree Shows Outdated Code

If your AI worktree doesn't reflect recent commits from another worktree:

cd ../ai-worktree
git fetch origin
git rebase origin/main  # or merge, depending on your preference
Enter fullscreen mode Exit fullscreen mode

Dependencies Not Working

Each worktree needs its own installed dependencies:

# Laravel
composer install
npm install

# SPFx
npm install

# ASP.NET Core
dotnet restore
Enter fullscreen mode Exit fullscreen mode

Large Repository, Slow Worktree Creation

For very large repositories, worktree creation can be slow. Use sparse checkout:

git worktree add --no-checkout ../sparse-worktree branch-name
cd ../sparse-worktree
git sparse-checkout init --cone
git sparse-checkout set src/relevant-folder
Enter fullscreen mode Exit fullscreen mode

Integrating with Your Development Workflow

Git Aliases for Common Operations

Add these to your .gitconfig:

[alias]
    # List worktrees with better formatting
    wt = worktree list

    # Create AI worktree quickly
    wt-ai = "!f() { git worktree add -b ai/$1 ../$(basename $(pwd))-ai-$1; }; f"

    # Remove AI worktree and branch
    wt-ai-rm = "!f() { git worktree remove ../$(basename $(pwd))-ai-$1 && git branch -D ai/$1; }; f"

    # Prune and clean
    wt-clean = "!git worktree prune && git branch --list 'ai/*' --merged | xargs -r git branch -d"
Enter fullscreen mode Exit fullscreen mode

Usage:

git wt-ai payments      # Creates worktree and ai/payments branch
git wt-ai-rm payments   # Removes both
git wt-clean            # Prune stale worktrees and merged AI branches
Enter fullscreen mode Exit fullscreen mode

Shell Functions for Complex Workflows

Add to your .bashrc or .zshrc:

# Start an AI assisted task
ai_task() {
    local task_name=$1
    local project_name=$(basename $(git rev-parse --show-toplevel))
    local worktree_path="../${project_name}-ai-${task_name}"

    git worktree add -b "ai/${task_name}" "$worktree_path"
    cd "$worktree_path"

    # Auto detect and install dependencies
    [ -f "composer.json" ] && composer install
    [ -f "package.json" ] && npm install
    [ -f "*.csproj" ] && dotnet restore

    echo "Ready! Opening Claude Code..."
    claude
}

# Quick cleanup
ai_cleanup() {
    local task_name=$1
    local project_name=$(basename $(git rev-parse --show-toplevel 2>/dev/null || echo $(basename $(pwd)) | sed 's/-ai-.*//'))
    local worktree_path="../${project_name}-ai-${task_name}"

    git worktree remove "$worktree_path" 2>/dev/null
    git branch -D "ai/${task_name}" 2>/dev/null
    echo "Cleaned up ai/${task_name}"
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Git worktrees transform how we can work with AI coding assistants. By providing isolated, parallel working environments, they enable us to:

  • Let AI agents work autonomously without blocking our own progress
  • Experiment with multiple AI generated solutions simultaneously
  • Maintain clean separation between human and AI contributions
  • Safely evaluate and iterate on AI suggestions before merging

The investment in learning worktrees pays dividends every time you use an AI coding tool. The commands become second nature quickly, and the workflow improvements are substantial.

As AI assisted development continues to evolve, workflows like these will become increasingly important. The developers who master the tooling around AI integration will be the ones who extract the most value from these powerful assistants.

Start small: next time you have a task suitable for Claude Code, create a dedicated worktree. Experience the freedom of parallel development firsthand. Once you do, you'll wonder how you ever worked without it.


Have questions or want to share your own AI plus worktree workflows? Drop a comment below or reach out on social media. Happy coding!

Top comments (0)