Claude
Skills
Sign in
Back

worktree-workflow

Included with Lifetime
$97 forever

Git worktree workflow for isolated feature development and PR creation When user starts new work, needs to switch contexts, or wants parallel development

General

What this skill does


# Git Worktree Workflow Agent

## What's New in Git Worktree & AI Agents (2025)

- **AI Agent Integration**: 4-5 parallel Claude Code agents working independently on different features
- **Complete Isolation**: Each worktree prevents agents from modifying wrong branches or interfering with each other
- **Structured Organization**: `./worktrees/feature/`, `./worktrees/bugfix/`, `./worktrees/review/` patterns for clarity
- **Production Adoption**: incident.io uses worktrees for parallel AI agent development
- **Emergency Hotfix Pattern**: Create worktree on release branch without disrupting ongoing development
- **Cleanup Best Practices**: Systematic removal of orphaned worktrees with `git worktree prune`
- **Meaningful Directory Names**: Avoid confusion when multiple agents or developers work simultaneously

## Overview

This agent teaches using Git worktrees to isolate changes in separate working directories, enabling parallel development without branch switching and creating clean PRs when complete. **Worktrees are particularly powerful for AI agent workflows**, where multiple autonomous agents can work on different features simultaneously without conflict.

## Core Concept

Git worktrees let you have multiple working directories from the same repository:

- **Main worktree**: Your primary working directory (usually `main` or `master`)
- **Linked worktrees**: Additional directories for features/fixes, each on different branches
- **No branch switching**: Each worktree has its own branch checked out
- **Shared .git**: All worktrees share the same repository data

## CLI Commands

### Creating Worktrees

```bash
# Create worktree for new feature
git worktree add ../feature-auth feature/auth

# Create worktree with new branch from current HEAD
git worktree add -b fix/login-bug ../fix-login

# Create worktree from specific branch
git worktree add -b feature/api ../api-work origin/main

# Create worktree in subdirectory
git worktree add worktrees/feature-x -b feature/x
```

### Listing Worktrees

```bash
# List all worktrees
git worktree list

# List with more details
git worktree list --porcelain
```

### Removing Worktrees

```bash
# Remove worktree (deletes directory and unregisters)
git worktree remove ../feature-auth

# Remove even with uncommitted changes
git worktree remove --force ../feature-auth

# Clean up stale worktree references
git worktree prune
```

### Moving Between Worktrees

```bash
# Navigate to worktree
cd ../feature-auth

# Or use absolute path
cd ~/git/myproject-feature-auth

# Return to main worktree
cd ~/git/myproject
```

## Complete Workflow

### Starting New Work

```bash
#!/bin/bash
# start-work.sh <feature-name>

set -euo pipefail

FEATURE_NAME=${1:?Usage: start-work.sh <feature-name>}
BRANCH_NAME="feature/${FEATURE_NAME}"
WORKTREE_DIR="../${FEATURE_NAME}"

echo "Starting new work: $FEATURE_NAME"

# Create worktree from main
git worktree add -b "$BRANCH_NAME" "$WORKTREE_DIR" origin/main

# Navigate to worktree
cd "$WORKTREE_DIR"

echo "✅ Worktree created at: $WORKTREE_DIR"
echo "   Branch: $BRANCH_NAME"
echo "   Ready to start coding!"

# Optional: Open in editor
# code .
```

### Working in Worktree

```bash
# In your worktree directory
cd ../feature-auth

# Make changes
echo "new feature" > feature.ts

# Stage and commit as usual
git add feature.ts
git commit -m "feat: add authentication"

# Push to remote
git push -u origin feature/auth
```

### Creating PR from Worktree

```bash
#!/bin/bash
# pr-from-worktree.sh

set -euo pipefail

# Ensure we're in a worktree (not main)
CURRENT_BRANCH=$(git branch --show-current)
if [ "$CURRENT_BRANCH" = "main" ] || [ "$CURRENT_BRANCH" = "master" ]; then
  echo "❌ Cannot create PR from main branch"
  exit 1
fi

echo "Creating PR from branch: $CURRENT_BRANCH"

# Push changes
git push -u origin "$CURRENT_BRANCH"

# Create PR
gh pr create --fill

echo "✅ PR created!"
echo "View: gh pr view --web"
```

### Completing Work

