---
name: code-refactoring
description: >-
  Improves code structure, readability, and maintainability without changing external
  behavior. Use when code smells are detected (duplication, long functions, deep nesting),
  user asks to "clean this up" or "refactor this", or before adding features to messy code.
  NOT for adding features, fixing bugs, or rewriting from scratch.
allowed-tools:
  - Read
  - Glob
  - Grep
  - Bash
---

## Identity & Scope

**Executor:** either
**Model tier:** sonnet
**Scope:** Source code files and associated test files
**Off-limits:** Changing external behavior, modifying public APIs, deleting test coverage
**Hard rules:** No credentials in output. No deleting files. No spending money. Report via structured output.

## Essential Principles

1. **Tests first, refactor second** — Never refactor without a test safety net. Guards against: breaking working code with no way to detect it.
2. **Small steps, frequent verification** — One refactoring at a time, run tests between each. Guards against: compound failures impossible to diagnose.
3. **Extract, don't rewrite** — Pull out methods and classes from existing code. Guards against: new bugs from reimplementing working logic.
4. **Behavior must not change** — Same inputs must produce same outputs. Guards against: shipping "improvements" that break consumers.

## When to Use
- Code duplication detected (same logic in multiple places)
- Functions too long (>40 lines) or deeply nested (>3 levels)
- User asks to "clean this up", "refactor this", or "reduce complexity"
- Preparing messy code for a new feature
- Renaming for clarity after domain understanding shift

## When NOT to Use
- Adding new functionality — implement first, refactor after
- Fixing a bug — use bug-debugging skill; refactoring masks issues
- No tests and you can't add them — refactoring without tests is gambling
- Code is unfamiliar but works — unfamiliar != bad
- Performance optimization — profile first with a dedicated skill

## Rationalizations to Reject

| Shortcut | Why it's wrong |
|----------|----------------|
| "Refactor and add feature in one pass" | Mixing changes makes failures impossible to attribute |
| "Tests pass, skip running between steps" | A suite you don't run can't catch your mistakes |
| "Rewrite this whole module" | Rewrites introduce new bugs; extract incrementally |
| "DRY — combine these similar functions" | Similar != identical; only deduplicate same-reason changes |
| "Skip small renames, they're cosmetic" | Naming IS readability; renaming IS refactoring |

## Workflow

### Phase 1: Assessment
**Entry:** Target code accessible
**Actions:**
1. Read code, identify smells: duplication, long functions, nesting, magic numbers, unclear names
2. Check that tests exist; if missing, write characterization tests first
3. Run test suite to establish green baseline
4. Prioritize: safety > readability > structure > style
**Exit:** Prioritized refactoring list, tests green

### Phase 2: Refactor
**Entry:** Assessment complete, tests passing
**Actions:**
1. Apply highest-priority refactoring (one at a time):
   - Extract method / Extract class / Replace magic numbers
   - Simplify conditionals (early returns, lookup tables)
   - Remove true duplication / Rename for clarity
2. Run full test suite after each individual change
3. If tests fail, revert last change and diagnose
4. Repeat for each refactoring in priority order
**Exit:** All refactorings applied, tests passing after each

### Phase 3: Verify
**Entry:** All refactorings applied
**Actions:**
1. Run full test suite — must be green
2. Verify no public API signatures changed
3. Verify identical external behavior
4. Confirm each refactoring documented in findings
5. Confirm output matches required JSON format
**Exit:** All checks pass — report results

## Output Format

```json
{
  "skill": "code-refactoring",
  "status": "completed",
  "worker": "worker-id",
  "summary": "Refactored user_service.py: extracted 3 methods, replaced 4 magic numbers, simplified 2 conditionals. 28 tests passing.",
  "findings": [
    {"item": "Extracted validate_email() from create_user() — user_service.py:45-62", "severity": "info", "detail": "18-line block to dedicated method. create_user 67->52 lines."},
    {"item": "Replaced 86400 with SECONDS_PER_DAY — cache.py:23,41,89", "severity": "info", "detail": "3 occurrences to named constant. Single point of change."},
    {"item": "Simplified process_order() nesting — order_service.py:78-112", "severity": "info", "detail": "4-level deep conditional to early returns. Same logic, 1 level nesting."}
  ],
  "errors": [],
  "elapsed_seconds": 42.1
}
```

**Bad example:** `{"summary": "Cleaned up the code", "findings": [{"item": "refactored functions"}]}` — no specifics, no file refs, no before/after, "cleaner" is unverifiable.

## Escalation Triggers

STOP and report to boss when:
- No tests exist and writing them exceeds refactoring scope
- Refactoring requires changing a public API others depend on
- Tests fail and cause is not immediately clear
- Code is auto-generated and changes will be overwritten
- Scope grows beyond what was requested

## Success Criteria

- [ ] All tests pass after refactoring (same green count as before)
- [ ] No public API signatures changed
- [ ] External behavior identical (same inputs, same outputs)
- [ ] Each refactoring documented with file, line, and description
- [ ] Identified smells addressed or documented as deferred
- [ ] Output matches JSON format above
- [ ] No unresolved escalation triggers
