Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 18:16:54 +08:00
commit 2eeb6e60c6
39 changed files with 10735 additions and 0 deletions

View File

@@ -0,0 +1,568 @@
# Mode 1: Single Worktree Creation
## Overview
This mode creates a single git worktree for parallel development. Use this when the user wants to work on one additional branch alongside their current work.
## When to Use
- User mentions creating "a worktree" (singular)
- User specifies one branch name
- User says "I need to work on [branch]"
- Default mode when unclear
## Workflow
### Phase 0: Prerequisites & Validation
#### Step 0.1: Verify Git Repository
```bash
git rev-parse --is-inside-work-tree
```
**Expected Output:**
```
true
```
**If fails:**
- Stop immediately
- Error: "Not in a git repository. Please navigate to your project root and try again."
#### Step 0.2: Get Repository Information
```bash
# Get repository name
basename $(git rev-parse --show-toplevel)
# Get current branch
git branch --show-current
```
**Store:**
- `REPO_NAME`: Repository name
- `CURRENT_BRANCH`: Current branch
#### Step 0.3: Check Working Directory Status
```bash
git status --porcelain
```
**If output exists:**
- **Warning:** "You have uncommitted changes in your current worktree:"
- Show: `git status --short`
- Ask: "Continue creating worktree anyway? This won't affect your changes."
- If user declines → Stop
**If clean:**
- Proceed silently
#### Step 0.4: Check Existing Worktrees
```bash
git worktree list
```
**Purpose:**
- Show user current worktree state
- Detect conflicts before creation
- Store for later reference
---
### Phase 1: Gather Information
#### Step 1.1: Extract Branch Name
**From user request:**
- "create worktree for **feature-auth**"
- "set up worktree for **bugfix-123**"
- "I need a worktree for **experiment-new-ui**"
**Extract:**
- `BRANCH_NAME`: The branch to work on
**If unclear:**
- Ask: "What branch name should I use for the worktree?"
#### Step 1.2: Determine Branch Type
**Check if branch exists:**
```bash
git show-ref --verify refs/heads/$BRANCH_NAME 2>/dev/null
```
**If exits (exit code 0):**
- `BRANCH_TYPE`: "existing"
- Message: "Found existing branch: $BRANCH_NAME"
**If doesn't exist:**
- `BRANCH_TYPE`: "new"
- Message: "Will create new branch: $BRANCH_NAME"
**Also check remote:**
```bash
git show-ref --verify refs/remotes/origin/$BRANCH_NAME 2>/dev/null
```
**If exists on remote but not local:**
- Offer: "Branch exists on remote. Track remote branch or create new local?"
- Default: Track remote
#### Step 1.3: Determine Worktree Location
**Default location:**
```
../$REPO_NAME-$BRANCH_NAME
```
**Example:**
- Repo: `myapp`
- Branch: `feature-auth`
- Location: `../myapp-feature-auth`
**Ask user:**
"I'll create the worktree at: `$DEFAULT_LOCATION`"
"Use this location? (yes/no/specify custom)"
**Options:**
- Yes → Use default
- No → Ask for custom path
- Custom → Use provided path
**Store:**
- `WORKTREE_PATH`: Final worktree location
#### Step 1.4: Check Directory Availability
```bash
if [ -d "$WORKTREE_PATH" ]; then
echo "exists"
else
echo "available"
fi
```
**If exists:**
- **Error:** "Directory already exists: $WORKTREE_PATH"
- Ask: "Remove it and continue? (yes/no)"
- If yes → `rm -rf $WORKTREE_PATH` (with confirmation)
- If no → Ask for different location
#### Step 1.5: Development Environment Setup
**Check for package.json:**
```bash
if [ -f "package.json" ]; then
echo "found"
fi
```
**If found:**
- Default: "Setup development environment? (yes/no)" → yes
- Ask: "Install dependencies in new worktree?"
**Store:**
- `SETUP_DEV`: true/false
**If no package.json:**
- Skip dev setup questions
- `SETUP_DEV`: false
---
### Phase 2: Create Worktree
#### Step 2.1: Execute Worktree Creation
**For new branch:**
```bash
git worktree add $WORKTREE_PATH -b $BRANCH_NAME
```
**For existing branch:**
```bash
git worktree add $WORKTREE_PATH $BRANCH_NAME
```
**For tracking remote branch:**
```bash
git worktree add $WORKTREE_PATH -b $BRANCH_NAME --track origin/$BRANCH_NAME
```
**Expected Output:**
```
Preparing worktree (new branch 'feature-auth')
HEAD is now at abc123 Initial commit
```
**Monitor for errors:**
- "fatal: invalid reference" → Branch doesn't exist
- "fatal: 'path' already exists" → Directory conflict
- "fatal: 'branch' is already checked out" → Branch in another worktree
**If error:**
- Stop and report error
- Provide fix suggestion
- Don't continue to next phase
#### Step 2.2: Verify Worktree Creation
```bash
git worktree list
```
**Check output includes:**
```
/path/to/worktree abc123 [branch-name]
```
**Verify directory:**
```bash
ls -la $WORKTREE_PATH
```
**Must see:**
- `.git` file (not directory - points to parent)
- Project files
**If verification fails:**
- **Error:** "Worktree creation failed verification"
- Show: `git worktree list`
- Offer: "Try again with different settings?"
- Stop
#### Step 2.3: Confirm Success
**Output:**
```
✓ Worktree created successfully
Location: $WORKTREE_PATH
Branch: $BRANCH_NAME ($BRANCH_TYPE)
Status: Ready
```
---
### Phase 3: Setup Development Environment
**Only if `SETUP_DEV` is true**
#### Step 3.1: Navigate to Worktree
```bash
cd $WORKTREE_PATH
```
#### Step 3.2: Detect Package Manager
**Check for lockfiles in priority order:**
```bash
# Check pnpm
if [ -f "pnpm-lock.yaml" ]; then
PKG_MANAGER="pnpm"
INSTALL_CMD="pnpm install"
fi
# Check yarn
if [ -f "yarn.lock" ]; then
PKG_MANAGER="yarn"
INSTALL_CMD="yarn install"
fi
# Check bun
if [ -f "bun.lockb" ]; then
PKG_MANAGER="bun"
INSTALL_CMD="bun install"
fi
# Check npm
if [ -f "package-lock.json" ]; then
PKG_MANAGER="npm"
INSTALL_CMD="npm install"
fi
# Default to npm if no lockfile
if [ -z "$PKG_MANAGER" ]; then
PKG_MANAGER="npm"
INSTALL_CMD="npm install"
fi
```
**Output:**
```
Detected package manager: $PKG_MANAGER
```
#### Step 3.3: Run Installation
```bash
$INSTALL_CMD
```
**Show progress:**
```
Installing dependencies with $PKG_MANAGER...
```
**Expected output (varies by manager):**
- npm: "added X packages in Ys"
- pnpm: "Packages: +X"
- yarn: "Done in Xs"
- bun: "X packages installed"
**Monitor for errors:**
- Network failures
- Lockfile conflicts
- Disk space issues
**If error:**
- Show error message
- Suggest: "Installation failed. You can manually run `$INSTALL_CMD` in the worktree later."
- Mark: Dev environment setup failed
- Continue (don't stop entire process)
**If success:**
```
✓ Dependencies installed successfully
```
#### Step 3.4: Copy Environment Files (Optional)
**Check for .env in parent:**
```bash
if [ -f "../.env" ]; then
echo "found"
fi
```
**If found:**
- Ask: "Copy .env file to worktree? (yes/no)"
- Default: Ask (don't assume - may contain secrets)
**If yes:**
```bash
cp ../.env .env
```
**Output:**
```
✓ Environment file copied
```
**Other common files to check:**
- `.env.local`
- `.env.development`
- `.env.test`
#### Step 3.5: Verify Development Setup
```bash
# Check node_modules exists
if [ -d "node_modules" ]; then
echo "✓ Dependencies installed"
fi
# Try running a basic script (optional)
npm run build --dry-run 2>/dev/null && echo "✓ Build configuration valid"
```
**Final status:**
```
✓ Development environment ready
Package manager: $PKG_MANAGER
Dependencies: Installed
Environment: Ready
```
---
### Phase 4: Provide User Guidance
#### Step 4.1: Generate Summary
**Create summary output:**
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Worktree Created Successfully
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Location: $WORKTREE_PATH
Branch: $BRANCH_NAME (new/existing)
Base: $BASE_BRANCH
Dev Setup: ✓ Complete / ⊘ Skipped
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Next Steps
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1. Navigate to worktree:
cd $WORKTREE_PATH
2. Start Claude Code:
claude
3. Begin development on $BRANCH_NAME
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```
#### Step 4.2: Show All Worktrees
```bash
git worktree list
```
**Format output:**
```
All Worktrees:
/path/to/main (main) ← current
$WORKTREE_PATH ($BRANCH_NAME) ← new
```
**Highlight:**
- Current worktree with `← current`
- New worktree with `← new`
#### Step 4.3: Provide Quick Reference Commands
```
Quick Reference:
List worktrees: git worktree list
Remove worktree: git worktree remove $WORKTREE_PATH
Navigate: cd $WORKTREE_PATH
Return to main: cd [original path]
```
#### Step 4.4: Offer Additional Actions
**Ask user:**
"Would you like me to:
- [ ] Open the worktree in a new terminal
- [ ] Generate a setup script for future worktrees
- [ ] Show git commands for advanced management"
**Based on response, provide appropriate outputs**
---
### Phase 5: Post-Creation Verification
#### Step 5.1: Final Checks
```bash
# Verify worktree is in list
git worktree list | grep -q "$WORKTREE_PATH"
# Verify directory exists and has files
[ -d "$WORKTREE_PATH" ] && [ "$(ls -A $WORKTREE_PATH)" ]
# Verify .git file exists
[ -f "$WORKTREE_PATH/.git" ]
```
**All must pass**
#### Step 5.2: Success Confirmation
**Create success checklist:**
```
✓ Worktree created at correct location
✓ Branch checked out properly
✓ Files visible in worktree directory
✓ Development environment ready (if requested)
✓ Worktree appears in git worktree list
✓ Ready for Claude Code session
```
**If any fail:**
- Report which check failed
- Provide troubleshooting steps
- Offer to retry or cleanup
---
## Error Handling
### Error: Not a Git Repository
```
Error: Not in a git repository
Solution:
1. Navigate to your project root
2. Verify with: git status
3. Try again
```
### Error: Branch Already Checked Out
```
Error: Branch 'feature-x' is already checked out at '/path'
Solution:
1. List worktrees: git worktree list
2. Navigate to existing worktree, or
3. Remove existing worktree first:
git worktree remove /path
```
### Error: Directory Already Exists
```
Error: Directory already exists: /path/to/worktree
Solutions:
1. Use different location
2. Remove directory: rm -rf /path/to/worktree
3. Specify custom path when creating
```
### Error: Installation Failed
```
Error: Dependency installation failed
Solutions:
1. Check network connection
2. Manually run in worktree:
cd /path/to/worktree
[package-manager] install
3. Check lockfile compatibility
```
---
## Stop Conditions
**Stop immediately if:**
- [ ] Not in a git repository
- [ ] Worktree creation command fails
- [ ] Directory already exists and user declines removal
- [ ] User cancels during any confirmation
**Continue with warnings if:**
- [ ] Uncommitted changes in current worktree
- [ ] Dependency installation fails
- [ ] Environment file copy fails
---
## Success Criteria
- [ ] Worktree created successfully
- [ ] Branch checked out
- [ ] Directory accessible
- [ ] Dev environment ready (if requested)
- [ ] User provided with clear next steps
- [ ] All verification checks passed
---
## Example: Complete Flow
```
User: Create a worktree for feature-authentication

View File

@@ -0,0 +1,714 @@
# Mode 2: Batch Worktree Creation
## Overview
This mode creates multiple git worktrees in a single operation. Use this when the user wants to work on several branches simultaneously or needs to set up multiple environments at once.
## When to Use
- User mentions "multiple worktrees"
- User provides comma-separated list of branches
- User says "set up worktrees for X, Y, and Z"
- User wants to create worktrees for multiple PRs/issues
## Workflow
### Phase 0: Prerequisites & Validation
#### Step 0.1: Verify Git Repository
```bash
git rev-parse --is-inside-work-tree
```
**Expected Output:**
```
true
```
**If fails:**
- Stop immediately
- Error: "Not in a git repository. Please navigate to your project root and try again."
#### Step 0.2: Get Repository Information
```bash
# Get repository name
REPO_NAME=$(basename $(git rev-parse --show-toplevel))
# Get current branch
CURRENT_BRANCH=$(git branch --show-current)
# Get repository root
REPO_ROOT=$(git rev-parse --show-toplevel)
```
#### Step 0.3: Check Working Directory Status
```bash
git status --porcelain
```
**If output exists:**
- **Warning:** "You have uncommitted changes. This won't affect worktree creation, but be aware."
- Continue (batch operations should be robust)
#### Step 0.4: List Current Worktrees
```bash
git worktree list
```
**Purpose:**
- Show baseline state
- Detect potential conflicts
- Track for final summary
---
### Phase 1: Gather Information
#### Step 1.1: Extract Branch List
**From user request patterns:**
- "create worktrees for **feature-a, feature-b, feature-c**"
- "set up worktrees for **bug-123, bug-456**"
- "I need worktrees for **feat-x and feat-y**"
**Parse into array:**
```bash
BRANCHES=("feature-a" "feature-b" "feature-c")
```
**Normalize:**
- Trim whitespace
- Remove "and", commas
- Handle various separators
**Validate:**
- Must have at least 2 branches
- If 1 branch → Redirect to Mode 1
- If 0 branches → Ask user
#### Step 1.2: Determine Branch Types
**For each branch, check existence:**
```bash
for branch in "${BRANCHES[@]}"; do
if git show-ref --verify refs/heads/$branch 2>/dev/null; then
BRANCH_TYPES[$branch]="existing"
else
BRANCH_TYPES[$branch]="new"
fi
done
```
**Show summary:**
```
Planning to create 3 worktrees:
feature-a (new)
feature-b (existing)
feature-c (new)
```
**Confirm with user:**
"Create these worktrees? (yes/no)"
#### Step 1.3: Determine Locations
**For each branch, generate default location:**
```bash
for branch in "${BRANCHES[@]}"; do
LOCATIONS[$branch]="../$REPO_NAME-$branch"
done
```
**Show locations:**
```
Worktree locations:
feature-a → ../myapp-feature-a
feature-b → ../myapp-feature-b
feature-c → ../myapp-feature-c
```
**Ask:**
"Use these locations? (yes/customize)"
**If customize:**
- Ask for pattern or specific paths
- Support patterns like `../worktrees/{branch}`
#### Step 1.4: Check Directory Conflicts
```bash
CONFLICTS=()
for branch in "${BRANCHES[@]}"; do
location="${LOCATIONS[$branch]}"
if [ -d "$location" ]; then
CONFLICTS+=("$branch$location")
fi
done
```
**If conflicts:**
```
Warning: These directories already exist:
feature-a → ../myapp-feature-a
feature-c → ../myapp-feature-c
Options:
1. Skip conflicting worktrees
2. Remove and recreate
3. Use different locations
```
**Handle based on user choice**
#### Step 1.5: Development Environment Setup
**Ask once for all worktrees:**
"Setup development environment in all worktrees? (yes/no)"
**Default:** yes (if package.json exists)
**Store:**
- `SETUP_DEV_ALL`: true/false
---
### Phase 2: Create Worktrees (Parallel Processing)
#### Step 2.1: Create Execution Plan
**Build command list:**
```bash
COMMANDS=()
for branch in "${BRANCHES[@]}"; do
location="${LOCATIONS[$branch]}"
branch_type="${BRANCH_TYPES[$branch]}"
if [ "$branch_type" == "new" ]; then
COMMANDS+=("git worktree add $location -b $branch")
else
COMMANDS+=("git worktree add $location $branch")
fi
done
```
**Show plan:**
```
Execution plan:
1. git worktree add ../myapp-feature-a -b feature-a
2. git worktree add ../myapp-feature-b feature-b
3. git worktree add ../myapp-feature-c -b feature-c
```
#### Step 2.2: Execute Worktree Creations
**Sequential execution with progress tracking:**
```bash
CREATED=()
FAILED=()
TOTAL=${#BRANCHES[@]}
CURRENT=0
for branch in "${BRANCHES[@]}"; do
((CURRENT++))
echo "[$CURRENT/$TOTAL] Creating worktree for $branch..."
location="${LOCATIONS[$branch]}"
branch_type="${BRANCH_TYPES[$branch]}"
# Execute creation
if [ "$branch_type" == "new" ]; then
if git worktree add "$location" -b "$branch" 2>&1; then
CREATED+=("$branch")
echo " ✓ Success: $branch"
else
FAILED+=("$branch")
echo " ✗ Failed: $branch"
fi
else
if git worktree add "$location" "$branch" 2>&1; then
CREATED+=("$branch")
echo " ✓ Success: $branch"
else
FAILED+=("$branch")
echo " ✗ Failed: $branch"
fi
fi
done
```
**Progress output:**
```
[1/3] Creating worktree for feature-a...
✓ Success: feature-a
[2/3] Creating worktree for feature-b...
✓ Success: feature-b
[3/3] Creating worktree for feature-c...
✗ Failed: feature-c (branch already checked out)
```
#### Step 2.3: Verify Creations
```bash
git worktree list
```
**Count created worktrees:**
```bash
VERIFIED=0
for branch in "${CREATED[@]}"; do
location="${LOCATIONS[$branch]}"
if git worktree list | grep -q "$location"; then
((VERIFIED++))
fi
done
```
**Report:**
```
Verification: $VERIFIED/$TOTAL worktrees created successfully
```
#### Step 2.4: Handle Failures
**If any failed:**
```
Failed to create worktrees for:
feature-c: Branch already checked out at /other/path
Options:
1. Continue with successful worktrees
2. Retry failed worktrees
3. Clean up and start over
```
**Recommended:** Continue with successful ones
---
### Phase 3: Setup Development Environments (Batch)
**Only if `SETUP_DEV_ALL` is true**
#### Step 3.1: Detect Package Manager
```bash
# Check in repository root (same for all worktrees)
if [ -f "pnpm-lock.yaml" ]; then
PKG_MANAGER="pnpm"
INSTALL_CMD="pnpm install"
elif [ -f "yarn.lock" ]; then
PKG_MANAGER="yarn"
INSTALL_CMD="yarn install"
elif [ -f "bun.lockb" ]; then
PKG_MANAGER="bun"
INSTALL_CMD="bun install"
elif [ -f "package-lock.json" ]; then
PKG_MANAGER="npm"
INSTALL_CMD="npm install"
else
PKG_MANAGER="npm"
INSTALL_CMD="npm install"
fi
```
**Output:**
```
Using $PKG_MANAGER for all worktrees
```
#### Step 3.2: Install Dependencies (Parallel)
**For each created worktree:**
```bash
INSTALL_SUCCESS=()
INSTALL_FAILED=()
for branch in "${CREATED[@]}"; do
location="${LOCATIONS[$branch]}"
echo "Installing dependencies in $branch..."
# Run in subshell
(
cd "$location" && $INSTALL_CMD > /tmp/install-$branch.log 2>&1
) &
# Store PID for tracking
INSTALL_PIDS[$branch]=$!
done
# Wait for all installations
for branch in "${CREATED[@]}"; do
pid=${INSTALL_PIDS[$branch]}
if wait $pid; then
INSTALL_SUCCESS+=("$branch")
echo "$branch: Dependencies installed"
else
INSTALL_FAILED+=("$branch")
echo "$branch: Installation failed (see /tmp/install-$branch.log)"
fi
done
```
**Progress:**
```
Installing dependencies in all worktrees...
✓ feature-a: Dependencies installed (12.3s)
✓ feature-b: Dependencies installed (11.8s)
✗ feature-c: Installation failed (network error)
Successfully installed: 2/3
```
#### Step 3.3: Copy Environment Files (Optional)
**Check for .env:**
```bash
if [ -f ".env" ]; then
echo "Found .env file"
read -p "Copy .env to all worktrees? (yes/no): " copy_env
if [ "$copy_env" == "yes" ]; then
for branch in "${CREATED[@]}"; do
location="${LOCATIONS[$branch]}"
cp .env "$location/.env"
echo " ✓ Copied .env to $branch"
done
fi
fi
```
#### Step 3.4: Summary of Dev Setup
```
Development Environment Setup Complete:
feature-a:
✓ Dependencies installed ($PKG_MANAGER)
✓ Environment ready
feature-b:
✓ Dependencies installed ($PKG_MANAGER)
✓ Environment ready
feature-c:
✗ Skipped (worktree creation failed)
```
---
### Phase 4: Provide Comprehensive Guidance
#### Step 4.1: Generate Summary Report
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Batch Worktree Creation Complete
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Created: ${#CREATED[@]}/${#BRANCHES[@]} worktrees
Failed: ${#FAILED[@]}/${#BRANCHES[@]} worktrees
Success:
✓ feature-a → ../myapp-feature-a (new branch)
✓ feature-b → ../myapp-feature-b (existing branch)
Failed:
✗ feature-c: Branch already checked out
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```
#### Step 4.2: Provide Navigation Commands
**For each successful worktree:**
```
Start working on feature-a:
cd ../myapp-feature-a
claude
Start working on feature-b:
cd ../myapp-feature-b
claude
```
#### Step 4.3: Show All Worktrees
```bash
git worktree list
```
**Format:**
```
All Worktrees:
/Users/connor/myapp (main) ← current
/Users/connor/myapp-feature-a (feature-a) ← new
/Users/connor/myapp-feature-b (feature-b) ← new
```
#### Step 4.4: Provide Batch Management Commands
```
Batch Management:
List all worktrees:
git worktree list
Remove specific worktree:
git worktree remove ../myapp-feature-a
Remove all new worktrees:
git worktree remove ../myapp-feature-a
git worktree remove ../myapp-feature-b
Generate cleanup script:
Would you like me to create a cleanup script?
```
#### Step 4.5: Offer Script Generation
**Ask user:**
"Generate a script to manage these worktrees? (yes/no)"
**If yes, create:**
- Start scripts for each worktree
- Cleanup script for all worktrees
- Status check script
---
### Phase 5: Post-Creation Verification
#### Step 5.1: Comprehensive Verification
```bash
# Verify all created worktrees
for branch in "${CREATED[@]}"; do
location="${LOCATIONS[$branch]}"
# Check in worktree list
if ! git worktree list | grep -q "$location"; then
echo "$branch: Not in worktree list"
continue
fi
# Check directory exists
if [ ! -d "$location" ]; then
echo "$branch: Directory not found"
continue
fi
# Check .git file
if [ ! -f "$location/.git" ]; then
echo "$branch: Missing .git file"
continue
fi
# Check has files
if [ -z "$(ls -A $location)" ]; then
echo "$branch: Empty directory"
continue
fi
echo "$branch: All checks passed"
done
```
#### Step 5.2: Success Checklist
```
Verification Results:
feature-a:
✓ Worktree in git worktree list
✓ Directory exists with files
✓ .git file present
✓ Development environment ready
✓ Ready for Claude Code session
feature-b:
✓ Worktree in git worktree list
✓ Directory exists with files
✓ .git file present
✓ Development environment ready
✓ Ready for Claude Code session
```
---
## Advanced Features
### Feature 1: Smart Branch Detection
**Auto-detect from PRs:**
```bash
# Get open PR branches
gh pr list --json headRefName --jq '.[].headRefName'
```
**Offer to user:**
"Found 5 open PRs. Create worktrees for all? (yes/select/no)"
### Feature 2: Parallel Claude Code Sessions
**Generate tmux/screen setup:**
```bash
#!/bin/bash
# Start parallel Claude Code sessions
tmux new-session -d -s worktrees
tmux split-window -h
tmux split-window -v
tmux send-keys -t 0 "cd ../myapp-feature-a && claude" C-m
tmux send-keys -t 1 "cd ../myapp-feature-b && claude" C-m
tmux send-keys -t 2 "cd ../myapp && claude" C-m
tmux attach-session -t worktrees
```
### Feature 3: Dependency Sharing
**Optimize with shared node_modules:**
```
Note: Each worktree has separate node_modules.
Disk usage: ~500MB per worktree
Consider using:
- pnpm (with content-addressable storage)
- yarn with workspaces
- Shared cache configurations
```
### Feature 4: Custom Patterns
**Support location patterns:**
```
User: Create worktrees in ~/worktrees/{branch}
Result:
feature-a → ~/worktrees/feature-a
feature-b → ~/worktrees/feature-b
feature-c → ~/worktrees/feature-c
```
---
## Error Handling
### Error: Mixed Success/Failure
**Strategy: Continue with successful ones**
```
2 of 3 worktrees created successfully.
✓ feature-a: Ready
✓ feature-b: Ready
✗ feature-c: Failed (branch conflict)
You can:
1. Start working with feature-a and feature-b
2. Resolve feature-c issue separately
3. Use Mode 1 to retry feature-c
```
### Error: All Creations Failed
```
Failed to create any worktrees.
Common causes:
- Branch names conflict with existing worktrees
- Directories already exist
- Branch doesn't exist and can't create
Review errors above and try again with corrections.
```
### Error: Some Installations Failed
```
Worktrees created but some installations failed:
✓ feature-a: Ready
✗ feature-b: Installation failed (network error)
You can:
1. Use feature-a immediately
2. Manually install in feature-b:
cd ../myapp-feature-b
npm install
```
---
## Performance Considerations
### Parallel vs. Sequential
**Worktree Creation:**
- **Sequential** (current approach)
- Reason: Git operations may conflict
- Time: ~1s per worktree
**Dependency Installation:**
- **Parallel** (recommended)
- Reason: Independent operations
- Time: ~12s total (vs. 36s sequential for 3)
### Disk Space
**Estimate before creation:**
```bash
# Repository size
du -sh .
# Per worktree: ~(repo size + node_modules size)
# Example: 50MB + 500MB = 550MB per worktree
# 3 worktrees = 1.65GB
```
**Warn if:**
- Creating > 5 worktrees
- Available disk space < 5GB
---
## Stop Conditions
**Stop immediately if:**
- [ ] Not in a git repository
- [ ] All worktree creations fail
- [ ] User cancels during confirmation
**Continue with warnings if:**
- [ ] Some worktree creations fail (partial success)
- [ ] Dependency installations fail
- [ ] Environment file copy fails
---
## Success Criteria
- [ ] At least one worktree created successfully
- [ ] All created worktrees verified
- [ ] Development environments ready (if requested)
- [ ] User provided with clear next steps for each worktree
- [ ] Summary report generated
- [ ] Cleanup instructions provided
---
## Example: Complete Flow
```
User: Create worktrees for feature-auth, feature-dashboard, and bugfix-login

View File

@@ -0,0 +1,726 @@
# Mode 3: Worktree Cleanup
## Overview
This mode safely removes git worktrees after work is complete. It includes safety checks for uncommitted changes, optional branch deletion, and cleanup verification.
## When to Use
- User says "remove worktree [name]"
- User wants to "clean up worktrees"
- User mentions "delete" or "cleanup" with "worktree"
- After feature is merged and branch is no longer needed
## Workflow
### Phase 0: Prerequisites & Context
#### Step 0.1: Verify Git Repository
```bash
git rev-parse --is-inside-work-tree
```
**Expected Output:**
```
true
```
**If fails:**
- Stop immediately
- Error: "Not in a git repository"
#### Step 0.2: List Current Worktrees
```bash
git worktree list
```
**Purpose:**
- Show user all available worktrees
- Help identify what to remove
- Detect if worktrees exist
**Expected Output:**
```
/Users/connor/myapp abc123 [main]
/Users/connor/myapp-feature-a def456 [feature-a]
/Users/connor/myapp-bugfix-123 ghi789 [bugfix-123]
```
**If only one worktree (main):**
- Message: "No additional worktrees to remove"
- Stop (nothing to cleanup)
---
### Phase 1: Identify Target Worktrees
#### Step 1.1: Determine Cleanup Scope
**Parse user request:**
- "remove worktree **feature-a**" → Single worktree
- "remove **all** worktrees" → All non-main worktrees
- "clean up worktrees" → All or let user select?
- "remove worktree at **/path**" → By path
**Extract:**
- `CLEANUP_MODE`: "single" | "all" | "selective"
- `TARGET`: branch name or path
#### Step 1.2: Map to Worktree Paths
**For single worktree:**
```bash
# If user provided branch name
TARGET_BRANCH="feature-a"
TARGET_PATH=$(git worktree list | grep "\[$TARGET_BRANCH\]" | awk '{print $1}')
# If user provided path
TARGET_PATH="/Users/connor/myapp-feature-a"
TARGET_BRANCH=$(git worktree list | grep "$TARGET_PATH" | grep -oP '\[\K[^\]]+')
```
**Verify target exists:**
```bash
if [ -z "$TARGET_PATH" ]; then
echo "Error: Worktree not found"
exit 1
fi
```
**For all worktrees:**
```bash
# Get all non-main worktrees
MAIN_PATH=$(git rev-parse --show-toplevel)
mapfile -t ALL_WORKTREES < <(git worktree list | grep -v "$MAIN_PATH" | awk '{print $1}')
```
#### Step 1.3: Show Cleanup Plan
**For single:**
```
Planning to remove:
Branch: feature-a
Path: /Users/connor/myapp-feature-a
Status: [to be determined in next step]
```
**For all:**
```
Planning to remove all worktrees:
feature-a → /Users/connor/myapp-feature-a
bugfix-123 → /Users/connor/myapp-bugfix-123
Main worktree will be preserved:
main → /Users/connor/myapp
```
**Confirm:**
"Proceed with cleanup? (yes/no)"
---
### Phase 2: Safety Checks
#### Step 2.1: Check for Uncommitted Changes
**For each target worktree:**
```bash
cd "$WORKTREE_PATH"
CHANGES=$(git status --porcelain)
if [ -n "$CHANGES" ]; then
echo "⚠️ Uncommitted changes detected"
git status --short
fi
```
**If changes found:**
```
⚠️ Warning: feature-a has uncommitted changes:
M src/auth.ts
?? src/new-file.ts
Options:
1. Abort cleanup (save your work first)
2. Show diff and decide
3. Continue anyway (DANGER: changes will be lost)
4. Stash changes automatically
```
**Recommended:** Abort and let user save work
**If user chooses stash:**
```bash
cd "$WORKTREE_PATH"
git stash push -m "Auto-stash before worktree removal $(date)"
STASH_CREATED=true
```
**Record stash location:**
```
✓ Changes stashed in main repository
To recover: git stash list
Stash name: stash@{0}: Auto-stash before worktree removal...
```
#### Step 2.2: Check Branch Merge Status
**Determine if branch is merged:**
```bash
BRANCH_NAME=$(cd "$WORKTREE_PATH" && git branch --show-current)
BASE_BRANCH="main" # or detect from git config
# Check if merged to base
if git branch --merged "$BASE_BRANCH" | grep -q "$BRANCH_NAME"; then
MERGE_STATUS="merged"
else
MERGE_STATUS="unmerged"
fi
```
**Report status:**
```
Branch status:
✓ feature-a: Merged to main
⚠️ bugfix-123: NOT merged to main
```
**If unmerged:**
```
⚠️ Warning: bugfix-123 is not merged to main
Unmerged commits:
[Show last few commits unique to this branch]
Options:
1. Abort cleanup (merge first)
2. Create backup branch (bugfix-123-backup)
3. Continue and delete branch
4. Remove worktree but keep branch
```
#### Step 2.3: Check Active Processes
**Check if worktree is in use:**
```bash
# Check for running processes in worktree
lsof +D "$WORKTREE_PATH" 2>/dev/null
# Check for open editors
if lsof +D "$WORKTREE_PATH" | grep -q "vim\|nvim\|code\|claude"; then
echo "⚠️ Active processes detected in worktree"
fi
```
**If processes found:**
```
⚠️ Warning: Processes are using this worktree:
- VS Code (PID: 12345)
- Claude Code (PID: 67890)
Please close these applications first, or force cleanup (not recommended).
```
---
### Phase 3: Execute Cleanup
#### Step 3.1: Remove Worktree
**Standard removal:**
```bash
git worktree remove "$WORKTREE_PATH"
```
**If removal fails (locked):**
```bash
# Try with force
git worktree remove --force "$WORKTREE_PATH"
```
**Expected Output:**
```
✓ Removed worktree: /Users/connor/myapp-feature-a
```
**Verify removal:**
```bash
if ! git worktree list | grep -q "$WORKTREE_PATH"; then
echo "✓ Worktree removed from git"
fi
if [ ! -d "$WORKTREE_PATH" ]; then
echo "✓ Directory removed"
fi
```
#### Step 3.2: Handle Branch Deletion
**Ask user:**
```
Worktree removed successfully.
Delete branch 'feature-a' too? (yes/no/backup)
Options:
yes - Delete branch permanently
no - Keep branch (can checkout later)
backup - Create backup branch before deleting
```
**If yes:**
```bash
git branch -d "$BRANCH_NAME"
```
**If force needed (unmerged):**
```bash
# Warn user first
echo "⚠️ Branch is unmerged. Use -D to force delete."
read -p "Force delete? (yes/no): " force
if [ "$force" == "yes" ]; then
git branch -D "$BRANCH_NAME"
fi
```
**If backup:**
```bash
# Create backup branch
BACKUP_NAME="${BRANCH_NAME}-backup-$(date +%Y%m%d)"
git branch "$BACKUP_NAME" "$BRANCH_NAME"
echo "✓ Created backup: $BACKUP_NAME"
# Then delete original
git branch -d "$BRANCH_NAME"
```
#### Step 3.3: Cleanup Verification
**Verify complete removal:**
```bash
# Check worktree list
if git worktree list | grep -q "$WORKTREE_PATH"; then
echo "✗ Worktree still in git worktree list"
ERROR=true
fi
# Check directory
if [ -d "$WORKTREE_PATH" ]; then
echo "✗ Directory still exists"
ERROR=true
fi
# Check branch (if deleted)
if [ "$DELETE_BRANCH" == "yes" ]; then
if git branch | grep -q "$BRANCH_NAME"; then
echo "✗ Branch still exists"
ERROR=true
fi
fi
```
**Success confirmation:**
```
✓ Cleanup verified:
✓ Worktree removed from git
✓ Directory deleted
✓ Branch deleted (if requested)
```
---
### Phase 4: Batch Cleanup (If Multiple Worktrees)
**For cleanup mode "all":**
#### Step 4.1: Process Each Worktree
```bash
REMOVED=()
FAILED=()
KEPT_BRANCHES=()
DELETED_BRANCHES=()
for worktree in "${ALL_WORKTREES[@]}"; do
echo "Processing: $worktree"
# Get branch name
BRANCH=$(git worktree list | grep "$worktree" | grep -oP '\[\K[^\]]+')
# Safety checks
cd "$worktree"
if [ -n "$(git status --porcelain)" ]; then
echo " ⚠️ Uncommitted changes - skipping"
FAILED+=("$worktree (uncommitted changes)")
continue
fi
# Remove worktree
if git worktree remove "$worktree"; then
REMOVED+=("$worktree")
echo " ✓ Removed"
# Ask about branch (or use default policy)
if git branch --merged main | grep -q "$BRANCH"; then
git branch -d "$BRANCH"
DELETED_BRANCHES+=("$BRANCH")
echo " ✓ Deleted merged branch: $BRANCH"
else
KEPT_BRANCHES+=("$BRANCH")
echo " Kept unmerged branch: $BRANCH"
fi
else
FAILED+=("$worktree")
echo " ✗ Failed"
fi
done
```
#### Step 4.2: Batch Cleanup Summary
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Batch Cleanup Complete
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Removed: ${#REMOVED[@]} worktrees
Failed: ${#FAILED[@]} worktrees
Successfully removed:
✓ /Users/connor/myapp-feature-a
✓ /Users/connor/myapp-feature-b
Failed to remove:
✗ /Users/connor/myapp-bugfix-123 (uncommitted changes)
Branches deleted:
✓ feature-a (merged)
✓ feature-b (merged)
Branches kept:
bugfix-123 (unmerged)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```
---
### Phase 5: Post-Cleanup Actions
#### Step 5.1: Show Remaining Worktrees
```bash
git worktree list
```
**Output:**
```
Remaining worktrees:
/Users/connor/myapp (main) ← current
/Users/connor/myapp-bugfix-123 (bugfix-123) ← has uncommitted changes
```
#### Step 5.2: Cleanup Orphaned References
**Prune removed worktrees:**
```bash
git worktree prune
```
**Purpose:**
- Remove administrative files for deleted worktrees
- Clean up .git/worktrees directory
**Output:**
```
✓ Pruned orphaned worktree references
```
#### Step 5.3: Show Recovery Information
**If changes were stashed:**
```
📦 Stashed Changes:
Your uncommitted changes are saved in git stash:
Stash: stash@{0}
Message: Auto-stash before worktree removal 2025-09-04
To recover:
git stash list # List all stashes
git stash show stash@{0} # Preview changes
git stash pop stash@{0} # Apply and remove stash
git stash apply stash@{0} # Apply but keep stash
```
**If branches were backed up:**
```
💾 Backed Up Branches:
Created backup branches before deletion:
feature-a-backup-20250904
feature-b-backup-20250904
To restore:
git checkout feature-a-backup-20250904
git branch feature-a # Recreate original branch
To remove backups:
git branch -D feature-a-backup-20250904
```
#### Step 5.4: Disk Space Reclaimed
**Calculate space saved:**
```bash
# Estimate space freed (approximate)
echo "Disk space reclaimed: ~$(du -sh $WORKTREE_PATH 2>/dev/null || echo 'N/A')"
```
**Show before/after:**
```
Disk Space Summary:
Before: 2.4 GB (3 worktrees)
After: 800 MB (1 worktree)
Reclaimed: ~1.6 GB
```
---
## Safety Protocols
### Before Removal
**Mandatory checks:**
- [ ] Worktree exists in git worktree list
- [ ] Not removing main/current worktree
- [ ] Checked for uncommitted changes
- [ ] Checked for unmerged commits
- [ ] Confirmed with user
### During Removal
**Safe removal process:**
- [ ] Use `git worktree remove` (not rm -rf)
- [ ] Verify removal succeeded
- [ ] Handle locked worktrees appropriately
- [ ] Preserve stashes if needed
### After Removal
**Verification:**
- [ ] Worktree not in git worktree list
- [ ] Directory removed
- [ ] Branch handled per user request
- [ ] Stashes accessible (if created)
- [ ] Backups created (if requested)
---
## Error Handling
### Error: Uncommitted Changes
```
Error: Cannot remove worktree with uncommitted changes
Current changes in feature-a:
M src/auth.ts
?? src/new-file.ts
Solutions:
1. Commit changes:
cd /path/to/worktree
git add .
git commit -m "Save work"
2. Stash changes:
Let me stash them automatically
3. Force remove (DANGER):
Changes will be lost forever
```
### Error: Worktree Locked
```
Error: Worktree is locked
Reason: Usually means processes are using it
Solutions:
1. Close all applications using this worktree
2. Check: lsof +D /path/to/worktree
3. Force remove: git worktree remove --force
```
### Error: Branch Checkout Elsewhere
```
Error: Cannot delete branch - checked out elsewhere
Branch 'feature-a' is checked out at:
/other/path/to/worktree
Solution:
1. Remove that worktree first
2. Or skip branch deletion (keep branch)
```
### Error: Unmerged Commits
```
Error: Branch has unmerged commits
Commits not in main:
abc123 feat: Add new feature
def456 fix: Bug fix
Options:
1. Merge first: git merge feature-a
2. Create backup: feature-a-backup
3. Force delete: git branch -D feature-a
```
---
## Advanced Features
### Feature 1: Smart Cleanup
**Auto-detect removable worktrees:**
```bash
# Find merged branches
git for-each-ref --format='%(refname:short)' refs/heads/ |
while read branch; do
if git branch --merged main | grep -q "$branch" &&
[ "$branch" != "main" ]; then
echo "Removable: $branch (merged)"
fi
done
```
**Offer cleanup:**
```
Found 3 worktrees with merged branches:
feature-a (merged 3 days ago)
feature-b (merged 1 week ago)
bugfix-old (merged 2 weeks ago)
Clean up all merged worktrees? (yes/select/no)
```
### Feature 2: Archive Instead of Delete
**Create archive before removal:**
```bash
ARCHIVE_DIR="$HOME/.git-worktree-archives"
ARCHIVE_NAME="${BRANCH_NAME}-$(date +%Y%m%d-%H%M%S).tar.gz"
# Archive worktree
tar -czf "$ARCHIVE_DIR/$ARCHIVE_NAME" -C "$(dirname $WORKTREE_PATH)" "$(basename $WORKTREE_PATH)"
echo "✓ Archived to: $ARCHIVE_DIR/$ARCHIVE_NAME"
echo " To restore: tar -xzf $ARCHIVE_NAME"
```
### Feature 3: Cleanup Report
**Generate detailed report:**
```markdown
# Worktree Cleanup Report
Date: 2025-09-04 15:30:00
## Removed Worktrees
- feature-a (merged, 15 commits, 3 days old)
- feature-b (merged, 8 commits, 1 week old)
## Branches Deleted
- feature-a (merged to main)
- feature-b (merged to main)
## Disk Space Reclaimed
- Total: 1.6 GB
- Per worktree: ~800 MB
## Stashes Created
- stash@{0}: Auto-stash feature-a
- stash@{1}: Auto-stash feature-b
## Recommendations
- Review stashes and apply if needed
- Consider cleanup policy for future
- Monitor disk usage regularly
```
---
## Stop Conditions
**Stop immediately if:**
- [ ] Not in a git repository
- [ ] Target worktree doesn't exist
- [ ] User cancels during confirmation
- [ ] Trying to remove main worktree
- [ ] Uncommitted changes and user aborts
**Continue with warnings if:**
- [ ] Some worktrees fail in batch mode
- [ ] Branch deletion fails
- [ ] Prune operation fails
---
## Success Criteria
- [ ] Worktree removed from git worktree list
- [ ] Directory deleted from filesystem
- [ ] Branch handled per user request (deleted/kept/backed up)
- [ ] No uncommitted changes lost
- [ ] Cleanup verified
- [ ] Recovery information provided (if applicable)
---
## Example: Complete Flow
```
User: Remove the feature-authentication worktree
Claude:
Checking worktree: feature-authentication
Location: /Users/connor/myapp-feature-authentication
Safety checks:
✓ No uncommitted changes
✓ Branch merged to main
✓ No active processes
Proceed with removal? (yes/no)
User: yes
Claude:
Removing worktree...
✓ Worktree removed from git
✓ Directory deleted
Delete branch 'feature-authentication' too? (yes/no/backup)
User: yes
Claude:
✓ Branch deleted (was merged to main)
Cleanup complete!
Remaining worktrees:
/Users/connor/myapp (main) ← current
Disk space reclaimed: ~800 MB
```

View File

@@ -0,0 +1,739 @@
# Mode 4: List and Manage Worktrees
## Overview
This mode provides visibility into existing worktrees with detailed status information, health checks, and management utilities. Use this for monitoring, troubleshooting, and understanding the current worktree state.
## When to Use
- User says "list worktrees" or "show worktrees"
- User asks "what worktrees do I have?"
- User wants "worktree status"
- User needs to "check worktrees"
- Diagnostic/troubleshooting scenarios
## Workflow
### Phase 0: Prerequisites
#### Step 0.1: Verify Git Repository
```bash
git rev-parse --is-inside-work-tree
```
**Expected Output:**
```
true
```
**If fails:**
- Message: "Not in a git repository"
- Suggest: Navigate to project root
- Stop
---
### Phase 1: Gather Worktree Information
#### Step 1.1: Get Basic Worktree List
```bash
git worktree list
```
**Expected Output:**
```
/Users/connor/myapp abc123 [main]
/Users/connor/myapp-feature-a def456 [feature-a]
/Users/connor/myapp-bugfix-123 ghi789 [bugfix-123]
```
**Parse into structured data:**
```bash
while read -r line; do
PATH=$(echo "$line" | awk '{print $1}')
COMMIT=$(echo "$line" | awk '{print $2}')
BRANCH=$(echo "$line" | grep -oP '\[\K[^\]]+')
WORKTREES["$BRANCH"]="$PATH"
COMMITS["$BRANCH"]="$COMMIT"
done < <(git worktree list)
```
#### Step 1.2: Enhance with Status Information
**For each worktree:**
```bash
for branch in "${!WORKTREES[@]}"; do
path="${WORKTREES[$branch]}"
# Get git status
cd "$path"
STATUS=$(git status --porcelain)
AHEAD_BEHIND=$(git rev-list --left-right --count origin/$branch...$branch 2>/dev/null)
# Check if clean
if [ -z "$STATUS" ]; then
CLEAN[$branch]=true
else
CLEAN[$branch]=false
CHANGE_COUNT[$branch]=$(echo "$STATUS" | wc -l)
fi
# Check ahead/behind
if [ -n "$AHEAD_BEHIND" ]; then
BEHIND=$(echo "$AHEAD_BEHIND" | awk '{print $1}')
AHEAD=$(echo "$AHEAD_BEHIND" | awk '{print $2}')
SYNC[$branch]="behind:$BEHIND ahead:$AHEAD"
fi
# Get last commit info
LAST_COMMIT[$branch]=$(git log -1 --format="%h %s" 2>/dev/null)
LAST_COMMIT_DATE[$branch]=$(git log -1 --format="%ar" 2>/dev/null)
# Check if merged
if git branch --merged main | grep -q "^[* ]*$branch$"; then
MERGED[$branch]=true
else
MERGED[$branch]=false
fi
# Check directory size
SIZE[$branch]=$(du -sh "$path" 2>/dev/null | awk '{print $1}')
done
```
#### Step 1.3: Detect Current Worktree
```bash
CURRENT_PATH=$(git rev-parse --show-toplevel)
CURRENT_BRANCH=$(git branch --show-current)
```
---
### Phase 2: Display Worktree Information
#### Step 2.1: Formatted List View
**Standard view:**
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Git Worktrees (3 total)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
● main ← current
/Users/connor/myapp
Clean working directory
Up to date with origin/main
Size: 850 MB
○ feature-a
/Users/connor/myapp-feature-a
3 uncommitted changes
2 commits ahead of origin
Last commit: feat: Add authentication (2 hours ago)
Size: 920 MB
○ bugfix-123
/Users/connor/myapp-bugfix-123
Clean working directory
Merged to main
Last commit: fix: Login redirect (1 day ago)
Size: 880 MB
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Total disk usage: 2.65 GB
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```
#### Step 2.2: Detailed View (Optional)
**With --detailed flag or user request:**
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Worktree: main
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Location: /Users/connor/myapp
Branch: main
Commit: abc123def
Status: Clean
Sync: Up to date with origin/main
Last Commit: chore: Update dependencies (3 hours ago)
Commits: 1,234 total
Contributors: 5 active
Size: 850 MB
Node Modules: 145,234 packages
Created: 3 months ago (2025-06-04)
Health: ✓ Healthy
✓ No uncommitted changes
✓ Synced with remote
✓ Dependencies installed
✓ No conflicts
─────────────────────────────────────────────
Worktree: feature-a
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Location: /Users/connor/myapp-feature-a
Branch: feature-a
Base Branch: main
Commit: def456ghi
Status: Modified (3 files)
Sync: 2 commits ahead, 0 behind
Last Commit: feat: Add authentication (2 hours ago)
Branch Age: 3 days
Size: 920 MB
Node Modules: 145,234 packages
Changes:
M src/auth/login.ts
M src/auth/register.ts
?? src/auth/types.ts
Health: ⚠️ Needs attention
⚠️ Uncommitted changes
⚠️ Not pushed to remote
✓ Dependencies up to date
✓ No conflicts with main
Recommendations:
- Commit changes: git add . && git commit
- Push to remote: git push origin feature-a
- Consider opening PR (3 commits ready)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```
#### Step 2.3: Table View
**Compact comparison:**
```
┌─────────────┬──────────────┬────────┬────────┬────────────┐
│ Branch │ Status │ Ahead │ Behind │ Size │
├─────────────┼──────────────┼────────┼────────┼────────────┤
│ main * │ Clean │ 0 │ 0 │ 850 MB │
│ feature-a │ Modified (3) │ 2 │ 0 │ 920 MB │
│ bugfix-123 │ Clean │ 0 │ 0 │ 880 MB │
└─────────────┴──────────────┴────────┴────────┴────────────┘
* Current worktree
```
#### Step 2.4: Status Icons
**Visual indicators:**
```
● main [clean] [synced] [active]
○ feature-a [modified] [ahead] [needs-push]
○ bugfix-123 [clean] [merged] [ready-to-cleanup]
```
**Icon legend:**
- `●` Current worktree
- `○` Other worktrees
- `✓` Healthy status
- `⚠️` Needs attention
- `✗` Error/problem
---
### Phase 3: Health Checks
#### Step 3.1: Check Worktree Health
**For each worktree:**
```bash
check_health() {
local path=$1
local branch=$2
local issues=()
cd "$path"
# Check 1: Uncommitted changes
if [ -n "$(git status --porcelain)" ]; then
issues+=("Uncommitted changes")
fi
# Check 2: Not synced with remote
if ! git diff --quiet @{u} 2>/dev/null; then
issues+=("Out of sync with remote")
fi
# Check 3: Merge conflicts
if git ls-files -u | grep -q .; then
issues+=("Has merge conflicts")
fi
# Check 4: Dependencies outdated
if [ -f "package.json" ]; then
if [ ! -d "node_modules" ]; then
issues+=("Dependencies not installed")
fi
fi
# Check 5: Behind main
behind=$(git rev-list --count HEAD..main 2>/dev/null)
if [ "$behind" -gt 10 ]; then
issues+=("Far behind main ($behind commits)")
fi
# Check 6: Stale branch (no activity)
last_commit_age=$(git log -1 --format=%ct 2>/dev/null)
current_time=$(date +%s)
days_old=$(( (current_time - last_commit_age) / 86400 ))
if [ "$days_old" -gt 30 ]; then
issues+=("Stale branch ($days_old days old)")
fi
if [ ${#issues[@]} -eq 0 ]; then
echo "✓ Healthy"
else
echo "⚠️ Issues: ${issues[*]}"
fi
}
```
#### Step 3.2: Generate Health Report
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Worktree Health Report
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Healthy: 1 worktree
✓ main
Needs Attention: 1 worktree
⚠️ feature-a
- Uncommitted changes
- Not pushed to remote
Ready for Cleanup: 1 worktree
○ bugfix-123
- Merged to main
- No uncommitted changes
- Last activity: 1 week ago
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```
---
### Phase 4: Management Actions
#### Step 4.1: Offer Actions
**Based on worktree states:**
```
Available Actions:
1. Clean up merged worktrees (1 candidate)
2. Sync all worktrees with remote
3. Check for stale worktrees (30+ days)
4. Show disk usage breakdown
5. Generate maintenance script
6. Navigate to specific worktree
What would you like to do?
```
#### Step 4.2: Quick Navigation
**Provide navigation commands:**
```bash
# For each worktree
echo "Navigate to $branch:"
echo " cd ${WORKTREES[$branch]}"
```
**Example output:**
```
Quick Navigation:
Main:
cd /Users/connor/myapp
Feature A:
cd /Users/connor/myapp-feature-a
Bugfix 123:
cd /Users/connor/myapp-bugfix-123
```
#### Step 4.3: Sync All Worktrees
**If user requests sync:**
```bash
for branch in "${!WORKTREES[@]}"; do
path="${WORKTREES[$branch]}"
echo "Syncing $branch..."
cd "$path"
# Fetch latest
git fetch origin
# Check if can fast-forward
if git merge-base --is-ancestor HEAD @{u} 2>/dev/null; then
git merge --ff-only @{u}
echo " ✓ Updated to latest"
else
echo " ⚠️ Cannot fast-forward (manual merge needed)"
fi
done
```
#### Step 4.4: Disk Usage Analysis
```
Disk Usage Breakdown:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Repository Files: 150 MB per worktree
Node Modules: 700 MB per worktree
Build Artifacts: 50 MB per worktree
Total per worktree: ~900 MB
Current worktrees: 3
Total disk usage: 2.65 GB
Potential savings if cleaned up:
- Remove bugfix-123: Save 880 MB
- Shared dependencies: Not possible (git worktrees)
Recommendations:
- Clean up merged branches regularly
- Use pnpm for better dependency management
- Remove build artifacts: npm run clean
```
---
### Phase 5: Advanced Features
#### Feature 5.1: Dependency Check
**Check for outdated dependencies:**
```bash
for branch in "${!WORKTREES[@]}"; do
path="${WORKTREES[$branch]}"
cd "$path"
if [ -f "package.json" ]; then
echo "Checking $branch..."
# Check if outdated
outdated=$(npm outdated --json 2>/dev/null || echo "{}")
if [ "$outdated" != "{}" ]; then
count=$(echo "$outdated" | jq 'length')
echo " ⚠️ $count outdated packages"
else
echo " ✓ Dependencies up to date"
fi
fi
done
```
#### Feature 5.2: Find Specific Files
**Search across all worktrees:**
```bash
find_in_worktrees() {
local filename=$1
for branch in "${!WORKTREES[@]}"; do
path="${WORKTREES[$branch]}"
if [ -f "$path/$filename" ]; then
echo "$branch: $path/$filename"
# Show diff from main if different
if diff -q "$path/$filename" "${WORKTREES[main]}/$filename" &>/dev/null; then
echo " (same as main)"
else
echo " (modified from main)"
fi
fi
done
}
```
#### Feature 5.3: Compare Worktrees
**Side-by-side comparison:**
```
Comparing: feature-a vs main
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Files changed: 15
Modified: 12
Added: 3
Removed: 0
Commits ahead: 5
feat: Add authentication
feat: Add user registration
test: Add auth tests
docs: Update API docs
chore: Update dependencies
Lines changed:
+450 additions
-120 deletions
Dependencies changed: 3
+ passport@0.6.0
+ bcrypt@5.1.0
+ jsonwebtoken@9.0.0
```
#### Feature 5.4: Activity Timeline
**Show recent activity across worktrees:**
```
Recent Activity Across All Worktrees:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Today:
feature-a: feat: Add authentication (2 hours ago)
main: chore: Update dependencies (3 hours ago)
Yesterday:
bugfix-123: fix: Login redirect (1 day ago)
This Week:
feature-a: Created worktree (3 days ago)
Last Week:
bugfix-123: Created worktree (8 days ago)
```
---
### Phase 6: Generate Management Scripts
#### Script 6.1: Status Check Script
```bash
#!/bin/bash
# worktree-status.sh
# Generated by git-worktree-setup skill
echo "Checking worktree status..."
git worktree list --porcelain | while read -r line; do
if [[ $line == worktree* ]]; then
path=${line#worktree }
cd "$path"
branch=$(git branch --show-current)
status=$(git status --short | wc -l)
echo "$branch: $status changes"
fi
done
```
#### Script 6.2: Sync All Script
```bash
#!/bin/bash
# sync-all-worktrees.sh
for worktree in $(git worktree list | awk '{print $1}'); do
echo "Syncing $worktree..."
cd "$worktree"
git fetch origin
git merge --ff-only @{u} 2>/dev/null && echo " ✓ Updated" || echo " ⚠️ Manual merge needed"
done
```
#### Script 6.3: Cleanup Helper
```bash
#!/bin/bash
# cleanup-merged-worktrees.sh
git worktree list | grep -v "$(git rev-parse --show-toplevel)" | while read -r line; do
path=$(echo "$line" | awk '{print $1}')
branch=$(echo "$line" | grep -oP '\[\K[^\]]+')
if git branch --merged main | grep -q "^[* ]*$branch$"; then
echo "Removing merged worktree: $branch"
git worktree remove "$path"
git branch -d "$branch"
fi
done
```
---
## Output Formats
### Format 1: Simple List
```
main (current)
feature-a
bugfix-123
```
### Format 2: With Paths
```
main → /Users/connor/myapp (current)
feature-a → /Users/connor/myapp-feature-a
bugfix-123 → /Users/connor/myapp-bugfix-123
```
### Format 3: With Status
```
main [clean] (current)
feature-a [3 changes] [ahead 2]
bugfix-123 [clean] [merged]
```
### Format 4: JSON (for scripts)
```json
{
"worktrees": [
{
"branch": "main",
"path": "/Users/connor/myapp",
"current": true,
"clean": true,
"ahead": 0,
"behind": 0,
"merged": false
},
{
"branch": "feature-a",
"path": "/Users/connor/myapp-feature-a",
"current": false,
"clean": false,
"changes": 3,
"ahead": 2,
"behind": 0,
"merged": false
}
]
}
```
---
## Information Hierarchy
**Level 1: Quick glance**
- Branch names
- Current indicator
- Basic status (clean/modified)
**Level 2: Detailed status**
- Paths
- Ahead/behind counts
- Last commit info
- Merge status
**Level 3: Deep inspection**
- File-level changes
- Dependency status
- Health checks
- Recommendations
**User chooses depth based on need**
---
## Error Handling
### No Worktrees Found
```
No additional worktrees found.
You only have the main worktree:
/Users/connor/myapp (main)
To create a worktree:
"Create a worktree for [branch-name]"
```
### Corrupted Worktree
```
⚠️ Worktree corruption detected: feature-a
Issues:
- Path doesn't exist: /Users/connor/myapp-feature-a
- Still in git worktree list
Fix:
git worktree prune
git worktree repair
```
### Permissions Issues
```
✗ Cannot access worktree: /path/to/worktree
Error: Permission denied
Solution:
Check file permissions:
ls -la /path/to/worktree
```
---
## Success Criteria
- [ ] All worktrees listed successfully
- [ ] Accurate status for each worktree
- [ ] Health checks completed
- [ ] Management options provided
- [ ] User can navigate/act on information
---
## Example: Complete Flow
```
User: Show me my worktrees
Claude:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Git Worktrees (3 total)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
● main (current)
/Users/connor/myapp
✓ Clean, synced
○ feature-a
/Users/connor/myapp-feature-a
⚠️ 3 changes, 2 commits ahead
○ bugfix-123
/Users/connor/myapp-bugfix-123
✓ Merged to main
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Recommendations:
- Commit changes in feature-a
- Clean up bugfix-123 (merged)
Would you like more details? (yes/no)
```