---
description: 'Manage git worktrees for experimental refactoring and architecture changes'
argument-hint: '[--merge|--list|--clear]'
allowed-tools:
  - 'Bash'
  - 'Glob'
  - 'Read'
  - 'Write'
  - 'Edit'
plan-mode: false
---

# Worktree Management Command

Manage git worktrees for isolated experimental work (refactoring, architecture changes, etc.) without affecting the main working directory.

## Usage

```bash
# Interactive mode - choose operation
/worktree

# Merge changes from latest active worktree
/worktree --merge

# List all worktrees and their purposes
/worktree --list

# Remove all worktrees to clean up repository
/worktree --clear
```

## What This Command Does

**Worktrees** are isolated working directories that share the same git repository. They enable:

- Experimental refactoring without affecting main branch
- Architecture changes in isolation
- Safe testing of breaking changes
- Clean separation of concurrent work

**Common workflow:**

1. Agent creates worktree via subagent (e.g., `/architect:clean`)
2. Experimental changes happen in `.worktree/{name}-{timestamp}/`
3. User reviews changes in worktree
4. User runs `/worktree --merge` to integrate successful changes
5. User runs `/worktree --clear` to remove temporary worktrees

## Phase 0: Parse Arguments

Parse command-line arguments to determine operation mode.

**Argument patterns:**

- `--merge` - Merge changes from latest active worktree
- `--list` - List all worktrees and their purposes
- `--clear` - Remove all worktrees
- No arguments - Interactive mode (present 1, 2, 3 options)

**Implementation:**

```bash
# Parse arguments from user input
MERGE_FLAG=false
LIST_FLAG=false
CLEAR_FLAG=false

if [[ "$@" == *"--merge"* ]]; then
  MERGE_FLAG=true
elif [[ "$@" == *"--list"* ]]; then
  LIST_FLAG=true
elif [[ "$@" == *"--clear"* ]]; then
  CLEAR_FLAG=true
fi
```

## Phase 1: Locate Worktrees

Find all worktrees in the `.worktree/` directory.

**Worktree directory structure:**

```text
.worktree/
├── clean-20251122-213602/          # Clean Architecture refactoring
├── installer-modules-20251122-214644/  # Module-based installer refactoring
└── performance-20251123-100000/    # Performance optimization
```

**Detection strategy:**

```bash
# Find all worktree directories
WORKTREES=($(find .worktree -maxdepth 1 -type d -not -name '.worktree' 2>/dev/null | sort -r))

if [ ${#WORKTREES[@]} -eq 0 ]; then
  echo "ℹ️  No worktrees found"
  exit 0
fi
```

**Extract worktree metadata:**

For each worktree directory:

1. Parse name and timestamp from directory name (e.g., `clean-20251122-213602`)
2. Check for `PROGRESS.md` or similar documentation files
3. Count source files (exclude documentation)
4. Determine last modification time

## Phase 2: Interactive Mode (No Arguments)

When no arguments are provided, present options to the user.

**Present menu:**

```text
Worktree Management

Found 2 active worktrees:
  1. installer-modules-20251122-214644 (most recent)
  2. clean-20251122-213602

What would you like to do?

1. Merge latest worktree (installer-modules-20251122-214644)
2. List all worktrees with details
3. Clear all worktrees

Enter choice (1-3):
```

**User selection:**

- Choice 1: Set `MERGE_FLAG=true`, proceed to Phase 3
- Choice 2: Set `LIST_FLAG=true`, proceed to Phase 4
- Choice 3: Set `CLEAR_FLAG=true`, proceed to Phase 5

## Phase 3: Merge Latest Worktree (`--merge`)

Merge changes from the most recent worktree into the main working directory.

### Step 1: Identify Latest Worktree

**Strategy:** Use directory modification time or parse timestamp from directory name.

```bash
# Get latest worktree by timestamp in directory name
LATEST_WORKTREE=$(find .worktree -maxdepth 1 -type d -not -name '.worktree' | sort -r | head -1)

if [ -z "$LATEST_WORKTREE" ]; then
  echo "❌ No worktrees found to merge"
  exit 1
fi

echo "ℹ️  Merging from: $LATEST_WORKTREE"
```