```bash
#!/bin/bash
# complete-work.sh

set -euo pipefail

CURRENT_BRANCH=$(git branch --show-current)
WORKTREE_PATH=$(pwd)

echo "Completing work on: $CURRENT_BRANCH"

# Ensure everything is committed
if ! git diff --quiet || ! git diff --cached --quiet; then
  echo "❌ You have uncommitted changes"
  git status
  exit 1
fi

# Push final changes
git push

# Create PR if it doesn't exist
if ! gh pr view &>/dev/null; then
  echo "Creating PR..."
  gh pr create --fill
fi

# Show PR status
gh pr view

# Return to main worktree
cd "$(git rev-parse --show-toplevel)"

echo ""
echo "Next steps:"
echo "  1. Review PR: gh pr view --web"
echo "  2. After merge: git worktree remove $WORKTREE_PATH"
echo "  3. Clean up: git branch -d $CURRENT_BRANCH"
```

## Advanced Patterns

### Organized Worktree Layout

```bash
# Create worktrees in dedicated directory
WORKTREE_BASE="$HOME/worktrees/$(basename $(git rev-parse --show-toplevel))"
mkdir -p "$WORKTREE_BASE"

# Create worktree
git worktree add "$WORKTREE_BASE/feature-auth" -b feature/auth

# Your layout:
# ~/git/myproject/              (main worktree)
# ~/worktrees/myproject/
#   ├── feature-auth/            (feature worktree)
#   ├── fix-bug-123/             (bugfix worktree)
#   └── refactor-api/            (refactor worktree)
```

### Quick Switch Script

```bash
#!/bin/bash
# switch-worktree.sh <worktree-name>

WORKTREE_NAME=${1:?Usage: switch-worktree.sh <worktree-name>}
WORKTREE_BASE="$HOME/worktrees/$(basename $(git rev-parse --show-toplevel))"
WORKTREE_PATH="$WORKTREE_BASE/$WORKTREE_NAME"

if [ -d "$WORKTREE_PATH" ]; then
  cd "$WORKTREE_PATH"
  echo "✅ Switched to: $WORKTREE_PATH"
else
  echo "❌ Worktree not found: $WORKTREE_PATH"
  echo ""
  echo "Available worktrees:"
  git worktree list
  exit 1
fi
```

### List Worktrees with Branch Status

```bash
#!/bin/bash
# worktree-status.sh

git worktree list | while IFS= read -r line; do
  # Extract worktree path
  path=$(echo "$line" | awk '{print $1}')
  branch=$(echo "$line" | awk '{print $3}' | tr -d '[]')

  echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  echo "📁 $path"
  echo "🌿 $branch"

  # Show git status in that worktree
  if [ -d "$path" ]; then
    (
      cd "$path" 2>/dev/null && {
        if git diff --quiet && git diff --cached --quiet; then
          echo "✅ Clean"
        else
          echo "⚠️  Uncommitted changes"
        fi

        # Show if branch has upstream
        if git rev-parse --abbrev-ref @{u} &>/dev/null; then
          ahead=$(git rev-list --count @{u}..HEAD)
          behind=$(git rev-list --count HEAD..@{u})
          [ $ahead -gt 0 ] && echo "⬆️  $ahead commit(s) ahead"
          [ $behind -gt 0 ] && echo "⬇️  $behind commit(s) behind"
        else
          echo "🔗 No upstream branch"
        fi
      }
    )
  fi
  echo ""
done
```

### Cleanup Merged Worktrees

```bash
#!/bin/bash
# cleanup-merged-worktrees.sh

set -euo pipefail

# Get default branch
DEFAULT_BRANCH=$(git remote show origin | grep "HEAD branch" | sed 's/.*: //')

echo "Cleaning up merged worktrees (base: $DEFAULT_BRANCH)..."

# Update refs
git fetch origin --prune

# Find merged branches
git worktree list --porcelain | grep -E "^worktree|^branch" | while read -r line; do
  if [[ $line =~ ^worktree ]]; then
    current_worktree=$(echo "$line" | awk '{print $2}')
  elif [[ $line =~ ^branch ]]; then
    branch=$(echo "$line" | awk '{print $2}' | sed 's|refs/heads/||')

    # Skip default branch
    [ "$branch" = "$DEFAULT_BRANCH" ] && continue

    # Check if merged
    if git branch --merged "origin/$DEFAULT_BRANCH" | grep -q "^[* ]*$branch$"; then
      echo "🗑️  Removing merged worktree: $current_worktree ($branch)"
      git worktree remove "$current_worktree" || true
      git branch -d "$branch" || true
    fi
  fi
done

# Prune stale references
git worktree prune

echo "✅ Cleanup complete"
```

## AI Agent Workflows (2025)

### The incident.io Case Study

**Real-world example**: incident.io runs **4-5 Claude Code agents in parallel** using worktrees, enabling m

Related in General