---
name: refactor
description: |
  Structured 8-phase refactoring workflow with two input modes:
  Automatic (skill discovers issues) and Guided (input file with change list).
  Each run gets its own subfolder in _docs/04_refactoring/.
  Delegates code execution to the implement skill via task files in _docs/02_tasks/.
  Additional workflow modes: Targeted (skip discovery), Quick Assessment (phases 0-2 only).
category: evolve
tags: [refactoring, coupling, technical-debt, performance, testability]
trigger_phrases: ["refactor", "refactoring", "improve code", "analyze coupling", "decoupling", "technical debt", "code quality"]
disable-model-invocation: true
---

# Structured Refactoring

Phase details live in `phases/` — read the relevant file before executing each phase.

## Core Principles

- **Preserve behavior first**: never refactor without a passing test suite (exception: testability runs, where the goal is making code testable)
- **Measure before and after**: every change must be justified by metrics
- **Small incremental changes**: commit frequently, never break tests
- **Save immediately**: write artifacts to disk after each phase
- **Delegate execution**: all code changes go through the implement skill via task files
- **Ask, don't assume**: when scope or priorities are unclear, STOP and ask the user
- **Exact-fit recommendations**: do not recommend a replacement pattern, library, service, architecture, algorithm, or "modern approach" merely because it improves structure or solves a similar class of problem. It must fit confirmed product constraints, acceptance criteria, operating context, integration boundaries, and current code realities. Otherwise reject it, mark it experimental, or ask the user before adding it to the roadmap.
- **Per-mode API capability verification on replacements**: when a refactor proposes replacing or adding a library/SDK/framework/service that exposes multiple modes or configurations, pin the exact mode the refactored code will use (inputs, outputs, runtime) and verify *that mode* via mandatory `context7` lookup plus a saved Minimum Viable Example before promoting the recommendation to `Selected`. Capability claims at the category level ("supports A, B, C modes") must be cross-checked against the literal mode enumeration — `A, B → A+B` style conflations are the recurring silent-failure path.

## Context Resolution

Announce detected paths and input mode to user before proceeding.

**Fixed paths:**

| Path | Location |
|------|----------|
| PROBLEM_DIR | `_docs/00_problem/` |
| SOLUTION_DIR | `_docs/01_solution/` |
| COMPONENTS_DIR | `_docs/02_document/components/` |
| DOCUMENT_DIR | `_docs/02_document/` |
| TASKS_DIR | `_docs/02_tasks/` |
| TASKS_TODO | `_docs/02_tasks/todo/` |
| REFACTOR_DIR | `_docs/04_refactoring/` |
| RUN_DIR | `REFACTOR_DIR/NN-[run-name]/` |

**Prereqs**: `problem.md` required, `acceptance_criteria.md` warn if absent.

**RUN_DIR resolution**: on start, scan REFACTOR_DIR for existing `NN-*` folders. Auto-increment the numeric prefix for the new run. The run name is derived from the invocation context (e.g., `01-testability-refactoring`, `02-coupling-refactoring`). If invoked with a guided input file, derive the name from the input file name or ask the user.

Create REFACTOR_DIR and RUN_DIR if missing. If a RUN_DIR with the same name already exists, ask user: **resume or start fresh?**

## Input Modes

| Mode | Trigger | Discovery source |
|------|---------|-----------------|
| Automatic | Default, no input file | Skill discovers issues from code analysis |
| Guided | Input file provided (e.g., `/refactor @list-of-changes.md`) | Reads input file + scans code to form validated change list |

Both modes produce `RUN_DIR/list-of-changes.md` (template: `templates/list-of-changes.md`). Both modes then convert that file into task files in TASKS_DIR during Phase 2.

**Guided mode cleanup**: after `RUN_DIR/list-of-changes.md` is created from the input file, delete the original input file only if it lives outside `RUN_DIR`. If the provided file is already the canonical `RUN_DIR/list-of-changes.md`, keep it as the audit record.

## Workflow