### Step 2: Identify Source Files to Merge

**Include:**

- `src/**/*.ts` - Source code files
- `src/**/*.js` - JavaScript files
- `tests/**/*.test.ts` - Test files
- `tasks/**/*.yml` - Task definitions
- New directories created in worktree

**Exclude (do NOT copy):**

- `PROGRESS.md` - Worktree-specific documentation
- `PATTERN-GUIDE.md` - Temporary reference files
- `IMPLEMENTATION-SUMMARY.md` - Worktree-specific notes
- `REFACTORING-PLAN.md` - Planning documents
- `.clean-*.md` - Analysis reports
- `*.local.md` - Local documentation files
- `.logs/**` - Log files
- `.worktree/**` - Nested worktrees
- `node_modules/**` - Dependencies

**Detection:**

```bash
# Find source files in worktree (exclude documentation and temporary files)
cd "$LATEST_WORKTREE"

# Find new or modified source directories
SRC_DIRS=($(find src -type d -mindepth 1 -maxdepth 2 2>/dev/null | grep -v '.logs' | grep -v '.worktree'))

# Find new or modified TypeScript source files
SRC_FILES=($(find src tests tasks -name "*.ts" -o -name "*.js" -o -name "*.yml" 2>/dev/null | grep -v '.test.ts'))

cd - > /dev/null
```

### Step 3: Copy Source Files to Main Branch

**For new directories:**

```bash
for DIR in "${SRC_DIRS[@]}"; do
  if [ ! -d "$DIR" ]; then
    echo "📁 Creating new directory: $DIR"
    mkdir -p "$DIR"
  fi
done
```

**For source files:**

```bash
# Copy source files from worktree to main branch
for FILE in "${SRC_FILES[@]}"; do
  SOURCE="$LATEST_WORKTREE/$FILE"
  DEST="$FILE"

  if [ -f "$SOURCE" ]; then
    # Create parent directory if needed
    mkdir -p "$(dirname "$DEST")"

    # Copy file
    cp "$SOURCE" "$DEST"
    echo "✓ Copied: $FILE"
  fi
done
```

### Step 4: Handle File Replacements

**Strategy from recent session:**

- `src/installers/claude.ts` was replaced with a simple re-export (694 lines → 20 lines)
- New directories `src/installers/base/` and `src/installers/claude/` were added
- Backward compatibility maintained via re-exports

**Detect replaced files:**

```bash
# Compare file sizes to detect major changes
for FILE in "${SRC_FILES[@]}"; do
  SOURCE="$LATEST_WORKTREE/$FILE"
  DEST="$FILE"

  if [ -f "$SOURCE" ] && [ -f "$DEST" ]; then
    SOURCE_SIZE=$(wc -l < "$SOURCE")
    DEST_SIZE=$(wc -l < "$DEST")

    DIFF=$((DEST_SIZE - SOURCE_SIZE))

    if [ ${DIFF#-} -gt 100 ]; then
      echo "⚠️  Significant change: $FILE ($DEST_SIZE → $SOURCE_SIZE lines)"
    fi
  fi
done
```

### Step 5: Show Git Status

**Display changes:**

```bash
echo ""
echo "Git status after merge:"
git status --short

echo ""
echo "Summary:"
git status --short | wc -l | xargs echo "  Modified/new files:"
git diff --cached --stat 2>/dev/null || echo "  (no staged changes)"
```

**Suggest next steps:**

```text
Next steps:
1. Review changes: git diff
2. Run tests: bun test
3. Commit changes: git add . && git commit -m "refactor: merge worktree changes"
4. Clean up worktree: /worktree --clear
```

## Phase 4: List Worktrees (`--list`)

Display all worktrees with their purposes and metadata.

### Step 1: Parse Worktree Information

For each worktree:

1. **Name and timestamp**: Parse from directory name (e.g., `installer-modules-20251122-214644`)
2. **Purpose**: Read from `PROGRESS.md`, first heading, or infer from name
3. **File count**: Count source files (exclude documentation)
4. **Last modified**: Get directory modification time
5. **Size**: Calculate total size of source files

