---
name: simplify-refactor
description: Review changed code for smells (duplication, oversized files, dead code, complexity), propose focused refactors, and verify with tests. No scope creep.
---

# Simplify & Refactor

Focused code quality pass for Trip Planner. Scans recently changed files for code smells, proposes minimal refactors, and verifies no regressions. Keeps things lean — no speculative abstractions.

**Input:** Optional file paths or git ref (e.g., `HEAD~3`). Defaults to uncommitted changes + last commit.

---

## Phase 1: Identify Scope

### 1.1 Gather Changed Files
Determine which files to review:

```bash
# Uncommitted changes
git diff --name-only
git diff --cached --name-only

# Or changes since ref (if provided)
git diff --name-only {ref}..HEAD
```

Filter to production code only:
- Include: `*.ts`, `*.scss`, `*.html` in `frontend/src/` and `backend/src/`
- Exclude: `*.spec.ts`, `*.test.ts`, `__tests__/`, `node_modules/`, `dist/`

### 1.2 Read Changed Files
Read each changed file. For each, note:
- File path and line count
- What changed (diff context)
- Layer: frontend component / frontend service / backend route / backend service / shared / style

---

## Phase 2: Detect Code Smells

Scan each file against these smell categories. **Only flag clear issues, not style preferences.**

### 2.1 Oversized Files
Flag files exceeding these thresholds:

| File Type | Threshold | Action |
|-----------|-----------|--------|
| Component `.ts` | > 200 lines | Consider extracting child components or utility functions |
| Service `.ts` | > 250 lines | Consider splitting by domain responsibility |
| Template `.html` | > 150 lines | Consider extracting reusable partials |
| Stylesheet `.scss` | > 200 lines | Consider splitting by section with `@use` |
| Route handler `.ts` | > 100 lines | Consider extracting validation or transformation logic |

### 2.2 Duplicated Logic
Detect repeated patterns:
- Same HTTP call pattern in multiple services (extract shared helper)
- Repeated form validation logic across components
- Copy-pasted SCSS blocks (> 5 identical lines)
- Duplicate type definitions across frontend/backend
- Same error handling try/catch pattern (> 3 occurrences)

**Threshold:** Flag only if duplicated 3+ times. Two similar blocks are fine.

### 2.3 Dead Code
Detect:
- Unused imports (imported but never referenced in file)
- Unused private methods (declared but never called within the class)
- Commented-out code blocks (> 3 lines of commented code)
- Empty files or stub-only files with no implementation
- Unused CSS classes (class defined in SCSS but not referenced in template)

### 2.4 Unnecessary Complexity
Detect:
- Deeply nested conditionals (> 3 levels of if/else or ternary)
- Functions with > 5 parameters (consider an options object)
- Mixed concerns in a single method (data fetch + transform + UI update)
- Premature abstractions (generic utility used in exactly one place)
- Observable chains that could be simplified with signals/computed

### 2.5 Convention Violations
Check against `CLAUDE.md` conventions:
- **Angular**: Missing `OnPush`, legacy decorators, constructor injection, `*ngIf`/`*ngFor`
- **Design tokens**: Hardcoded colors, spacing, shadows, font sizes, z-index, border-radius
- **Backend**: Missing error handling on routes, raw SQL instead of Drizzle queries
- **TypeScript**: `any` types, missing return types on public methods

---

## Phase 3: Propose Refactors

### 3.1 Prioritize Findings

Categorize each finding:

| Priority | Meaning | Criteria |
|----------|---------|----------|
| **High** | Bugs or maintainability risk | Dead code masking bugs, duplicated logic diverging, missing error handling |
| **Medium** | Code quality improvement | Oversized files, unnecessary complexity, convention violations |
| **Low** | Minor cleanup | Unused imports, minor formatting, single dead variable |

### 3.2 Present Findings Table

**>>> STOP — APPROVAL REQUIRED <<<**

Present findings to user before making changes:

```
## Refactor Proposals

| # | File | Smell | Priority | Proposed Change |
|---|------|-------|----------|-----------------|
| 1 | ... | ... | High | ... |
| 2 | ... | ... | Medium | ... |

Approve changes? (all / specific numbers / none)
```

**Rules:**
- Each proposal must be specific: exact file, exact issue, exact fix
- No vague "improve code quality" proposals
- No proposals that change behavior or add features
- No proposals that require touching > 3 files (those need their own story)

### 3.3 Verify Test Baseline
Before making any changes, run tests and record baseline:

```bash
# Frontend
cd frontend && npx ng test

# Backend
cd backend && npm test
```

Record: total tests, passing, failing. If any are already failing, note them as pre-existing.

---

## Phase 4: Apply Refactors

### 4.1 Apply Approved Changes Only
For each approved refactor:
1. Make the minimal change described in the proposal
2. Do NOT expand scope beyond what was approved
3. Do NOT "while I'm here" adjacent code
4. Preserve all existing behavior — refactors must be invisible to users

### 4.2 Verify After Each Change
After each refactor (not at the end — after each one):

```bash
cd frontend && npx ng test
cd backend && npm test
```

If tests fail after a specific refactor:
- Revert that change immediately
- Note it as "reverted — caused regression"
- Move to next refactor

### 4.3 Final Verification
After all approved refactors are applied:

```bash
# Full test suite
cd frontend && npx ng test
cd backend && npm test

# Production build
cd frontend && npx ng build
```

All must pass. If total passing tests decreased from baseline, investigate.

---

## Phase 5: Summary Report

Present final report:

```
## Refactor Summary

### Applied
| # | File | Change | Tests |
|---|------|--------|-------|
| 1 | ... | ... | Pass |

### Skipped (user declined)
| # | File | Reason |

### Reverted (caused regression)
| # | File | Reason |

### Test Results
- Before: X tests passing
- After: Y tests passing
- Production build: Pass/Fail
```

---

## Key Constraints

- **No behavior changes.** Refactors must be invisible to end users. If a change could alter behavior, it's not a refactor — it's a feature/fix.
- **No speculative abstractions.** Don't create helpers or utilities "for the future." Only extract when duplication is proven (3+ occurrences).
- **No scope expansion.** Only touch files in the identified scope. Don't wander into adjacent files.
- **Test after each change.** Not at the end — after each individual refactor. Revert immediately on failure.
- **User approves before changes.** Never refactor without presenting proposals and getting approval.
- **Minimal diffs.** The best refactor is the smallest one that solves the problem.
