# Worktree and Branch Cleanup

## Clean Up Worktree

```bash
# Repair cross-platform worktree paths before cleanup (WSL ↔ Windows)
detect_platform
repair_worktree_paths "$(git rev-parse --git-common-dir 2>/dev/null || echo '.bare')"

# Find worktree for this branch (use --porcelain for reliable parsing)
WORKTREE_PATH=$(git worktree list --porcelain | grep -B2 "branch refs/heads/$BRANCH" | grep "^worktree " | sed 's/^worktree //')

if [ -n "$WORKTREE_PATH" ] && [ -d "$WORKTREE_PATH" ]; then
  echo "Removing worktree: $WORKTREE_PATH"

  # Make sure we're not in the worktree directory
  cd "$GF_DEVELOP_PATH" 2>/dev/null || cd "$(git rev-parse --show-toplevel)"

  git worktree remove "$WORKTREE_PATH" --force 2>/dev/null || {
    rm -rf "$WORKTREE_PATH"
  }

  git worktree prune
  echo "✅ Worktree removed"
fi
```

## Delete Remote and Local Branches

```bash
# Check if remote branch still exists
REMOTE_EXISTS=$(git branch -r --list "origin/$BRANCH")

if [ -n "$REMOTE_EXISTS" ]; then
  echo "Deleting remote branch: $BRANCH"
  git push origin --delete "$BRANCH" 2>/dev/null || {
    echo "⚠️ Could not delete remote branch (may already be deleted by PR)"
  }
fi

# Delete local branch
git branch -D "$BRANCH" 2>/dev/null || echo "Local branch already deleted"
```

## Archive Plan

```bash
PLAN_FILE=$(ls .claude/gitflow/plans/*${BRANCH_NAME}*.md 2>/dev/null | head -1)

if [ -f "$PLAN_FILE" ]; then
  ARCHIVE_NAME="${PLAN_FILE%.md}_DONE_$(date +%Y%m%d-%H%M%S).md"
  mv "$PLAN_FILE" "$ARCHIVE_NAME"
  echo "✅ Plan archived: $ARCHIVE_NAME"
fi
```