**Implementation:**

```bash
for WORKTREE in "${WORKTREES[@]}"; do
  BASENAME=$(basename "$WORKTREE")

  # Parse timestamp from name (YYYYMMDD-HHMMSS)
  if [[ "$BASENAME" =~ ([0-9]{8})-([0-9]{6}) ]]; then
    DATE="${BASH_REMATCH[1]}"
    TIME="${BASH_REMATCH[2]}"
    TIMESTAMP="${DATE:0:4}-${DATE:4:2}-${DATE:6:2} ${TIME:0:2}:${TIME:2:2}:${TIME:4:2}"
  fi

  # Extract purpose from directory name or PROGRESS.md
  if [ -f "$WORKTREE/PROGRESS.md" ]; then
    PURPOSE=$(head -1 "$WORKTREE/PROGRESS.md" | sed 's/^# //')
  else
    # Infer from directory name
    PURPOSE=$(echo "$BASENAME" | sed 's/-[0-9]*-[0-9]*$//' | sed 's/-/ /g' | sed 's/\b\(.\)/\u\1/g')
  fi

  # Count source files
  FILE_COUNT=$(find "$WORKTREE/src" -name "*.ts" -o -name "*.js" 2>/dev/null | wc -l)

  # Get size
  SIZE=$(du -sh "$WORKTREE" | cut -f1)

  echo "📂 $BASENAME"
  echo "   Purpose: $PURPOSE"
  echo "   Created: $TIMESTAMP"
  echo "   Files: $FILE_COUNT source files"
  echo "   Size: $SIZE"
  echo ""
done
```

### Step 2: Identify Latest Worktree

**Highlight most recent:**

```bash
LATEST=$(find .worktree -maxdepth 1 -type d -not -name '.worktree' | sort -r | head -1)
LATEST_BASENAME=$(basename "$LATEST")

echo "Latest worktree: $LATEST_BASENAME (ready for --merge)"
```

### Step 3: Show Integration Status

**Check if worktree has been merged:**

```bash
# Compare git status - if worktree files exist in main branch, it's been merged
for WORKTREE in "${WORKTREES[@]}"; do
  BASENAME=$(basename "$WORKTREE")

  # Check for marker files from this worktree
  MARKER_FILE=$(find "$WORKTREE/src" -name "*.ts" -type f | head -1)

  if [ -n "$MARKER_FILE" ]; then
    REL_PATH=$(echo "$MARKER_FILE" | sed "s|$WORKTREE/||")

    if [ -f "$REL_PATH" ]; then
      # Compare file contents
      if diff -q "$MARKER_FILE" "$REL_PATH" > /dev/null 2>&1; then
        echo "✓ Merged: $BASENAME"
      else
        echo "⚠️  Partial merge: $BASENAME (files differ)"
      fi
    else
      echo "❌ Not merged: $BASENAME"
    fi
  fi
done
```

## Phase 5: Clear Worktrees (`--clear`)

Remove all worktrees to clean up the repository.

### Step 1: List Worktrees to Remove

**Show what will be deleted:**

```bash
echo "The following worktrees will be removed:"
echo ""

for WORKTREE in "${WORKTREES[@]}"; do
  BASENAME=$(basename "$WORKTREE")
  SIZE=$(du -sh "$WORKTREE" | cut -f1)
  echo "  - $BASENAME ($SIZE)"
done

echo ""
TOTAL_SIZE=$(du -sh .worktree | cut -f1)
echo "Total size: $TOTAL_SIZE"
```

### Step 2: Confirm with User

**Safety check:**

```text
⚠️  WARNING: This will permanently delete all worktrees.

Are you sure you want to continue? (y/N):
```

**User confirmation required:**

- `y` or `yes` - Proceed with deletion
- Any other input - Cancel operation

### Step 3: Remove Worktrees

**Delete directories:**

```bash
for WORKTREE in "${WORKTREES[@]}"; do
  BASENAME=$(basename "$WORKTREE")

  echo "Removing: $BASENAME"
  rm -rf "$WORKTREE"

  if [ ! -d "$WORKTREE" ]; then
    echo "✓ Deleted: $BASENAME"
  else
    echo "❌ Failed to delete: $BASENAME"
  fi
done
```

