---
name: cleanup
description: Audit and remove orphan worktrees and branches
---

# Phase: CLEANUP - Maintenance

## YOUR TASK:

Audit worktrees and branches, remove orphaned/stale items.

**IMPORTANT:** Must be run from main or develop branch.

---

## PRE-CHECK:

```bash
# Load GitFlow config (sets GF_* variables)
read_gitflow_config || { echo "❌ Run /gitflow init first."; exit 1; }

CURRENT=$(git rev-parse --abbrev-ref HEAD)

[[ "$CURRENT" != "$GF_MAIN_BRANCH" ]] && [[ "$CURRENT" != "$GF_DEVELOP_BRANCH" ]] && {
  echo "❌ Cleanup must be run from $GF_MAIN_BRANCH or $GF_DEVELOP_BRANCH"
  echo "   Current branch: $CURRENT"
  echo "→ Run: git checkout $GF_DEVELOP_BRANCH"
  STOP
}
```

---

## EXECUTION:

### 1. Audit Worktrees

```bash
echo "Scanning worktrees..."

mkdir -p .claude/gitflow/cache
git worktree list > .claude/gitflow/cache/worktrees.txt

ORPHANED=()
STALE=()
VALID=()

while read -r line; do
  WT_PATH=$(echo "$line" | awk '{print $1}')
  WT_COMMIT=$(echo "$line" | awk '{print $2}')
  WT_BRANCH=$(echo "$line" | awk '{print $3}' | tr -d '[]')

  # Check if path exists
  if [ ! -d "$WT_PATH" ]; then
    ORPHANED+=("$WT_PATH:$WT_BRANCH")
    continue
  fi

  # Check if branch still exists on remote
  REMOTE_EXISTS=$(git branch -r --list "origin/$WT_BRANCH" | wc -l)
  if [ "$REMOTE_EXISTS" -eq 0 ] && [[ "$WT_BRANCH" != "$GF_MAIN_BRANCH" ]] && [[ "$WT_BRANCH" != "$GF_DEVELOP_BRANCH" ]]; then
    STALE+=("$WT_PATH:$WT_BRANCH")
    continue
  fi

  VALID+=("$WT_PATH:$WT_BRANCH")
done < .claude/gitflow/cache/worktrees.txt
```

### 2. Audit Local Branches

```bash
echo "Scanning local branches..."

MERGED_BRANCHES=()
UNMERGED_BRANCHES=()

# Find merged branches
for branch in $(git branch --merged $GF_DEVELOP_BRANCH | grep -v "^\*" | grep -v "$GF_MAIN_BRANCH" | grep -v "$GF_DEVELOP_BRANCH"); do
  # Check if remote exists
  REMOTE_EXISTS=$(git branch -r --list "origin/$branch" | wc -l)
  [ "$REMOTE_EXISTS" -eq 0 ] && MERGED_BRANCHES+=("$branch")
done

# Find branches without remote
for branch in $(git branch | grep -v "^\*" | grep -v "$GF_MAIN_BRANCH" | grep -v "$GF_DEVELOP_BRANCH"); do
  REMOTE_EXISTS=$(git branch -r --list "origin/$branch" | wc -l)
  [ "$REMOTE_EXISTS" -eq 0 ] && {
    MERGED=$(git branch --merged $GF_DEVELOP_BRANCH | grep -c "$branch")
    [ "$MERGED" -eq 0 ] && UNMERGED_BRANCHES+=("$branch")
  }
done
```

### 3. Display Audit Results

```
╔══════════════════════════════════════════════════════════════════╗
║                    CLEANUP AUDIT                                  ║
╠══════════════════════════════════════════════════════════════════╣

## Worktrees

| Status | Count |
|--------|-------|
| Valid | {#VALID} |
| Orphaned | {#ORPHANED} |
| Stale | {#STALE} |

{if ORPHANED}
### Orphaned Worktrees (path missing)
{list with paths}
{endif}

{if STALE}
### Stale Worktrees (remote deleted)
{list with paths and branches}
{endif}

## Local Branches

| Status | Count |
|--------|-------|
| Merged (safe to delete) | {#MERGED_BRANCHES} |
| Unmerged (caution) | {#UNMERGED_BRANCHES} |

{if MERGED_BRANCHES}
### Merged Branches
{list}
{endif}

{if UNMERGED_BRANCHES}
### Unmerged Branches ⚠️
{list}
{endif}

╚══════════════════════════════════════════════════════════════════╝
```

### 4. Cleanup Actions

```yaml
AskUserQuestion:
  header: "Cleanup"
  question: "What do you want to clean?"
  options:
    - label: "All safe items (Recommended)"
      description: "Orphaned worktrees + merged branches"
    - label: "Worktrees only"
      description: "Remove orphaned and stale worktrees"
    - label: "Branches only"
      description: "Delete merged local branches"
    - label: "Nothing (dry run)"
      description: "Just show what would be cleaned"
  multiSelect: false
```

### 5. Execute Cleanup

**Worktrees:**
```bash
# Remove orphaned
for item in "${ORPHANED[@]}"; do
  WT_PATH=$(echo "$item" | cut -d':' -f1)
  git worktree remove "$WT_PATH" --force 2>/dev/null || rm -rf "$WT_PATH"
done

# Prune
git worktree prune

# Remove stale
for item in "${STALE[@]}"; do
  WT_PATH=$(echo "$item" | cut -d':' -f1)
  WT_BRANCH=$(echo "$item" | cut -d':' -f2)

  git worktree remove "$WT_PATH" --force 2>/dev/null || rm -rf "$WT_PATH"
  git branch -D "$WT_BRANCH" 2>/dev/null
done
```

**Branches:**
```bash
# Delete merged branches
for branch in "${MERGED_BRANCHES[@]}"; do
  git branch -d "$branch"
done
```

### 6. Summary

```
╔══════════════════════════════════════════════════════════════════╗
║                    CLEANUP COMPLETE                               ║
╠══════════════════════════════════════════════════════════════════╣
║  Worktrees removed: {count}                                       ║
║  Branches deleted:  {count}                                       ║
╠══════════════════════════════════════════════════════════════════╣
║  Remaining worktrees: {count}                                     ║
║  Remaining branches:  {count}                                     ║
╚══════════════════════════════════════════════════════════════════╝
```

---

## DRY RUN MODE:

```bash
# With --dry-run flag
echo "DRY RUN - No changes will be made"
echo ""
echo "Would remove worktrees:"
for item in "${ORPHANED[@]}" "${STALE[@]}"; do
  echo "  - $item"
done
echo ""
echo "Would delete branches:"
for branch in "${MERGED_BRANCHES[@]}"; do
  echo "  - $branch"
done
```

---

## SUCCESS CRITERIA:

- Audit completed
- Orphaned worktrees removed
- Stale worktrees removed
- Merged branches deleted
- Summary displayed
