# Refactor Cleaner Agent

> **Purpose:** Detect and safely remove dead code, unused dependencies, and technical debt.

---

## When to Use

This agent is automatically invoked when:
- Codebase has grown significantly
- Major features are removed
- Dependency audit is needed
- The `/refactor-clean` command is used

You can also invoke it manually with `/refactor-clean`.

---

## Capabilities

### 1. Dead Code Detection

#### Python
```bash
# Using vulture for unused code detection
vulture src/ --min-confidence 80

# Using coverage to find uncovered code
pytest --cov=src --cov-report=term-missing

# Find unused imports
ruff check --select=F401 src/
```

#### TypeScript/JavaScript
```bash
# Using ts-prune for unused exports
npx ts-prune

# Using knip for comprehensive dead code analysis
npx knip

# ESLint for unused variables
npx eslint --rule 'no-unused-vars: error' src/
```

### 2. Unused Dependency Detection

#### Python
```bash
# Check for unused dependencies
pip-audit --requirements requirements.txt

# Using pipreqs to find actually used packages
pipreqs --print src/
```

#### JavaScript/TypeScript
```bash
# Using depcheck
npx depcheck

# Using knip for dependencies
npx knip --dependencies
```

### 3. Safe Removal Process

```markdown
## Dead Code Removal Report

### Phase 1: Detection
Found 23 potentially unused items:
- 8 unused functions
- 5 unused classes
- 7 unused imports
- 3 unused dependencies

### Phase 2: Verification
Each item verified against:
- [ ] Test coverage data
- [ ] Git blame (last modified)
- [ ] Import graph analysis
- [ ] Dynamic usage patterns

### Phase 3: Categorization

| Category | Count | Risk |
|----------|-------|------|
| Safe to Remove | 15 | Low |
| Needs Review | 5 | Medium |
| Keep (false positive) | 3 | N/A |

### Phase 4: Removal Plan
```

---

## Analysis Reports

### Unused Functions
```markdown
## Unused Functions

| Function | File | Last Modified | Confidence |
|----------|------|---------------|------------|
| `parse_legacy_format()` | `src/utils.py` | 6 months ago | 95% |
| `deprecated_handler()` | `src/api.py` | 1 year ago | 99% |
```

### Unused Dependencies
```markdown
## Unused Dependencies

| Package | Last Used | Size | Recommendation |
|---------|-----------|------|----------------|
| `lodash` | Never imported | 1.2MB | Remove |
| `moment` | Only in tests | 500KB | Move to devDeps |
```

### Circular Dependencies
```markdown
## Circular Dependencies

Cycle 1:
  src/services/user.py → src/services/auth.py → src/services/user.py

Recommendation: Extract shared logic to src/services/common.py
```

---

## Removal Strategies

### Safe Removal (Automated)
- Unused imports
- Unused local variables
- Commented-out code (> 6 months)

### Review Required (Manual)
- Unused exported functions
- Unused classes
- Unused dependencies

### Keep (False Positives)
- Dynamic imports
- Reflection-based usage
- Test-only utilities
- CLI entry points

---

## Integration with Other Agents

- **Code Reviewer:** Flags dead code during reviews
- **Build Error Resolver:** Fixes issues after removal
- **Planner:** Includes cleanup in feature plans

---

## Commands

| Command | Description |
|---------|-------------|
| `/refactor-clean` | Full dead code analysis |
| `/refactor-clean --deps` | Dependency audit only |
| `/refactor-clean --imports` | Unused imports only |
| `/refactor-clean --apply` | Apply safe removals |

---

## Configuration

```json
{
  "refactorCleaner": {
    "minConfidence": 80,
    "excludePaths": ["tests/", "scripts/", "migrations/"],
    "ignoredPatterns": ["*_handler", "*_callback"],
    "autoRemove": ["imports", "variables"],
    "requireReview": ["functions", "classes", "dependencies"]
  }
}
```

---

## Best Practices

1. **Analyze Before Remove** - Always run detection first
2. **Verify Test Coverage** - Low coverage = higher false positive risk
3. **Check Git History** - Recently modified = might be in use
4. **Remove in Stages** - Don't bulk delete everything at once
5. **Run Tests After** - Verify nothing broke
6. **Commit Separately** - Dead code removal = separate commit

---

## Example Session

```
$ /refactor-clean

🔍 Analyzing codebase...

Dead Code Analysis Complete
===========================

Found 18 unused items:

Unused Imports (8) - Safe to remove
  ✓ src/utils.py: import os (unused)
  ✓ src/api.py: from typing import Dict (unused)
  ...

Unused Functions (5) - Review required
  ⚠ src/helpers.py: format_legacy_date() - 90% confidence
  ⚠ src/parsers.py: parse_v1_format() - 85% confidence
  ...

Unused Dependencies (2) - Review required
  ⚠ moment: Not imported anywhere
  ⚠ lodash: Only in removed file

Apply safe removals? [y/N]: y
✓ Removed 8 unused imports

Review 7 items manually? [y/N]: y
[Opens interactive review...]
```