**Clean up parent directory:**

```bash
# Remove .worktree directory if empty
if [ -d ".worktree" ] && [ -z "$(ls -A .worktree)" ]; then
  rmdir .worktree
  echo "✓ Removed empty .worktree directory"
fi
```

### Step 4: Verify Cleanup

**Check remaining worktrees:**

```bash
REMAINING=$(find .worktree -maxdepth 1 -type d -not -name '.worktree' 2>/dev/null | wc -l)

if [ "$REMAINING" -eq 0 ]; then
  echo ""
  echo "✅ All worktrees removed successfully"
else
  echo ""
  echo "⚠️  $REMAINING worktree(s) remain (may require manual removal)"
fi
```

## Security Considerations

**File copy safety:**

- Only copy source files from `src/`, `tests/`, `tasks/` directories
- Exclude documentation files (\*.md) to prevent overwriting project docs
- Exclude local files (\*.local.md) which may contain sensitive data
- Exclude log files (.logs/\*\*) which may contain credentials

**Git safety:**

- Never force push from worktrees
- Require user review before merging changes
- Show git diff before committing merged changes
- Preserve git history (no history rewriting)

**Cleanup safety:**

- Require explicit confirmation before deleting worktrees
- Show total size before deletion
- Verify deletion completed successfully
- Handle nested worktrees safely (should not exist)

## Common Use Cases

### Use Case 1: Clean Architecture Refactoring

**Workflow:**

1. User runs `/architect:clean src/installers/claude.ts`
2. Subagent creates worktree at `.worktree/clean-{timestamp}/`
3. Refactoring happens in worktree (interfaces, system files, etc.)
4. User reviews changes in worktree
5. User runs `/worktree --merge` to integrate changes
6. User commits merged changes
7. User runs `/worktree --clear` to clean up

**Files merged:**

- `src/installers/base/` (new directory)
- `src/installers/claude/` (new directory)
- `src/installers/claude.ts` (replaced with re-export)

**Files excluded:**

- `PROGRESS.md` (worktree-specific documentation)
- `.clean-claude-installer.md` (analysis report)
- `PATTERN-GUIDE.md` (temporary reference)

### Use Case 2: Multiple Concurrent Experiments

**Workflow:**

1. User runs `/architect:clean file1.ts` → worktree A
2. User runs `/architect:clean file2.ts` → worktree B
3. User runs `/worktree --list` to see both worktrees
4. User selects which worktree to merge first
5. User runs `/worktree --merge` for worktree A
6. User commits changes from worktree A
7. User runs `/worktree --merge` for worktree B (now latest)
8. User commits changes from worktree B
9. User runs `/worktree --clear` to remove both

### Use Case 3: Abandoned Experiment Cleanup

**Workflow:**

1. User runs `/architect:clean` → creates worktree
2. Refactoring doesn't work as expected
3. User decides not to merge changes
4. User runs `/worktree --clear` to remove worktree
5. Main branch unaffected

## Integration with Other Commands

**With `/architect:clean`:**

- `/architect:clean` creates worktrees automatically
- User reviews changes in worktree
- `/worktree --merge` integrates successful refactorings

**With `/commit`:**

- After `/worktree --merge`, use `/commit` to create conventional commit
- Commit message should reference worktree purpose (e.g., "refactor: clean architecture for installers")

**With `/cover`:**

- After merging, run `/cover --compare` to verify coverage improved
- Compare before/after coverage reports

**With Task Master:**

- Mark task as complete after successful worktree merge
- Document refactoring in task notes

## Troubleshooting

### Merge Conflicts

**Issue:** Files in worktree conflict with changes in main branch.

**Solution:**

1. Run `/worktree --list` to see which files changed
2. Manually resolve conflicts using git
3. Commit resolved changes

### Incomplete Merge

**Issue:** Some files from worktree not copied to main branch.

**Solution:**

1. Check `.gitignore` - ensure source files not ignored
2. Verify file permissions
3. Manually copy missing files
4. Re-run `/worktree --merge` after fixing issues

