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,14 @@
# Changelog
## 1.0.0
- Refactored to Anthropic progressive disclosure pattern
- Updated description with "Use PROACTIVELY when..." format
- Extracted detailed content to modes/, data/, examples/ directories
## 0.1.0
- Initial skill release
- Automated git worktree creation
- Package manager detection
- Development environment initialization

View File

@@ -0,0 +1,405 @@
# Git Worktree Setup Skill
Automated git worktree creation for parallel Claude Code sessions. Work on multiple branches simultaneously without conflicts or context switching.
## Quick Start
### Single Worktree
```
User: Create a worktree for feature-authentication
```
Claude will:
1. Verify prerequisites
2. Create worktree at `../project-feature-authentication`
3. Set up development environment
4. Provide commands to start working
### Multiple Worktrees
```
User: Set up worktrees for feature-a, feature-b, and hotfix-123
```
Claude creates all three worktrees in parallel with full setup.
### List Worktrees
```
User: Show me my worktrees
```
Claude displays all active worktrees and their status.
### Cleanup
```
User: Remove the feature-authentication worktree
```
Claude safely removes the worktree after checking for uncommitted changes.
## Features
### Automatic Prerequisite Checking
- Verifies git repository
- Checks for uncommitted changes
- Validates branch existence
- Ensures no directory conflicts
- Confirms sufficient disk space
### Smart Defaults
- **Location:** `../repo-name-branch-name`
- **Branch type:** Auto-detects new vs. existing
- **Dev setup:** Automatically runs if package.json exists
- **Package manager:** Detects pnpm/yarn/bun/npm from lockfiles
### Development Environment Setup
- Detects package manager automatically
- Runs installation commands
- Optionally copies `.env` files
- Verifies setup succeeded
### Safe Cleanup
- Confirms before removing worktrees
- Checks for uncommitted changes
- Option to delete branch too
- Provides rollback instructions
### Clear Guidance
- Shows worktree path and status
- Provides navigation commands
- Explains how to start Claude Code
- Lists all worktrees for reference
## Usage Examples
### Example 1: New Feature Branch
**Scenario:** You want to start a new feature while keeping your current work.
```
User: Create a worktree for feature-user-profiles
Claude:
✓ Checking prerequisites...
✓ Repository: myapp
✓ Creating worktree at: /Users/connor/myapp-feature-user-profiles
✓ Created new branch: feature-user-profiles
✓ Running npm install...
✓ Development environment ready
Next steps:
cd ../myapp-feature-user-profiles
claude
All worktrees:
/Users/connor/myapp (main) ← current
/Users/connor/myapp-feature-user-profiles (feature-user-profiles) ← new
```
### Example 2: Work on Existing Branch
**Scenario:** You need to review a colleague's branch without switching your current work.
```
User: Set up a worktree for the existing bugfix-payment branch
Claude:
✓ Checking prerequisites...
✓ Found existing branch: bugfix-payment
✓ Creating worktree at: /Users/connor/myapp-bugfix-payment
✓ Checked out: bugfix-payment
✓ Running pnpm install...
✓ Ready for review
Navigate to worktree:
cd ../myapp-bugfix-payment
claude
```
### Example 3: Multiple Worktrees for Testing
**Scenario:** You need to test multiple features simultaneously.
```
User: Create worktrees for feature-dashboard, feature-reports, and feature-export
Claude:
✓ Creating 3 worktrees...
✓ feature-dashboard → /Users/connor/myapp-feature-dashboard
✓ feature-reports → /Users/connor/myapp-feature-reports
✓ feature-export → /Users/connor/myapp-feature-export
✓ Installing dependencies in all worktrees...
✓ All environments ready
Start working:
cd ../myapp-feature-dashboard && claude
cd ../myapp-feature-reports && claude
cd ../myapp-feature-export && claude
```
### Example 4: Emergency Hotfix
**Scenario:** Production issue needs immediate attention, but you're mid-feature.
```
User: I need a worktree for hotfix-login-redirect from main
Claude:
✓ Creating hotfix worktree from main...
✓ Worktree: /Users/connor/myapp-hotfix-login-redirect
✓ Branch: hotfix-login-redirect (from main)
✓ Dependencies installed
✓ Ready for emergency fix
Your current work in /Users/connor/myapp is untouched.
Fix the issue in:
cd ../myapp-hotfix-login-redirect
claude
```
### Example 5: Cleanup After Merge
**Scenario:** Your feature is merged, time to clean up.
```
User: Remove the feature-user-profiles worktree
Claude:
Checking /Users/connor/myapp-feature-user-profiles...
✓ No uncommitted changes
✓ Branch already merged to main
Remove worktree and delete branch? [yes/no]
User: yes
Claude:
✓ Removed worktree: /Users/connor/myapp-feature-user-profiles
✓ Deleted branch: feature-user-profiles
Remaining worktrees:
/Users/connor/myapp (main) ← current
```
## How It Works
### Worktree Creation Flow
```
User Request
Check Prerequisites
├─ Git repository? ✓
├─ Clean working dir? ⚠️ (warn if dirty)
├─ Branch exists? ✓
└─ Target dir available? ✓
Gather Information
├─ Branch name (from request)
├─ Location (default: ../repo-branch)
└─ Dev setup? (yes if package.json exists)
Create Worktree
├─ New branch: git worktree add path -b branch
└─ Existing: git worktree add path branch
Setup Environment
├─ Detect package manager (lockfiles)
├─ Run installation
└─ Copy .env (optional)
Verify & Report
├─ Check worktree list
├─ Show path and commands
└─ List all worktrees
```
### Package Manager Detection
The skill automatically detects your package manager:
| Lockfile | Package Manager |
|--------------------|-----------------|
| pnpm-lock.yaml | pnpm |
| yarn.lock | yarn |
| bun.lockb | bun |
| package-lock.json | npm |
## Benefits
### Parallel Development
- Work on multiple features simultaneously
- No context switching overhead
- Each worktree is isolated
- All share git history
### Risk Mitigation
- Keep stable main branch untouched
- Test risky changes in isolation
- Easy rollback - just remove worktree
- No stashing required
### Enhanced Productivity
- Run multiple Claude Code sessions
- Compare implementations side-by-side
- Test across branches
- Review PRs without switching
### Team Collaboration
- Review teammate's code without disruption
- Test integration of multiple features
- Maintain clean working directories
- Easy handoff between sessions
## Common Workflows
### Feature Development
1. Start new feature worktree
2. Implement in parallel with other work
3. Test in isolation
4. Merge when ready
5. Clean up worktree
### Code Review
1. Create worktree from PR branch
2. Review in Claude Code
3. Test changes
4. Remove worktree after approval
### Hotfix Management
1. Create worktree from main
2. Fix critical issue
3. Deploy hotfix
4. Clean up without affecting feature work
### Integration Testing
1. Create worktrees for all feature branches
2. Test interactions
3. Identify integration issues
4. Fix in respective worktrees
## Troubleshooting
### "Not in a git repository"
**Solution:** Navigate to your git repository root before requesting worktree.
### "Branch already checked out"
**Solution:** Remove existing worktree first: `User: remove worktree [name]`
### "Directory already exists"
**Solution:** Choose different location or remove existing directory.
### Package installation fails
**Solution:** Check network connection, or manually run install in worktree.
### Uncommitted changes warning
**Solution:** Commit or stash changes, or confirm to continue anyway.
## Best Practices
### Naming Conventions
- **Features:** `feature-descriptive-name`
- **Bugfixes:** `bugfix-issue-description`
- **Hotfixes:** `hotfix-critical-issue`
- **Experiments:** `experiment-idea-name`
### Worktree Management
- Clean up merged branches regularly
- Use descriptive branch names
- Keep worktrees focused on single tasks
- Commit often in each worktree
### Resource Management
- Limit active worktrees to ~5 simultaneously
- Each worktree consumes disk space
- Dependencies installed in each worktree
- Monitor disk usage for large projects
### Safety
- Always check for uncommitted changes before removing
- Use `git worktree list` to see all active worktrees
- Keep main worktree clean and stable
- Back up important work before experimenting
## Advanced Usage
### Custom Locations
```
User: Create worktree for feature-x at ~/projects/feature-x
```
### Skip Dev Setup
```
User: Create worktree for feature-y without installing dependencies
```
### Specific Base Branch
```
User: Create worktree for hotfix-z from the production branch
```
### Batch Operations
```
User: Create worktrees for all open PRs
```
## Integration with Claude Code
### Starting Sessions
After worktree creation:
```bash
cd /path/to/worktree
claude
```
### Parallel Sessions
Run Claude Code in multiple terminals:
```bash
# Terminal 1
cd ~/myapp-feature-a && claude
# Terminal 2
cd ~/myapp-feature-b && claude
# Terminal 3
cd ~/myapp-main && claude
```
### Session Handoff
Use `/handoff` in each session for context preservation:
```
# In worktree session
/handoff to document progress before switching
```
## Related Documentation
- [Git Worktree Official Docs](https://git-scm.com/docs/git-worktree)
- [Claude Code Parallel Sessions](https://docs.claude.com/en/docs/claude-code/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees)
- Troubleshooting: `data/troubleshooting.md`
- Best Practices: `data/best-practices.md`
- Example Workflows: `examples/sample-workflows.md`
## Support
### Skill Information
- **Version:** 1.0.0
- **Author:** Connor
- **Skill Type:** Automation/DevOps
### Getting Help
```
User: How do I use git worktrees?
User: Show me worktree examples
User: What are the benefits of worktrees?
```
---
**Ready to work in parallel?** Just ask Claude to create a worktree!

View File

@@ -0,0 +1,156 @@
---
name: git-worktree-setup
description: Use PROACTIVELY when working on multiple branches simultaneously or creating parallel Claude Code sessions. Automates git worktree creation with prerequisite checking, development environment initialization, and safe cleanup. Supports single worktree, batch creation, and worktree removal. Not for non-git projects or branch management without worktrees.
---
# Git Worktree Setup
Automates git worktree creation for parallel Claude Code sessions without conflicts.
## When to Use
**Trigger Phrases**:
- "create a worktree for [branch-name]"
- "set up worktree for [feature]"
- "create worktrees for [branch1], [branch2]"
- "remove worktree [name]"
- "list my worktrees"
**Use Cases**:
- Working on multiple features simultaneously
- Parallel Claude Code sessions on different branches
- Code review while continuing development
- Emergency hotfixes without interrupting work
## Quick Decision Matrix
| Request | Mode | Action |
|---------|------|--------|
| "create worktree for X" | Single | Create one worktree |
| "set up worktrees for X, Y" | Batch | Create multiple |
| "remove worktree X" | Cleanup | Remove specific |
| "list worktrees" | List | Display status |
## Workflow Overview
### Phase 0: Prerequisites (Mandatory)
```bash
# Verify git repo
git rev-parse --is-inside-work-tree
# Check uncommitted changes
git status --porcelain
# Get repo name
basename $(git rev-parse --show-toplevel)
```
### Phase 1: Gather Information
- Branch name (required)
- New or existing branch
- Location (default: `../repo-branch`)
- Setup dev environment
### Phase 2: Create Worktree
```bash
# New branch
git worktree add ../project-feature -b feature
# Existing branch
git worktree add ../project-bugfix bugfix
```
### Phase 3: Dev Environment Setup
- Detect package manager
- Run install
- Copy .env files
### Phase 4: Next Steps
- Show worktree path
- Provide navigation commands
- List all worktrees
## Quick Reference Commands
```bash
# Create with new branch
git worktree add ../project-branch -b branch-name
# Create from existing
git worktree add ../project-branch branch-name
# List all
git worktree list
# Remove worktree
git worktree remove ../project-branch
# Remove worktree and branch
git worktree remove ../project-branch
git branch -D branch-name
```
## Package Manager Detection
| Lock File | Manager |
|-----------|---------|
| pnpm-lock.yaml | pnpm |
| yarn.lock | yarn |
| bun.lockb | bun |
| package-lock.json | npm |
## Common Issues
| Issue | Cause | Fix |
|-------|-------|-----|
| "invalid reference" | Branch doesn't exist | Use `-b` for new |
| "already exists" | Directory exists | Choose different location |
| "uncommitted changes" | Dirty working dir | Commit or stash |
## Safety Protocols
**Before Creating**:
- [ ] Verify git repository
- [ ] Check clean working directory
- [ ] Validate target directory available
**Before Cleanup**:
- [ ] Confirm user intent
- [ ] Check for uncommitted changes
- [ ] Warn about permanent branch deletion
## Example Output
```
✓ Worktree created: /Users/connor/myapp-feature-auth
✓ Branch: feature-auth (new)
✓ Dependencies installed
Next steps:
cd ../myapp-feature-auth
claude
All worktrees:
- /path/to/main (main) ← current
- /path/to/worktree (feature-auth) ← new
```
## Success Criteria
- [ ] Worktree in correct location
- [ ] Branch checked out properly
- [ ] Files visible in directory
- [ ] Dev environment ready
- [ ] Appears in `git worktree list`
- [ ] User can start Claude Code
## Reference Materials
- `modes/` - Detailed mode workflows
- `templates/` - Setup script templates
- `data/best-practices.md`
- `data/troubleshooting.md`
---
**Version**: 1.0.0 | **Author**: Connor

View File

@@ -0,0 +1,666 @@
# Git Worktree Best Practices
A comprehensive guide to using git worktrees effectively for parallel development with Claude Code.
## Table of Contents
1. [Branch Naming Conventions](#branch-naming-conventions)
2. [Worktree Organization](#worktree-organization)
3. [Resource Management](#resource-management)
4. [Workflow Patterns](#workflow-patterns)
5. [Cleanup Strategies](#cleanup-strategies)
6. [Team Collaboration](#team-collaboration)
7. [Performance Optimization](#performance-optimization)
8. [Security Considerations](#security-considerations)
---
## Branch Naming Conventions
### Recommended Patterns
**Feature Branches:**
```
feature/descriptive-name
feature/user-authentication
feature/payment-integration
feature/dashboard-redesign
```
**Bugfix Branches:**
```
bugfix/issue-number-description
bugfix/123-login-redirect
bugfix/456-memory-leak
bugfix/789-validation-error
```
**Hotfix Branches:**
```
hotfix/critical-issue
hotfix/security-patch
hotfix/production-crash
```
**Experimental Branches:**
```
experiment/idea-name
experiment/new-architecture
experiment/performance-test
```
**Chore Branches:**
```
chore/dependency-updates
chore/refactor-auth
chore/update-docs
```
### Why Good Names Matter
- **Clarity:** Instantly understand the purpose
- **Organization:** Easy to group and filter
- **Cleanup:** Identify old branches quickly
- **Collaboration:** Team members know what's being worked on
### Naming Anti-Patterns
**Avoid:**
- Vague names: `fix`, `update`, `changes`
- Personal names: `johns-branch`, `temp-work`
- Dates only: `2025-09-04`, `sept-changes`
- No context: `test`, `wip`, `tmp`
**Use:**
- Descriptive: `feature/oauth-integration`
- Issue-linked: `bugfix/1234-payment-error`
- Purpose-clear: `experiment/graphql-migration`
---
## Worktree Organization
### Directory Structure
**Recommended: Sibling Directories**
```
~/projects/
├── myapp/ # Main worktree
├── myapp-feature-auth/ # Feature worktree
├── myapp-bugfix-login/ # Bugfix worktree
└── myapp-experiment-ui/ # Experiment worktree
```
**Alternative: Dedicated Worktrees Directory**
```
~/projects/
├── myapp/ # Main worktree
└── myapp-worktrees/ # All worktrees
├── feature-auth/
├── bugfix-login/
└── experiment-ui/
```
**Team Shared Setup:**
```
~/work/
├── myapp/ # Main (stable)
├── myapp-review/ # For PR reviews
├── myapp-hotfix/ # Emergency fixes
└── myapp-current/ # Active feature work
```
### Location Best Practices
**Do:**
- Keep worktrees near main repo (faster operations)
- Use consistent naming pattern
- Group by purpose if many worktrees
- Document custom locations in team wiki
**Don't:**
- Scatter worktrees across filesystem
- Use deep nested paths (slow operations)
- Mix worktrees with unrelated projects
- Create worktrees inside other worktrees
---
## Resource Management
### Disk Space
**Understanding Space Usage:**
```
Main repository: 150 MB
Each worktree:
- Repository files: 150 MB
- node_modules: 700 MB
- Build artifacts: 50 MB
Total: ~900 MB per worktree
```
**Space Management Strategies:**
1. **Limit Active Worktrees**
- Keep 3-5 active worktrees maximum
- Clean up merged branches weekly
- Archive instead of keeping indefinitely
2. **Share When Possible**
- Use pnpm for shared node_modules
- Enable yarn's zero-installs
- Share build caches
3. **Clean Build Artifacts**
```bash
# Clean before removing worktree
cd worktree-path
npm run clean
rm -rf dist/ build/ .next/
```
4. **Monitor Disk Usage**
```bash
# Check worktree sizes
du -sh ../myapp-*
# Find largest directories
du -sh */ | sort -hr | head -10
```
### Memory Considerations
**Running Multiple Claude Code Sessions:**
- Each session: ~500MB RAM
- 3 parallel sessions: ~1.5GB RAM
- Keep system RAM usage < 80%
**Tips:**
- Close unused sessions
- Restart sessions periodically
- Use `/handoff` to preserve context
- Monitor system performance
### CPU Management
**Avoid Parallel Builds:**
```bash
# Bad: Running builds in all worktrees simultaneously
cd worktree1 && npm run build &
cd worktree2 && npm run build &
cd worktree3 && npm run build &
# Good: Sequential or limited parallel
npm run build # One at a time
```
**Use Build Queues:**
- Serialize resource-intensive operations
- Limit concurrent processes
- Use tools like `make -j2` for controlled parallelism
---
## Workflow Patterns
### Pattern 1: Feature Development
```
1. Create worktree for feature
└─ git worktree add ../myapp-feature-x -b feature-x
2. Develop in isolation
└─ cd ../myapp-feature-x && claude
3. Test independently
└─ npm test && npm run build
4. Merge when ready
└─ git checkout main && git merge feature-x
5. Clean up
└─ git worktree remove ../myapp-feature-x
```
### Pattern 2: PR Review
```
1. Create worktree from PR branch
└─ git worktree add ../myapp-review pr-branch
2. Review code with Claude Code
└─ cd ../myapp-review && claude
3. Test changes
└─ npm install && npm test
4. Leave feedback
└─ (Review in Claude Code)
5. Remove when done
└─ git worktree remove ../myapp-review
```
### Pattern 3: Hotfix While Developing
```
Current state: Working on feature-x in worktree
1. Create hotfix worktree from main
└─ git worktree add ../myapp-hotfix -b hotfix-critical
2. Fix issue in hotfix worktree
└─ cd ../myapp-hotfix && claude
3. Test and deploy
└─ npm test && deploy
4. Continue feature work
└─ cd ../myapp-feature-x
5. Merge hotfix to both main and feature
└─ git checkout feature-x && git merge main
```
### Pattern 4: Integration Testing
```
1. Create worktrees for all features
└─ Batch create: feature-a, feature-b, feature-c
2. Test each independently
└─ Parallel Claude Code sessions
3. Create integration worktree
└─ git worktree add ../myapp-integration -b integration
4. Merge all features to integration
└─ git merge feature-a feature-b feature-c
5. Test combined functionality
└─ npm test && npm run e2e
6. Clean up all worktrees after merge
```
### Pattern 5: Comparison Testing
```
1. Keep main worktree as baseline
2. Create feature worktree for new implementation
3. Run same tests in both
4. Compare results side-by-side
5. Make decision based on data
```
---
## Cleanup Strategies
### Daily Cleanup
**Check merged branches:**
```bash
# List merged branches
git branch --merged main | grep -v "main"
# Remove worktrees for merged branches
for branch in $(git branch --merged main | grep -v "main"); do
git worktree remove ../myapp-$branch 2>/dev/null || true
git branch -d $branch
done
```
### Weekly Cleanup
**Review all worktrees:**
```bash
# List all worktrees with age
git worktree list | while read path commit branch; do
cd "$path"
age=$(git log -1 --format=%ar)
echo "$branch: last activity $age"
done
```
**Remove stale worktrees (30+ days):**
```bash
# Manual review first, then remove
git worktree list | grep -v main | while read path; do
cd "$path"
last_commit=$(git log -1 --format=%ct)
current_time=$(date +%s)
days_old=$(( (current_time - last_commit) / 86400 ))
if [ $days_old -gt 30 ]; then
echo "Stale: $path ($days_old days old)"
fi
done
```
### Automated Cleanup
**Git hooks for cleanup:**
```bash
# .git/hooks/post-merge
#!/bin/bash
# Auto-cleanup merged branches
CURRENT_BRANCH=$(git branch --show-current)
if [ "$CURRENT_BRANCH" = "main" ]; then
echo "Checking for merged worktrees..."
git branch --merged main | grep -v "main" | while read branch; do
# Check if worktree exists
if git worktree list | grep -q "\\[$branch\\]"; then
echo "Found merged worktree: $branch"
echo "Run: git worktree remove /path/to/$branch"
fi
done
fi
```
### Cleanup Checklist
Before removing a worktree:
- [ ] No uncommitted changes
- [ ] Branch merged or backed up
- [ ] No important local files
- [ ] Dependencies can be reinstalled
- [ ] No running processes
---
## Team Collaboration
### Shared Worktree Conventions
**Team Standards Document:**
```markdown
# Worktree Standards
## Naming
- Features: feature/{jira-id}-{description}
- Bugfixes: bugfix/{issue-id}-{description}
- Reviews: review-{pr-number}
## Location
- All worktrees in ~/projects/myapp-worktrees/
## Lifecycle
- Create: Before starting work
- Update: Sync with main daily
- Remove: Within 24h of merge
## Resources
- Max 3 active worktrees per developer
- Clean up merged branches in daily standup
```
### Communication
**Notify team of worktrees:**
```bash
# In team chat
Working on worktrees:
- feature-auth (for AUTH-123)
- bugfix-login (for BUG-456)
- review-pr-789 (reviewing Sarah's PR)
Will clean up by EOD.
```
### Shared Scripts
**Team cleanup script:**
```bash
#!/bin/bash
# team-worktree-status.sh
echo "Worktree Status for $(whoami)"
echo "================================"
git worktree list | while read path commit branch; do
cd "$path"
status=$(git status --porcelain | wc -l)
behind=$(git rev-list --count HEAD..origin/main 2>/dev/null || echo "N/A")
echo "$branch:"
echo " Changes: $status"
echo " Behind main: $behind"
echo " Path: $path"
echo ""
done
```
---
## Performance Optimization
### Git Operations
**Fetch Once, Use Everywhere:**
```bash
# In main worktree
git fetch --all
# All worktrees automatically have access
# No need to fetch in each worktree
```
**Shallow Clones for Reviews:**
```bash
# For temporary review worktrees
git worktree add --detach ../review-pr HEAD
cd ../review-pr
git fetch origin pull/123/head:pr-123
git checkout pr-123
```
### Build Performance
**Share Build Caches:**
```bash
# In main repo
export TURBO_CACHE_DIR=/shared/turbo-cache
# All worktrees use same cache
# Builds are faster after first run
```
**Incremental Builds:**
```bash
# Don't clean between branches
npm run build # Uses previous cache
# Only clean when needed
npm run clean && npm run build
```
### Dependency Management
**pnpm (Recommended for Worktrees):**
```bash
# Global store, minimal duplication
pnpm install
# All worktrees reference same packages
# Saves ~80% disk space
```
**npm/yarn (Standard):**
```bash
# Each worktree has full node_modules
# More disk space, complete isolation
npm install
```
---
## Security Considerations
### Environment Variables
**Never commit .env:**
```bash
# Each worktree needs own .env
cp ../.env .env
# Add to .gitignore (should already be there)
echo ".env" >> .gitignore
```
**Worktree-specific configs:**
```bash
# Different API endpoints per worktree
# main: production API
# feature-x: staging API
# experiment: local API
# .env in each worktree
API_URL=https://staging.api.example.com
```
### Credentials
**Don't share credentials between worktrees:**
- Separate SSH keys if needed
- Different tokens per environment
- Revoke credentials in removed worktrees
**Clean credentials before removal:**
```bash
# Before removing worktree
cd worktree-path
rm -f .env .env.local
rm -f config/credentials.json
# Then remove
git worktree remove $(pwd)
```
### Access Control
**Workspace Permissions:**
```bash
# Ensure proper permissions
chmod 700 ~/projects/myapp-*
# No group/other access to sensitive worktrees
```
---
## Advanced Tips
### Worktree Templates
**Quick setup script:**
```bash
#!/bin/bash
# new-worktree.sh
BRANCH=$1
PATH=../myapp-$BRANCH
git worktree add $PATH -b $BRANCH
cd $PATH
cp ../.env .
pnpm install
code . # Open in editor
echo "Worktree ready: $PATH"
```
### Automation
**Auto-sync worktrees:**
```bash
# cron job: daily sync
0 9 * * * cd ~/projects/myapp && git fetch && \
for wt in $(git worktree list | awk '{print $1}'); do \
cd $wt && git pull --rebase 2>/dev/null; \
done
```
### Monitoring
**Disk space alerts:**
```bash
# Alert when worktrees exceed threshold
TOTAL=$(du -sm ~/projects/myapp-* | awk '{sum+=$1} END {print sum}')
if [ $TOTAL -gt 10000 ]; then
echo "Warning: Worktrees using ${TOTAL}MB"
fi
```
---
## Quick Reference
### Commands
```bash
# Create
git worktree add ../myapp-branch -b branch
# List
git worktree list
# Remove
git worktree remove ../myapp-branch
# Prune orphaned
git worktree prune
# Repair if corrupted
git worktree repair
# Move worktree
git worktree move old-path new-path
# Lock (prevent removal)
git worktree lock path
# Unlock
git worktree unlock path
```
### Aliases
```bash
# Add to ~/.gitconfig
[alias]
wt = worktree
wtl = worktree list
wta = "!f() { git worktree add ../$(basename $(pwd))-$1 -b $1; }; f"
wtr = worktree remove
wtp = worktree prune
```
**Usage:**
```bash
git wta feature-x # Creates ../myapp-feature-x
git wtl # Lists all worktrees
git wtr ../myapp-feature-x # Removes worktree
```
---
## Summary
**Key Takeaways:**
1. **Use descriptive branch names** - Future you will thank you
2. **Keep worktrees organized** - Consistent location pattern
3. **Monitor disk space** - Limit active worktrees
4. **Clean up regularly** - Don't hoard merged branches
5. **Document team conventions** - Everyone follows same patterns
6. **Optimize for performance** - Use pnpm, shared caches
7. **Secure sensitive data** - Clean .env before removal
8. **Automate repetitive tasks** - Scripts for common operations
**Remember:** Git worktrees are powerful tools for parallel development. Used well, they enhance productivity. Used poorly, they create chaos. Follow these best practices for worktree success!

View File

@@ -0,0 +1,922 @@
# Git Worktree Troubleshooting Guide
Comprehensive troubleshooting for common git worktree issues, errors, and edge cases.
## Table of Contents
1. [Creation Errors](#creation-errors)
2. [Permission Issues](#permission-issues)
3. [Corruption and Repair](#corruption-and-repair)
4. [Branch Conflicts](#branch-conflicts)
5. [Directory Issues](#directory-issues)
6. [Performance Problems](#performance-problems)
7. [Dependency Installation](#dependency-installation)
8. [Git Operations](#git-operations)
9. [Cleanup Issues](#cleanup-issues)
10. [Advanced Debugging](#advanced-debugging)
---
## Creation Errors
### Error: "fatal: invalid reference"
**Full Error:**
```
fatal: invalid reference: feature-x
```
**Cause:**
Branch doesn't exist (typo or branch not created yet).
**Solutions:**
1. **Create new branch:**
```bash
git worktree add ../myapp-feature-x -b feature-x
```
2. **Check branch name:**
```bash
git branch -a # List all branches
git branch | grep feature # Search for branch
```
3. **Track remote branch:**
```bash
git worktree add ../myapp-feature-x -b feature-x --track origin/feature-x
```
---
### Error: "fatal: 'path' already exists"
**Full Error:**
```
fatal: '../myapp-feature-x' already exists
```
**Cause:**
Directory already exists at target path.
**Solutions:**
1. **Remove directory:**
```bash
rm -rf ../myapp-feature-x
git worktree add ../myapp-feature-x -b feature-x
```
2. **Use different location:**
```bash
git worktree add ../myapp-feature-x-v2 -b feature-x
```
3. **Check if it's a forgotten worktree:**
```bash
git worktree list # If not listed, safe to remove
```
---
### Error: "fatal: 'branch' is already checked out"
**Full Error:**
```
fatal: 'feature-x' is already checked out at '/Users/connor/myapp-feature-x'
```
**Cause:**
Branch is already checked out in another worktree.
**Solutions:**
1. **Navigate to existing worktree:**
```bash
git worktree list # Find existing worktree
cd /path/to/existing/worktree
```
2. **Remove existing worktree:**
```bash
git worktree remove /path/to/existing/worktree
# Then create new one
git worktree add ../myapp-feature-x feature-x
```
3. **Use different branch:**
```bash
git worktree add ../myapp-feature-x-new -b feature-x-new
```
---
### Error: "fatal: not a git repository"
**Full Error:**
```
fatal: not a git repository (or any of the parent directories): .git
```
**Cause:**
Not in a git repository.
**Solutions:**
1. **Navigate to repository:**
```bash
cd /path/to/your/git/repo
git worktree add ../worktree-name -b branch-name
```
2. **Verify git repository:**
```bash
git status # Should not error
ls -la .git # Should exist
```
3. **Initialize if needed:**
```bash
git init # Only if starting new repo
```
---
## Permission Issues
### Error: "Permission denied"
**Full Error:**
```
error: unable to create file: Permission denied
```
**Cause:**
Insufficient permissions to create worktree directory.
**Solutions:**
1. **Check parent directory permissions:**
```bash
ls -ld $(dirname /path/to/worktree)
```
2. **Fix permissions:**
```bash
chmod 755 /path/to/parent
```
3. **Use location you own:**
```bash
git worktree add ~/worktrees/myapp-feature-x -b feature-x
```
4. **Check disk quota:**
```bash
df -h # Check disk space
quota -s # Check user quota (if applicable)
```
---
### Error: "Operation not permitted"
**Cause:**
macOS security restrictions or readonly filesystem.
**Solutions:**
1. **Grant Full Disk Access:**
- System Preferences → Security & Privacy → Privacy
- Full Disk Access → Add Terminal/IDE
2. **Check filesystem mount:**
```bash
mount | grep "$(pwd)"
# If shows 'ro' (readonly), remount:
# sudo mount -uw /
```
3. **Use different location:**
```bash
# Use home directory (always writable)
git worktree add ~/worktrees/myapp-feature-x -b feature-x
```
---
## Corruption and Repair
### Error: "Worktree path doesn't exist but listed"
**Symptoms:**
```
git worktree list
# Shows: /path/to/missing/worktree abc123 [branch]
# But: ls /path/to/missing/worktree
# No such file or directory
```
**Cause:**
Worktree directory manually deleted without `git worktree remove`.
**Solutions:**
1. **Prune orphaned references:**
```bash
git worktree prune
git worktree list # Verify removed
```
2. **Force remove:**
```bash
git worktree remove --force /path/to/missing/worktree
```
3. **Manual cleanup:**
```bash
# Check administrative files
ls .git/worktrees/
# Remove specific worktree directory
rm -rf .git/worktrees/branch-name
git worktree prune
```
---
### Error: "Corrupt worktree"
**Symptoms:**
- Can't checkout files
- Git commands fail in worktree
- Missing .git file in worktree
**Solutions:**
1. **Repair worktree:**
```bash
git worktree repair
```
2. **Check .git file:**
```bash
cat worktree-path/.git
# Should show: gitdir: /path/to/main/.git/worktrees/branch
```
3. **Recreate .git file:**
```bash
# If corrupt, recreate
echo "gitdir: $(git rev-parse --git-dir)/worktrees/branch-name" > worktree-path/.git
```
4. **Last resort - recreate worktree:**
```bash
# Backup any changes
cp -r worktree-path worktree-path-backup
# Remove and recreate
git worktree remove --force worktree-path
git worktree add worktree-path branch-name
# Restore changes
cp worktree-path-backup/* worktree-path/
```
---
## Branch Conflicts
### Error: "Cannot delete branch checked out in worktree"
**Full Error:**
```
error: Cannot delete branch 'feature-x' checked out at '/path/to/worktree'
```
**Cause:**
Trying to delete branch that's checked out in a worktree.
**Solutions:**
1. **Remove worktree first:**
```bash
git worktree remove /path/to/worktree
git branch -d feature-x
```
2. **Force delete (if sure):**
```bash
# This will remove worktree administrative files
git worktree remove --force /path/to/worktree
git branch -D feature-x
```
3. **Switch branch in worktree:**
```bash
cd /path/to/worktree
git checkout different-branch
# Now can delete feature-x in main repo
```
---
### Error: "Reference is not a tree"
**Full Error:**
```
fatal: reference is not a tree: abc123
```
**Cause:**
Commit reference doesn't exist or is corrupted.
**Solutions:**
1. **Fetch latest:**
```bash
git fetch --all
git worktree add ../worktree branch-name
```
2. **Use specific commit:**
```bash
git worktree add ../worktree commit-hash
```
3. **Check object exists:**
```bash
git cat-file -t abc123 # Should show 'commit'
git fsck # Check repository health
```
---
## Directory Issues
### Error: "Disk quota exceeded"
**Full Error:**
```
error: unable to create file: Disk quota exceeded
```
**Cause:**
Not enough disk space or quota exceeded.
**Solutions:**
1. **Check disk space:**
```bash
df -h
du -sh /path/to/worktrees
```
2. **Clean up old worktrees:**
```bash
git worktree list
git worktree remove /path/to/old/worktree
```
3. **Clean build artifacts:**
```bash
cd worktree
rm -rf node_modules dist build .next
npm install # Reinstall only what's needed
```
4. **Use different partition:**
```bash
git worktree add /other/partition/worktree -b branch
```
---
### Error: "Worktree directory not empty"
**Symptoms:**
Directory exists with files but not a git worktree.
**Solutions:**
1. **Remove conflicting directory:**
```bash
# Backup if needed
mv /path/to/directory /path/to/directory-backup
# Create worktree
git worktree add /path/to/directory -b branch
```
2. **Merge contents:**
```bash
# Create worktree elsewhere
git worktree add /temp/location -b branch
# Copy existing files
cp -r /path/to/directory/* /temp/location/
# Move worktree
git worktree move /temp/location /path/to/directory
```
---
## Performance Problems
### Problem: "Slow git operations in worktree"
**Symptoms:**
- `git status` takes 10+ seconds
- `git checkout` is very slow
- High CPU usage
**Solutions:**
1. **Check filesystem performance:**
```bash
# Test read speed
time cat large-file.txt > /dev/null
# Test write speed
time dd if=/dev/zero of=test.img bs=1M count=1024
```
2. **Disable status optimizations:**
```bash
# If on network drive
git config core.fsmonitor false
git config core.untrackedCache false
```
3. **Use sparse checkout:**
```bash
git sparse-checkout init --cone
git sparse-checkout set src/ tests/
```
4. **Move to local disk:**
```bash
# Network drives are slow
git worktree add ~/local-worktrees/feature-x -b feature-x
```
---
### Problem: "High disk usage"
**Symptoms:**
- Each worktree uses 1GB+
- Running out of disk space
**Solutions:**
1. **Use pnpm:**
```bash
npm install -g pnpm
# pnpm uses content-addressable storage
# Saves ~70% disk space for node_modules
```
2. **Share node_modules:**
```bash
# In main repo
pnpm install
# In worktree
pnpm install --prefer-offline
# Uses shared cache
```
3. **Clean build artifacts:**
```bash
# Add to package.json
"scripts": {
"clean": "rm -rf dist build .next coverage"
}
# Run before removing worktree
npm run clean
```
4. **Limit worktrees:**
```bash
# Keep only 3-4 active worktrees
# Remove old ones regularly
```
---
## Dependency Installation
### Error: "npm install fails in worktree"
**Symptoms:**
```
npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path /path/to/worktree/package.json
```
**Solutions:**
1. **Verify package.json exists:**
```bash
ls -la worktree-path/package.json
```
2. **Check file permissions:**
```bash
chmod 644 worktree-path/package.json
```
3. **Copy from main repo:**
```bash
cp main-repo/package.json worktree-path/
cp main-repo/package-lock.json worktree-path/
```
4. **Reinstall:**
```bash
cd worktree-path
rm -rf node_modules package-lock.json
npm install
```
---
### Error: "Lockfile conflict"
**Symptoms:**
```
npm ERR! Cannot read property 'match' of undefined
```
**Cause:**
Lockfile from different package manager or corrupted.
**Solutions:**
1. **Match package manager:**
```bash
# Check main repo
ls main-repo/*lock*
# If pnpm-lock.yaml:
pnpm install
# If yarn.lock:
yarn install
# If package-lock.json:
npm install
```
2. **Remove and regenerate:**
```bash
rm package-lock.json
npm install # Creates fresh lockfile
```
3. **Copy lockfile from main:**
```bash
cp main-repo/package-lock.json worktree/
npm ci # Clean install from lockfile
```
---
## Git Operations
### Error: "Cannot merge in worktree"
**Symptoms:**
```
error: Your local changes would be overwritten by merge
```
**Solutions:**
1. **Commit or stash changes:**
```bash
git add .
git commit -m "WIP: save changes"
# Or:
git stash push -m "WIP before merge"
```
2. **Merge with strategy:**
```bash
git merge --no-commit --no-ff branch-name
# Review changes, then commit
```
3. **Rebase instead:**
```bash
git rebase main
# Replay commits on top of main
```
---
### Error: "Detached HEAD in worktree"
**Symptoms:**
```
You are in 'detached HEAD' state
```
**Cause:**
Checked out specific commit instead of branch.
**Solutions:**
1. **Create branch from current state:**
```bash
git checkout -b new-branch-name
```
2. **Checkout existing branch:**
```bash
git checkout branch-name
```
3. **Return to main branch:**
```bash
git checkout main
```
---
## Cleanup Issues
### Error: "Cannot remove worktree - dirty"
**Full Error:**
```
error: repository is dirty, please commit or stash your changes
```
**Cause:**
Worktree has uncommitted changes.
**Solutions:**
1. **Commit changes:**
```bash
cd worktree-path
git add .
git commit -m "Final changes before removal"
git push # Push if needed
# Now remove
git worktree remove $(pwd)
```
2. **Stash changes:**
```bash
cd worktree-path
git stash push -m "Saved before worktree removal"
# Stash is available in main repo
git worktree remove $(pwd)
```
3. **Force remove (lose changes):**
```bash
git worktree remove --force worktree-path
# ⚠️ WARNING: All uncommitted changes lost!
```
---
### Error: "Worktree locked"
**Full Error:**
```
error: 'worktree-path' is locked; use 'unlock' to override, or 'remove --force'
```
**Cause:**
Worktree manually locked to prevent removal.
**Solutions:**
1. **Unlock and remove:**
```bash
git worktree unlock worktree-path
git worktree remove worktree-path
```
2. **Force remove:**
```bash
git worktree remove --force worktree-path
```
3. **Check why locked:**
```bash
cat .git/worktrees/branch-name/locked
# Shows reason for lock
```
---
## Advanced Debugging
### Diagnostic Commands
**Check worktree health:**
```bash
# List all worktrees
git worktree list
# Check git database
git fsck
# Verify repository integrity
git status
git branch -vv
# Check worktree administrative files
ls -la .git/worktrees/
# Detailed worktree info
git worktree list --porcelain
```
**Debug specific worktree:**
```bash
cd worktree-path
# Check git configuration
git config --list --local
# Check remote tracking
git branch -vv
# Check what's tracked
git ls-files
# Check for corruption
git fsck --full
```
---
### Enable Debug Logging
**Git verbose mode:**
```bash
GIT_TRACE=1 git worktree add ../debug -b debug
# Shows all git commands executed
```
**Trace specific operations:**
```bash
# Trace file operations
GIT_TRACE_PACK_ACCESS=1 git status
# Trace setup
GIT_TRACE_SETUP=1 git worktree list
# Trace performance
GIT_TRACE_PERFORMANCE=1 git status
```
---
### Recovery Procedures
**Recover deleted worktree:**
```bash
# If worktree removed but branch still exists
git worktree add ../recovered branch-name
# If branch deleted too
git reflog # Find commit
git worktree add ../recovered commit-hash
git checkout -b branch-name
```
**Recover from backup:**
```bash
# If you have time machine / backup
cp -r /backup/path/to/worktree /current/path/
# Repair git references
git worktree repair
```
**Nuclear option - start fresh:**
```bash
# Backup important changes
cp -r worktree-path/src ~/backup/
# Remove all worktrees
git worktree list | grep -v "$(git rev-parse --show-toplevel)" | \
awk '{print $1}' | xargs -I{} git worktree remove --force {}
# Clean up administrative files
git worktree prune
# Recreate from scratch
git worktree add ../fresh-start branch-name
# Restore backed up changes
cp -r ~/backup/* ../fresh-start/src/
```
---
## Getting Help
### Before Asking for Help
**Collect diagnostic information:**
```bash
#!/bin/bash
# worktree-diagnostics.sh
echo "=== Git Version ==="
git --version
echo -e "\n=== Worktree List ==="
git worktree list
echo -e "\n=== Repository Status ==="
git status
echo -e "\n=== Branch Info ==="
git branch -vv
echo -e "\n=== Remote Info ==="
git remote -v
echo -e "\n=== Worktree Admin Files ==="
ls -la .git/worktrees/
echo -e "\n=== Disk Space ==="
df -h .
echo -e "\n=== File Permissions ==="
ls -ld .git
ls -ld .git/worktrees/
# Save to file
# ./worktree-diagnostics.sh > diagnostics.txt
```
### Common Support Channels
- **Git Documentation:** `git help worktree`
- **GitHub Issues:** Check git/git repository
- **Stack Overflow:** Tag: `git-worktree`
- **Git Mailing List:** git@vger.kernel.org
---
## Quick Reference
### Most Common Issues
1. **Directory exists:** `rm -rf path && git worktree add path branch`
2. **Branch checked out:** `git worktree remove old-path && git worktree add new-path branch`
3. **Orphaned worktree:** `git worktree prune`
4. **Permission denied:** `chmod 755 parent-dir`
5. **Can't remove (dirty):** `git stash && git worktree remove path`
### Essential Commands
```bash
# Diagnose
git worktree list
git fsck
git worktree prune
# Repair
git worktree repair
git worktree unlock path
# Force operations (use with caution)
git worktree remove --force path
git branch -D branch-name
```
---
## Summary
Most git worktree issues fall into these categories:
1. **Creation conflicts** - Directory or branch conflicts
2. **Permission issues** - Filesystem restrictions
3. **Corruption** - Manual deletions or crashes
4. **Cleanup problems** - Uncommitted changes or locks
**General troubleshooting approach:**
1. Read error message carefully
2. Check `git worktree list` for current state
3. Use `git worktree prune` to clean orphans
4. Use `--force` flags only when necessary
5. Document unusual issues for team
**Remember:** Git worktrees are just checkouts in different directories. Most git commands work the same way - when in doubt, treat it like a normal git repository!

View File

@@ -0,0 +1,753 @@
# Git Worktree Sample Workflows
Real-world examples of using git worktrees with Claude Code for parallel development.
## Table of Contents
1. [Daily Development Workflows](#daily-development-workflows)
2. [Code Review Workflows](#code-review-workflows)
3. [Emergency Hotfix Workflows](#emergency-hotfix-workflows)
4. [Experimentation Workflows](#experimentation-workflows)
5. [Team Collaboration Workflows](#team-collaboration-workflows)
6. [Testing and QA Workflows](#testing-and-qa-workflows)
7. [Advanced Workflows](#advanced-workflows)
---
## Daily Development Workflows
### Workflow 1: Parallel Feature Development
**Scenario:** You're working on feature A when a new urgent feature B request comes in.
**Steps:**
```bash
# Currently working on feature-authentication
cd ~/projects/myapp
git branch # Shows: * feature-authentication
# New request: add dashboard feature
# Create worktree instead of switching branches
User: "Create a worktree for feature-dashboard"
Claude:
✓ Creating worktree...
Location: ~/projects/myapp-feature-dashboard
Branch: feature-dashboard (new)
Dependencies: Installing...
✓ Ready!
# Open new Claude Code session
cd ~/projects/myapp-feature-dashboard
claude
# Now have two parallel sessions:
# Terminal 1: Working on authentication
# Terminal 2: Working on dashboard
```
**Benefits:**
- No context switching
- No stashing required
- Independent testing
- Parallel Claude Code sessions
---
### Workflow 2: Bug Investigation During Feature Work
**Scenario:** Mid-feature development, you need to investigate a production bug.
**Steps:**
```bash
# Current state: Working on feature-redesign with uncommitted changes
User: "Create a worktree from main for bugfix-login-error"
Claude:
Checking prerequisites...
⚠️ You have uncommitted changes in current worktree
Continue? (Current work won't be affected)
User: "yes"
Claude:
✓ Creating worktree from main...
Location: ~/projects/myapp-bugfix-login-error
Branch: bugfix-login-error (from main)
✓ Clean state (no redesign changes)
✓ Ready!
# Investigate bug in clean environment
cd ~/projects/myapp-bugfix-login-error
claude
# After fix:
git add .
git commit -m "fix: resolve login redirect issue"
git push
# Create PR for bugfix
gh pr create --title "Fix: Login redirect error"
# Return to feature work
cd ~/projects/myapp-feature-redesign
# Feature work still intact with all uncommitted changes
```
**Key Points:**
- Bug investigated in clean environment
- Feature work undisturbed
- Easy context switching
- Independent commits and PRs
---
## Code Review Workflows
### Workflow 3: PR Review Without Interruption
**Scenario:** Teammate requests review while you're coding.
**Steps:**
```bash
# Current: Working on feature-payments
# Teammate: "Can you review PR #456?"
User: "Create a worktree for PR 456 review"
Claude:
Fetching PR #456...
PR Branch: feature-user-settings
Author: @teammate
Creating review worktree...
✓ Location: ~/projects/myapp-review-456
✓ Checked out: feature-user-settings
✓ Installing dependencies...
✓ Ready for review!
# Review in fresh environment
cd ~/projects/myapp-review-456
claude
# In Claude Code, review changes:
# - Read code
# - Run tests: npm test
# - Check build: npm run build
# - Test locally: npm run dev
# Leave feedback on GitHub
gh pr review 456 --comment --body "LGTM! Tests pass, code looks good."
# Clean up review worktree
cd ~/projects/myapp
User: "Remove the review-456 worktree"
Claude:
✓ No uncommitted changes
✓ Removed worktree
✓ Disk space freed: ~850MB
# Back to feature work
cd ~/projects/myapp-feature-payments
# Continue where you left off
```
**Benefits:**
- Review in pristine environment
- Your work stays untouched
- Run tests without affecting your code
- Quick cleanup after review
---
### Workflow 4: Compare Multiple PR Approaches
**Scenario:** Two PRs propose different solutions to the same problem.
**Steps:**
```bash
User: "Create worktrees for PR 123 and PR 124 to compare"
Claude:
Creating comparison worktrees...
✓ PR #123 (approach-a): ~/projects/myapp-pr-123
✓ PR #124 (approach-b): ~/projects/myapp-pr-124
Installing dependencies in parallel...
✓ Both environments ready!
# Test approach A
cd ~/projects/myapp-pr-123
npm test
npm run benchmark
# Test approach B
cd ~/projects/myapp-pr-124
npm test
npm run benchmark
# Compare results:
# Approach A: 250ms, cleaner code
# Approach B: 180ms, more complex
# Decision: Approve approach B, suggest code cleanup
# Clean up both
User: "Clean up PR worktrees"
Claude:
✓ Removed: myapp-pr-123
✓ Removed: myapp-pr-124
```
**Use Case:**
- A/B testing different implementations
- Performance comparison
- Side-by-side code review
- Data-driven decisions
---
## Emergency Hotfix Workflows
### Workflow 5: Production Hotfix During Feature Development
**Scenario:** Critical production bug needs immediate fix.
**Steps:**
```bash
# Current: Deep in feature development with many uncommitted changes
# Alert: Production is down!
User: "Create emergency hotfix worktree from production branch"
Claude:
🚨 Creating emergency hotfix...
✓ Source: production branch
✓ Location: ~/projects/myapp-hotfix-critical
✓ Branch: hotfix-api-timeout (from production)
✓ Clean slate (production code)
✓ Dependencies: Installing...
✓ Ready in 15 seconds!
Next: cd ~/projects/myapp-hotfix-critical && claude
# Fix in isolated environment
cd ~/projects/myapp-hotfix-critical
claude
# In Claude Code:
# 1. Identify issue
# 2. Write fix
# 3. Test thoroughly
# 4. Deploy
git add .
git commit -m "hotfix: increase API timeout to 30s"
git push origin hotfix-api-timeout
# Deploy to production
./deploy-hotfix.sh
# Merge to main
git checkout main
git merge hotfix-api-timeout
git push
# Merge to feature branch too (avoid conflicts later)
cd ~/projects/myapp-feature-redesign
git merge main
# Clean up hotfix worktree
User: "Remove hotfix worktree"
Claude:
✓ Hotfix merged to main and feature branch
✓ Production fixed
✓ Removed worktree
✓ Back to feature development
```
**Critical Benefits:**
- Instant context switch
- Production code isolated
- No stashing complex changes
- Merge back to all branches easily
---
### Workflow 6: Multiple Simultaneous Hotfixes
**Scenario:** Multiple production issues at once.
**Steps:**
```bash
User: "Create hotfix worktrees for login-bug, payment-error, and api-timeout"
Claude:
Creating 3 hotfix worktrees from production...
✓ hotfix-login-bug → ~/projects/myapp-hotfix-login
✓ hotfix-payment-error → ~/projects/myapp-hotfix-payment
✓ hotfix-api-timeout → ~/projects/myapp-hotfix-api
Installing dependencies in parallel...
All ready!
Assign to team:
Developer 1: cd ~/projects/myapp-hotfix-login
Developer 2: cd ~/projects/myapp-hotfix-payment
Developer 3: cd ~/projects/myapp-hotfix-api
# Each developer works in isolation
# Fixes don't conflict
# Deploy independently
# Merge back when done
```
**Team Benefits:**
- Parallel hotfix development
- No branch conflicts
- Independent testing
- Fast resolution
---
## Experimentation Workflows
### Workflow 7: Test Radical Architecture Change
**Scenario:** Want to try a major refactor without risking main work.
**Steps:**
```bash
User: "Create an experiment worktree for testing GraphQL migration"
Claude:
Creating experiment worktree...
✓ Location: ~/projects/myapp-experiment-graphql
✓ Branch: experiment-graphql-migration
✓ Based on: main
✓ Ready for experimentation!
cd ~/projects/myapp-experiment-graphql
claude
# Implement radical changes:
# - Replace REST with GraphQL
# - New schema design
# - Different data layer
# Test the experiment
npm test
npm run benchmark
# Results look promising!
# Migrate learnings to feature branch
# Or if experiment fails:
User: "Remove experiment worktree"
Claude:
✓ No harm done to main codebase
✓ Learnings documented
✓ Removed worktree
```
**Experimentation Benefits:**
- Safe to fail
- No polluting main branch
- Easy to abandon
- Document learnings
---
### Workflow 8: Performance Comparison
**Scenario:** Test if optimization actually improves performance.
**Steps:**
```bash
User: "Create worktrees for baseline and optimization comparison"
Claude:
Creating comparison environment...
✓ Baseline: ~/projects/myapp-baseline (current main)
✓ Optimization: ~/projects/myapp-optimized (new branch)
# Test baseline
cd ~/projects/myapp-baseline
npm run benchmark > baseline-results.txt
# Implement optimization
cd ~/projects/myapp-optimized
claude
# (Make optimization changes)
npm run benchmark > optimized-results.txt
# Compare results
diff baseline-results.txt optimized-results.txt
# Baseline: 450ms avg
# Optimized: 220ms avg
# Improvement: 51% faster ✓
# Optimization validated - merge it!
git checkout main
git merge experiment-optimized
# Clean up
User: "Remove comparison worktrees"
```
---
## Team Collaboration Workflows
### Workflow 9: Pair Programming Setup
**Scenario:** Pair programming with screen sharing.
**Steps:**
```bash
# Developer 1 (driver)
User: "Create pairing worktree for feature-checkout"
Claude:
✓ Created: ~/projects/myapp-pairing-checkout
✓ Fresh environment
✓ Ready for pairing session
cd ~/projects/myapp-pairing-checkout
claude
# Share screen, develop together
# Commit frequently
git add .
git commit -m "WIP: checkout flow"
git push
# Developer 2 (navigator) checks out same worktree later
git worktree add ~/projects/myapp-pairing-checkout pairing-checkout
cd ~/projects/myapp-pairing-checkout
# Continue from where Dev 1 left off
# After pairing session
User: "Merge pairing work to main feature branch"
Claude:
✓ Merged pairing-checkout → feature-checkout
✓ Removed pairing worktree
✓ Clean state
```
---
### Workflow 10: Integration Testing Multiple Features
**Scenario:** Test how three features work together before merging.
**Steps:**
```bash
# Current state:
# - feature-auth (ready)
# - feature-dashboard (ready)
# - feature-reports (ready)
User: "Create integration worktree combining auth, dashboard, and reports"
Claude:
Creating integration environment...
✓ Base: main branch
✓ Location: ~/projects/myapp-integration-test
✓ Branch: integration-test
Merging features...
✓ Merged: feature-auth
✓ Merged: feature-dashboard
✓ Merged: feature-reports
Running tests...
⚠️ 2 integration test failures detected
# Fix integration issues in integration worktree
cd ~/projects/myapp-integration-test
claude
# Fix conflicts and integration issues
git add .
git commit -m "fix: resolve feature integration conflicts"
# All tests pass!
npm test
# ✓ All 156 tests passing
# Now safe to merge features to main
git checkout main
git merge feature-auth
git merge feature-dashboard
git merge feature-reports
# Clean up
User: "Remove integration test worktree"
```
---
## Testing and QA Workflows
### Workflow 11: Test Across Multiple Node Versions
**Scenario:** Ensure compatibility with Node 16, 18, and 20.
**Steps:**
```bash
User: "Create worktrees for testing Node 16, 18, and 20"
Claude:
Creating test environments...
✓ node16: ~/projects/myapp-test-node16
✓ node18: ~/projects/myapp-test-node18
✓ node20: ~/projects/myapp-test-node20
# Terminal 1: Node 16
cd ~/projects/myapp-test-node16
nvm use 16
npm install
npm test
# Result: 3 failures (deprecated API)
# Terminal 2: Node 18
cd ~/projects/myapp-test-node18
nvm use 18
npm install
npm test
# Result: All pass ✓
# Terminal 3: Node 20
cd ~/projects/myapp-test-node20
nvm use 20
npm install
npm test
# Result: All pass ✓
# Fix Node 16 compatibility in separate worktree
cd ~/projects/myapp-test-node16
claude
# Fix deprecated API usage
# All versions pass!
```
---
### Workflow 12: Regression Testing
**Scenario:** Test new feature doesn't break existing functionality.
**Steps:**
```bash
# Have feature branch with changes
User: "Create worktrees for regression testing: baseline and feature"
Claude:
Setting up regression test...
✓ Baseline: ~/projects/myapp-baseline (main branch)
✓ Feature: ~/projects/myapp-feature-new-ui
# Run tests in baseline
cd ~/projects/myapp-baseline
npm test -- --coverage > baseline-coverage.txt
# Run tests in feature
cd ~/projects/myapp-feature-new-ui
npm test -- --coverage > feature-coverage.txt
# Compare
diff baseline-coverage.txt feature-coverage.txt
# Baseline: 142/142 tests pass, 87% coverage
# Feature: 156/156 tests pass, 89% coverage
# Added: 14 new tests ✓
# Coverage improved ✓
# No regressions ✓
# Safe to merge!
```
---
## Advanced Workflows
### Workflow 13: Dependency Update Testing
**Scenario:** Test major dependency update before applying to all branches.
**Steps:**
```bash
User: "Create worktree to test React 19 upgrade"
Claude:
✓ Created: ~/projects/myapp-react19-test
✓ Branch: test-react19-upgrade
cd ~/projects/myapp-react19-test
claude
# Upgrade React
npm install react@19 react-dom@19
# Update code for breaking changes
# Run tests
npm test
# Some failures - fix them
# Document migration steps
# Once stable, apply to feature branches
cd ~/projects/myapp-feature-auth
npm install react@19 react-dom@19
# Apply same fixes
# Repeat for other worktrees
```
---
### Workflow 14: Database Migration Testing
**Scenario:** Test database schema changes safely.
**Steps:**
```bash
User: "Create worktree for testing database migration"
Claude:
✓ Created: ~/projects/myapp-db-migration-test
✓ Using test database
cd ~/projects/myapp-db-migration-test
# Point to test database
echo "DATABASE_URL=postgresql://localhost/myapp_test" > .env
# Run migration
npm run migrate:up
# Test application with new schema
npm test
npm run dev
# Migration successful!
# Apply to staging/production
# Clean up test worktree
```
---
## Complete Real-World Example
### Full Development Day with Worktrees
```bash
# 9:00 AM - Start day, check tasks
git worktree list
# Just main worktree
# 9:15 AM - Start planned feature
User: "Create worktree for feature-notifications"
# Work on notifications...
# 11:30 AM - Urgent: Review teammate's PR
User: "Create worktree for reviewing PR 234"
# Review, approve, remove worktree
# 1:00 PM - Production bug reported
User: "Create hotfix worktree from production"
# Fix bug, deploy, merge back
# 2:30 PM - Back to notifications feature
cd ~/projects/myapp-feature-notifications
# Continue where I left off
# 3:00 PM - PM requests quick prototype
User: "Create experiment worktree for dashboard prototype"
# Build prototype, demo to PM
# Not approved - remove worktree
# 4:00 PM - Finish notifications feature
git add .
git commit -m "feat: add push notifications"
git push
# Create PR
gh pr create --title "Feature: Push Notifications"
# 4:30 PM - Clean up
User: "Show my worktrees"
Claude:
Current worktrees:
main (clean)
feature-notifications (PR created)
hotfix-production (merged and deployed)
User: "Clean up merged worktrees"
Claude:
✓ Removed: hotfix-production
✓ Kept: feature-notifications (PR pending)
# End of day - organized workspace
```
---
## Summary
Git worktrees enable:
- **Parallel development** without context switching
- **Safe experimentation** without risk
- **Fast emergency responses** without disruption
- **Efficient code reviews** in isolation
- **Comprehensive testing** across environments
- **Team collaboration** with shared workflows
**Key Principles:**
1. Create worktrees liberally - they're cheap
2. Clean up regularly - avoid clutter
3. Use descriptive names - future you will thank you
4. Document team conventions - consistency matters
5. Automate common patterns - save time
**Remember:** Worktrees are a tool. Use them when they add value. Don't overcomplicate simple tasks.

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)
```

View File

@@ -0,0 +1,498 @@
#!/bin/bash
# Git Worktree Batch Setup Script
# Generated by git-worktree-setup skill
#
# This script automates the creation of multiple git worktrees with parallel dependency installation.
#
# Usage:
# ./batch-setup.sh branch1 branch2 branch3 [--no-install] [--pattern=/path/{branch}]
set -euo pipefail
# ============================================================================
# Configuration
# ============================================================================
BRANCHES=()
SKIP_INSTALL=false
PATH_PATTERN=""
# Parse arguments
for arg in "$@"; do
case $arg in
--no-install)
SKIP_INSTALL=true
;;
--pattern=*)
PATH_PATTERN="${arg#*=}"
;;
*)
BRANCHES+=("$arg")
;;
esac
done
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# ============================================================================
# Helper Functions
# ============================================================================
print_success() {
echo -e "${GREEN}${NC} $1"
}
print_error() {
echo -e "${RED}${NC} $1" >&2
}
print_warning() {
echo -e "${YELLOW}${NC} $1"
}
print_info() {
echo -e "${BLUE}${NC} $1"
}
print_header() {
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "$1"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
}
# ============================================================================
# Prerequisite Checks
# ============================================================================
check_prerequisites() {
print_header "Checking Prerequisites"
# Check if in git repository
if ! git rev-parse --is-inside-work-tree &>/dev/null; then
print_error "Not in a git repository"
exit 1
fi
print_success "Git repository detected"
# Get repository info
REPO_NAME=$(basename "$(git rev-parse --show-toplevel)")
REPO_ROOT=$(git rev-parse --show-toplevel)
CURRENT_BRANCH=$(git branch --show-current)
print_info "Repository: $REPO_NAME"
print_info "Current branch: $CURRENT_BRANCH"
# Check for branch names
if [ ${#BRANCHES[@]} -eq 0 ]; then
print_error "No branch names provided"
echo "Usage: $0 branch1 branch2 branch3 [--no-install] [--pattern=/path/{branch}]"
exit 1
fi
print_info "Branches to create: ${#BRANCHES[@]}"
for branch in "${BRANCHES[@]}"; do
echo " - $branch"
done
}
validate_branches() {
print_header "Validating Branches"
declare -gA BRANCH_TYPES
declare -gA WORKTREE_PATHS
for branch in "${BRANCHES[@]}"; do
# Check if branch exists
if git show-ref --verify "refs/heads/$branch" &>/dev/null; then
BRANCH_TYPES[$branch]="existing"
print_info "$branch: existing branch"
elif git show-ref --verify "refs/remotes/origin/$branch" &>/dev/null; then
BRANCH_TYPES[$branch]="remote"
print_info "$branch: exists on remote"
else
BRANCH_TYPES[$branch]="new"
print_info "$branch: will create new branch"
fi
# Determine worktree path
if [ -n "$PATH_PATTERN" ]; then
# Use custom pattern
WORKTREE_PATHS[$branch]="${PATH_PATTERN//\{branch\}/$branch}"
else
# Use default pattern
WORKTREE_PATHS[$branch]="$(dirname "$REPO_ROOT")/$REPO_NAME-$branch"
fi
echo "${WORKTREE_PATHS[$branch]}"
done
}
check_directory_conflicts() {
print_header "Checking for Directory Conflicts"
CONFLICTS=()
for branch in "${BRANCHES[@]}"; do
path="${WORKTREE_PATHS[$branch]}"
if [ -d "$path" ]; then
CONFLICTS+=("$branch$path")
fi
done
if [ ${#CONFLICTS[@]} -gt 0 ]; then
print_warning "Found ${#CONFLICTS[@]} directory conflicts:"
for conflict in "${CONFLICTS[@]}"; do
echo " $conflict"
done
echo ""
echo "Options:"
echo " 1. Skip conflicting worktrees"
echo " 2. Remove and recreate"
echo " 3. Abort"
read -p "Choose (1/2/3): " -r choice
case $choice in
1)
print_info "Will skip conflicting directories"
for conflict in "${CONFLICTS[@]}"; do
branch="${conflict%% →*}"
# Remove from BRANCHES array
BRANCHES=("${BRANCHES[@]/$branch}")
done
# Remove empty elements
BRANCHES=("${BRANCHES[@]}")
;;
2)
print_warning "Removing conflicting directories..."
for conflict in "${CONFLICTS[@]}"; do
path="${conflict##*→ }"
rm -rf "$path"
print_success "Removed: $path"
done
;;
3)
print_info "Aborted by user"
exit 0
;;
esac
else
print_success "No directory conflicts"
fi
}
# ============================================================================
# Worktree Creation
# ============================================================================
create_worktrees() {
print_header "Creating Worktrees"
declare -gA CREATED_WORKTREES
declare -ga FAILED_WORKTREES
local total=${#BRANCHES[@]}
local current=0
for branch in "${BRANCHES[@]}"; do
((current++))
echo ""
print_info "[$current/$total] Creating worktree for $branch..."
path="${WORKTREE_PATHS[$branch]}"
branch_type="${BRANCH_TYPES[$branch]}"
case $branch_type in
new)
if git worktree add "$path" -b "$branch" 2>&1; then
CREATED_WORKTREES[$branch]="$path"
print_success "$branch: Created with new branch"
else
FAILED_WORKTREES+=("$branch")
print_error "$branch: Failed to create"
fi
;;
existing)
if git worktree add "$path" "$branch" 2>&1; then
CREATED_WORKTREES[$branch]="$path"
print_success "$branch: Created from existing branch"
else
FAILED_WORKTREES+=("$branch")
print_error "$branch: Failed to create"
fi
;;
remote)
if git worktree add "$path" -b "$branch" --track "origin/$branch" 2>&1; then
CREATED_WORKTREES[$branch]="$path"
print_success "$branch: Created tracking remote"
else
FAILED_WORKTREES+=("$branch")
print_error "$branch: Failed to create"
fi
;;
esac
done
echo ""
print_header "Worktree Creation Summary"
print_success "Created: ${#CREATED_WORKTREES[@]}/$total worktrees"
if [ ${#FAILED_WORKTREES[@]} -gt 0 ]; then
print_error "Failed: ${#FAILED_WORKTREES[@]} worktrees"
for failed in "${FAILED_WORKTREES[@]}"; do
echo " - $failed"
done
fi
}
# ============================================================================
# Development Environment Setup
# ============================================================================
detect_package_manager() {
cd "$REPO_ROOT"
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"
elif [ -f "package.json" ]; then
PKG_MANAGER="npm"
INSTALL_CMD="npm install"
else
PKG_MANAGER="none"
INSTALL_CMD=""
fi
if [ "$PKG_MANAGER" != "none" ]; then
print_info "Using $PKG_MANAGER for all worktrees"
fi
}
install_dependencies() {
if [ "$SKIP_INSTALL" = true ]; then
print_info "Skipping dependency installation (--no-install flag)"
return 0
fi
if [ "$PKG_MANAGER" = "none" ]; then
print_info "No package.json found, skipping dependency installation"
return 0
fi
if [ ${#CREATED_WORKTREES[@]} -eq 0 ]; then
print_warning "No worktrees created, skipping dependency installation"
return 0
fi
print_header "Installing Dependencies (Parallel)"
declare -gA INSTALL_SUCCESS
declare -gA INSTALL_FAILED
declare -A INSTALL_PIDS
# Start installations in parallel
for branch in "${!CREATED_WORKTREES[@]}"; do
path="${CREATED_WORKTREES[$branch]}"
print_info "Starting installation in $branch..."
# Run in background
(
cd "$path"
$INSTALL_CMD > "/tmp/install-$branch.log" 2>&1
) &
INSTALL_PIDS[$branch]=$!
done
# Wait for all installations
for branch in "${!INSTALL_PIDS[@]}"; do
pid=${INSTALL_PIDS[$branch]}
print_info "Waiting for $branch (PID: $pid)..."
if wait "$pid"; then
INSTALL_SUCCESS[$branch]=true
print_success "$branch: Dependencies installed"
else
INSTALL_FAILED[$branch]=true
print_error "$branch: Installation failed (see /tmp/install-$branch.log)"
fi
done
echo ""
print_header "Installation Summary"
print_success "Successful: ${#INSTALL_SUCCESS[@]}/${#CREATED_WORKTREES[@]}"
if [ ${#INSTALL_FAILED[@]} -gt 0 ]; then
print_warning "Failed: ${#INSTALL_FAILED[@]}"
for branch in "${!INSTALL_FAILED[@]}"; do
path="${CREATED_WORKTREES[$branch]}"
echo " - $branch (manually run: cd $path && $INSTALL_CMD)"
done
fi
}
# ============================================================================
# Summary and Next Steps
# ============================================================================
print_final_summary() {
print_header "Batch Worktree Creation Complete"
echo "Created: ${#CREATED_WORKTREES[@]}/${#BRANCHES[@]} worktrees"
if [ ${#FAILED_WORKTREES[@]} -gt 0 ]; then
echo "Failed: ${#FAILED_WORKTREES[@]}/${#BRANCHES[@]} worktrees"
fi
echo ""
if [ ${#CREATED_WORKTREES[@]} -gt 0 ]; then
echo "Successful worktrees:"
for branch in "${!CREATED_WORKTREES[@]}"; do
path="${CREATED_WORKTREES[$branch]}"
branch_type="${BRANCH_TYPES[$branch]}"
print_success "$branch$path ($branch_type)"
done
fi
echo ""
if [ ${#FAILED_WORKTREES[@]} -gt 0 ]; then
echo "Failed worktrees:"
for branch in "${FAILED_WORKTREES[@]}"; do
print_error "$branch"
done
echo ""
fi
print_header "Next Steps"
echo "Start working on each worktree:"
echo ""
for branch in "${!CREATED_WORKTREES[@]}"; do
path="${CREATED_WORKTREES[$branch]}"
echo "${BLUE}# $branch${NC}"
echo "cd $path"
echo "claude"
echo ""
done
print_header "All Worktrees"
git worktree list
echo ""
print_header "Batch Management"
echo "List all: git worktree list"
echo "Remove all:"
for branch in "${!CREATED_WORKTREES[@]}"; do
path="${CREATED_WORKTREES[$branch]}"
echo " git worktree remove $path"
done
echo ""
# Offer to generate cleanup script
read -p "Generate cleanup script? (yes/no): " -r
if [[ $REPLY =~ ^[Yy]es$ ]]; then
generate_cleanup_script
fi
}
generate_cleanup_script() {
CLEANUP_SCRIPT="cleanup-worktrees.sh"
cat > "$CLEANUP_SCRIPT" << 'EOF'
#!/bin/bash
# Cleanup script for batch-created worktrees
# Generated by git-worktree-setup skill
set -euo pipefail
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'
echo "Cleaning up worktrees..."
EOF
for branch in "${!CREATED_WORKTREES[@]}"; do
path="${CREATED_WORKTREES[$branch]}"
cat >> "$CLEANUP_SCRIPT" << EOF
echo "Removing $branch..."
if git worktree remove "$path" 2>/dev/null; then
echo -e "\${GREEN}✓\${NC} Removed: $branch"
read -p "Delete branch '$branch'? (yes/no): " -r
if [[ \$REPLY =~ ^[Yy]es$ ]]; then
git branch -d "$branch" 2>/dev/null && echo -e "\${GREEN}✓\${NC} Deleted branch: $branch" || echo -e "\${RED}✗\${NC} Failed to delete branch: $branch"
fi
else
echo -e "\${RED}✗\${NC} Failed to remove: $branch"
fi
EOF
done
cat >> "$CLEANUP_SCRIPT" << 'EOF'
echo ""
echo "Cleanup complete!"
echo ""
echo "Remaining worktrees:"
git worktree list
EOF
chmod +x "$CLEANUP_SCRIPT"
print_success "Generated cleanup script: $CLEANUP_SCRIPT"
print_info "Run with: ./$CLEANUP_SCRIPT"
}
# ============================================================================
# Main Execution
# ============================================================================
main() {
print_header "Git Worktree Batch Setup"
# Phase 0: Prerequisites
check_prerequisites
validate_branches
check_directory_conflicts
# Confirm before proceeding
echo ""
read -p "Create ${#BRANCHES[@]} worktrees? (yes/no): " -r
if [[ ! $REPLY =~ ^[Yy]es$ ]]; then
print_info "Aborted by user"
exit 0
fi
# Phase 1: Create worktrees
create_worktrees
# Phase 2: Setup development environments
detect_package_manager
install_dependencies
# Phase 3: Summary
print_final_summary
print_success "Batch setup complete!"
}
# Run main function
main "$@"

View File

@@ -0,0 +1,382 @@
#!/bin/bash
# Git Worktree Setup Script
# Generated by git-worktree-setup skill
#
# This script automates the creation of a git worktree with development environment setup.
#
# Usage:
# ./worktree-setup.sh <branch-name> [worktree-path] [--no-install]
set -euo pipefail
# ============================================================================
# Configuration
# ============================================================================
BRANCH_NAME="${1:-}"
WORKTREE_PATH="${2:-}"
SKIP_INSTALL=false
# Parse flags
for arg in "$@"; do
case $arg in
--no-install)
SKIP_INSTALL=true
shift
;;
esac
done
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# ============================================================================
# Helper Functions
# ============================================================================
print_success() {
echo -e "${GREEN}${NC} $1"
}
print_error() {
echo -e "${RED}${NC} $1" >&2
}
print_warning() {
echo -e "${YELLOW}${NC} $1"
}
print_info() {
echo -e "${BLUE}${NC} $1"
}
print_header() {
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "$1"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
}
# ============================================================================
# Prerequisite Checks
# ============================================================================
check_prerequisites() {
print_header "Checking Prerequisites"
# Check if in git repository
if ! git rev-parse --is-inside-work-tree &>/dev/null; then
print_error "Not in a git repository"
exit 1
fi
print_success "Git repository detected"
# Get repository info
REPO_NAME=$(basename "$(git rev-parse --show-toplevel)")
REPO_ROOT=$(git rev-parse --show-toplevel)
CURRENT_BRANCH=$(git branch --show-current)
print_info "Repository: $REPO_NAME"
print_info "Current branch: $CURRENT_BRANCH"
# Check for branch name
if [ -z "$BRANCH_NAME" ]; then
print_error "Branch name required"
echo "Usage: $0 <branch-name> [worktree-path] [--no-install]"
exit 1
fi
# Set default worktree path if not provided
if [ -z "$WORKTREE_PATH" ]; then
WORKTREE_PATH="$(dirname "$REPO_ROOT")/$REPO_NAME-$BRANCH_NAME"
fi
print_info "Target branch: $BRANCH_NAME"
print_info "Worktree path: $WORKTREE_PATH"
}
check_working_directory() {
# Check for uncommitted changes
if [ -n "$(git status --porcelain)" ]; then
print_warning "You have uncommitted changes in current worktree"
git status --short
echo ""
read -p "Continue anyway? (yes/no): " -r
if [[ ! $REPLY =~ ^[Yy]es$ ]]; then
print_info "Aborted by user"
exit 0
fi
else
print_success "Working directory is clean"
fi
}
check_branch_status() {
# Check if branch exists
if git show-ref --verify "refs/heads/$BRANCH_NAME" &>/dev/null; then
BRANCH_TYPE="existing"
print_info "Branch exists: $BRANCH_NAME"
else
BRANCH_TYPE="new"
print_info "Will create new branch: $BRANCH_NAME"
# Check if exists on remote
if git show-ref --verify "refs/remotes/origin/$BRANCH_NAME" &>/dev/null; then
print_info "Branch exists on remote, will track it"
BRANCH_TYPE="remote"
fi
fi
}
check_directory_conflict() {
if [ -d "$WORKTREE_PATH" ]; then
print_error "Directory already exists: $WORKTREE_PATH"
echo ""
read -p "Remove and continue? (yes/no): " -r
if [[ $REPLY =~ ^[Yy]es$ ]]; then
rm -rf "$WORKTREE_PATH"
print_success "Removed existing directory"
else
print_info "Aborted by user"
exit 0
fi
else
print_success "Target directory available"
fi
}
# ============================================================================
# Worktree Creation
# ============================================================================
create_worktree() {
print_header "Creating Worktree"
case $BRANCH_TYPE in
new)
print_info "Creating new branch: $BRANCH_NAME"
if git worktree add "$WORKTREE_PATH" -b "$BRANCH_NAME"; then
print_success "Worktree created with new branch"
else
print_error "Failed to create worktree"
exit 1
fi
;;
existing)
print_info "Checking out existing branch: $BRANCH_NAME"
if git worktree add "$WORKTREE_PATH" "$BRANCH_NAME"; then
print_success "Worktree created from existing branch"
else
print_error "Failed to create worktree"
exit 1
fi
;;
remote)
print_info "Tracking remote branch: origin/$BRANCH_NAME"
if git worktree add "$WORKTREE_PATH" -b "$BRANCH_NAME" --track "origin/$BRANCH_NAME"; then
print_success "Worktree created tracking remote branch"
else
print_error "Failed to create worktree"
exit 1
fi
;;
esac
}
verify_worktree() {
print_header "Verifying Worktree"
# Check if worktree appears in list
if git worktree list | grep -q "$WORKTREE_PATH"; then
print_success "Worktree appears in git worktree list"
else
print_error "Worktree not in git worktree list"
exit 1
fi
# Check if directory exists
if [ -d "$WORKTREE_PATH" ]; then
print_success "Worktree directory exists"
else
print_error "Worktree directory not found"
exit 1
fi
# Check if .git file exists
if [ -f "$WORKTREE_PATH/.git" ]; then
print_success "Git metadata configured"
else
print_error "Missing .git file in worktree"
exit 1
fi
# Check if has files
if [ -n "$(ls -A "$WORKTREE_PATH")" ]; then
print_success "Worktree populated with files"
else
print_error "Worktree directory is empty"
exit 1
fi
}
# ============================================================================
# Development Environment Setup
# ============================================================================
detect_package_manager() {
cd "$WORKTREE_PATH"
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"
elif [ -f "package.json" ]; then
PKG_MANAGER="npm"
INSTALL_CMD="npm install"
else
PKG_MANAGER="none"
INSTALL_CMD=""
fi
if [ "$PKG_MANAGER" != "none" ]; then
print_info "Detected package manager: $PKG_MANAGER"
fi
}
install_dependencies() {
if [ "$SKIP_INSTALL" = true ]; then
print_info "Skipping dependency installation (--no-install flag)"
return 0
fi
if [ "$PKG_MANAGER" = "none" ]; then
print_info "No package.json found, skipping dependency installation"
return 0
fi
print_header "Installing Dependencies"
cd "$WORKTREE_PATH"
print_info "Running: $INSTALL_CMD"
if $INSTALL_CMD; then
print_success "Dependencies installed successfully"
else
print_warning "Dependency installation failed"
print_info "You can manually install later with: cd $WORKTREE_PATH && $INSTALL_CMD"
return 1
fi
}
copy_environment_files() {
if [ "$SKIP_INSTALL" = true ]; then
return 0
fi
if [ -f "$REPO_ROOT/.env" ]; then
print_info "Found .env file in repository root"
read -p "Copy .env to worktree? (yes/no): " -r
if [[ $REPLY =~ ^[Yy]es$ ]]; then
cp "$REPO_ROOT/.env" "$WORKTREE_PATH/.env"
print_success "Copied .env file"
fi
fi
# Copy other common env files
for env_file in .env.local .env.development .env.test; do
if [ -f "$REPO_ROOT/$env_file" ]; then
read -p "Copy $env_file to worktree? (yes/no): " -r
if [[ $REPLY =~ ^[Yy]es$ ]]; then
cp "$REPO_ROOT/$env_file" "$WORKTREE_PATH/$env_file"
print_success "Copied $env_file"
fi
fi
done
}
# ============================================================================
# Summary and Next Steps
# ============================================================================
print_summary() {
print_header "Worktree Created Successfully"
echo "Location: $WORKTREE_PATH"
echo "Branch: $BRANCH_NAME ($BRANCH_TYPE)"
if [ "$PKG_MANAGER" != "none" ] && [ "$SKIP_INSTALL" = false ]; then
echo "Dev Setup: ✓ Complete ($PKG_MANAGER)"
else
echo "Dev Setup: ⊘ Skipped"
fi
echo ""
print_header "Next Steps"
echo "1. Navigate to worktree:"
echo " ${BLUE}cd $WORKTREE_PATH${NC}"
echo ""
echo "2. Start Claude Code:"
echo " ${BLUE}claude${NC}"
echo ""
echo "3. Begin development on $BRANCH_NAME"
echo ""
print_header "All Worktrees"
git worktree list
echo ""
print_header "Quick Reference"
echo "List worktrees: git worktree list"
echo "Remove worktree: git worktree remove $WORKTREE_PATH"
echo "Navigate: cd $WORKTREE_PATH"
echo "Return to main: cd $REPO_ROOT"
echo ""
}
# ============================================================================
# Main Execution
# ============================================================================
main() {
print_header "Git Worktree Setup"
# Phase 0: Prerequisites
check_prerequisites
check_working_directory
check_branch_status
check_directory_conflict
# Phase 1: Create worktree
create_worktree
verify_worktree
# Phase 2: Setup development environment
detect_package_manager
install_dependencies
copy_environment_files
# Phase 3: Summary
print_summary
print_success "Setup complete!"
}
# Run main function
main "$@"