| Phase | File | Summary | Gate |
|-------|------|---------|------|
| 0 | `phases/00-baseline.md` | Collect goals, create RUN_DIR, capture baseline metrics | BLOCKING: user confirms |
| 1 | `phases/01-discovery.md` | Document components (scoped for guided mode), produce list-of-changes.md | BLOCKING: user confirms |
| 2 | `phases/02-analysis.md` | Research improvements, produce roadmap, create epic, decompose into tasks in TASKS_DIR | BLOCKING: user confirms |
| | | *Quick Assessment stops here* | |
| 3 | `phases/03-safety-net.md` | Check existing tests or implement pre-refactoring tests (skip for testability runs) | GATE: all tests pass |
| 4 | `phases/04-execution.md` | Delegate task execution to implement skill | GATE: implement completes |
| 4.5 | (inline, testability runs only) | Produce `testability_changes_summary.md` listing every applied change in plain language, surface to user | GATE: user acknowledges summary |
| 5 | `phases/05-test-sync.md` | Remove obsolete, update broken, add new tests | GATE: all tests pass |
| 6 | `phases/06-verification.md` | Run full suite, compare metrics vs baseline | GATE: all pass, no regressions |
| 7 | `phases/07-documentation.md` | Update `_docs/` to reflect refactored state | Skip if `_docs/02_document/` absent |

**Workflow mode detection:**
- "quick assessment" / "just assess" → phases 0–2
- "refactor [specific target]" → skip phase 1 if docs exist
- Default → all phases

**Testability-run specifics** (guided mode invoked by autodev existing-code Step 4 or greenfield Step 8):
- Run name is `01-testability-refactoring`.
- Phase 3 (Safety Net) is skipped by design — no tests exist yet. Compensating control: the `list-of-changes.md` gate in Phase 1 must be reviewed and approved by the user before Phase 4 runs.
- Scope is MINIMAL and surgical; reject change entries that drift into full refactor territory (see the invoking flow's testability step for allowed/disallowed lists). Flagged entries go to `RUN_DIR/deferred_to_refactor.md` for the next optional full-refactor step or backlog consideration.
- After Phase 4 (Execution) completes, write `RUN_DIR/testability_changes_summary.md` as Phase 4.5. Format: one bullet per applied change.
  ```markdown
  # Testability Changes Summary ({{run_name}})

  Applied {{N}} change(s):

  - **{{change_id}}** — changed {{symbol}} in `{{file}}`: {{plain-language reason}}. Risk: {{low|medium|high}}.
  ```
  Group bullets by category (config extraction, DI insertion, singleton wrapping, interface extraction, function split). Present the summary to the user via the Choose format before proceeding to Phase 5.

At the start of execution, create a TodoWrite with all applicable phases.

## Artifact Structure

All artifacts are written to RUN_DIR:

```
baseline_metrics.md                      Phase 0
discovery/components/[##]_[name].md      Phase 1
discovery/solution.md                    Phase 1
discovery/system_flows.md                Phase 1
list-of-changes.md                       Phase 1
analysis/research_findings.md            Phase 2
analysis/refactoring_roadmap.md          Phase 2
test_specs/[##]_[test_name].md           Phase 3
execution_log.md                         Phase 4
testability_changes_summary.md           Phase 4.5 (testability runs only)
test_sync/{obsolete_tests,updated_tests,new_tests}.md  Phase 5
verification_report.md                   Phase 6
doc_update_log.md                        Phase 7
FINAL_report.md                          after all phases
```

Task files produced during Phase 2 go to TASKS_TODO (not RUN_DIR):
```
TASKS_TODO/[TRACKER-ID]_refactor_[short_name].md
TASKS_DIR/_dependencies_table.md (appended)
```

**Resumability**: match existing artifacts to phases above, resume from next incomplete phase.

## Final Report

After all phases complete, write `RUN_DIR/FINAL_report.md`:
mode used (automatic/guided), input mode, phases executed, baseline vs final metrics, changes summary, remaining items, lessons learned.

## Escalation Rules

| Situation | Action |
|-----------|--------|
| Unclear scope or ambiguous criteria | **ASK user** |
| Tests failing before refactoring | **ASK user** — fix tests or fix code? |
| Risk of breaking external contracts | **ASK user** |
| Performance vs readability trade-off | **ASK user** |
| No test suite or CI exists | **WARN user**, suggest safety net first |
| Security vulnerability found | **WARN user** immediately |
| Implement skill reports failures | **ASK user** — review batch reports |