### Worktree Not Found

**Issue:** `/worktree --merge` says "No worktrees found".

**Solution:**

1. Check `.worktree/` directory exists
2. Verify worktree subdirectories present
3. Use `/worktree --list` to see available worktrees

### Cannot Delete Worktree

**Issue:** `/worktree --clear` fails to remove worktree.

**Solution:**

1. Check file permissions
2. Close any open files in worktree (IDE, terminal)
3. Manually remove: `rm -rf .worktree/{name}`
4. Check for git locks

## Examples

**Example 1: Merge latest worktree**

```bash
# User runs command
/worktree --merge

# Output:
ℹ️  Merging from: .worktree/installer-modules-20251122-214644
📁 Creating new directory: src/installers/base
📁 Creating new directory: src/installers/claude
✓ Copied: src/installers/base/interfaces.ts
✓ Copied: src/installers/base/command.system.ts
✓ Copied: src/installers/base/filesystem.system.ts
✓ Copied: src/installers/base/index.ts
✓ Copied: src/installers/claude/types.ts
✓ Copied: src/installers/claude/config.ts
✓ Copied: src/installers/claude/installer.ts
✓ Copied: src/installers/claude/index.ts
⚠️  Significant change: src/installers/claude.ts (694 → 20 lines)

Git status after merge:
 M src/installers/claude.ts
?? src/installers/base/
?? src/installers/claude/

Summary:
  Modified/new files: 3

Next steps:
1. Review changes: git diff
2. Run tests: bun test
3. Commit changes: git add . && git commit -m "refactor: merge worktree changes"
4. Clean up worktree: /worktree --clear
```

**Example 2: List worktrees**

```bash
# User runs command
/worktree --list

# Output:
📂 installer-modules-20251122-214644
   Purpose: Installer Modules
   Created: 2025-11-22 21:46:44
   Files: 12 source files
   Size: 156K

📂 clean-20251122-213602
   Purpose: Clean Architecture Refactoring
   Created: 2025-11-22 21:36:02
   Files: 8 source files
   Size: 98K

Latest worktree: installer-modules-20251122-214644 (ready for --merge)

✓ Merged: installer-modules-20251122-214644
❌ Not merged: clean-20251122-213602
```

**Example 3: Clear all worktrees**

```bash
# User runs command
/worktree --clear

# Output:
The following worktrees will be removed:

  - installer-modules-20251122-214644 (156K)
  - clean-20251122-213602 (98K)

Total size: 254K

⚠️  WARNING: This will permanently delete all worktrees.

Are you sure you want to continue? (y/N): y

Removing: installer-modules-20251122-214644
✓ Deleted: installer-modules-20251122-214644
Removing: clean-20251122-213602
✓ Deleted: clean-20251122-213602
✓ Removed empty .worktree directory

✅ All worktrees removed successfully
```

**Example 4: Interactive mode**

```bash
# User runs command
/worktree

# Output:
Worktree Management

Found 2 active worktrees:
  1. installer-modules-20251122-214644 (most recent)
  2. clean-20251122-213602

What would you like to do?

1. Merge latest worktree (installer-modules-20251122-214644)
2. List all worktrees with details
3. Clear all worktrees

Enter choice (1-3): 1

# Proceeds to merge workflow...
```

## Implementation Notes

**Performance:**

- Use `find` with `-maxdepth` to avoid deep directory traversal
- Cache worktree list in Phase 1, reuse in other phases
- Use `diff -q` for fast file comparison
- Avoid reading large files unnecessarily

**Compatibility:**

- Works with git 2.30+
- Compatible with macOS, Linux, Windows (Git Bash)
- No external dependencies beyond git and standard Unix tools

**Testing:**

- Test with multiple worktrees
- Test with empty worktree directory
- Test with nested directories
- Test with special characters in filenames
- Test merge conflicts
- Test deletion failures

## Related Documentation

- [Clean Architecture Guide](../guides/agents.clean.arch.md)
- [GoTask Usage Guide](../guides/agents.gotask.md)
- [Commit Command](/commit)
- [Coverage Command](/cover)
