---
name: refactor
description: "Refactor existing code to improve quality, maintainability, or performance. Ensures no behavior changes via comprehensive testing."
argument-hint: "[what to refactor]"
---

# /refactor — Disciplined Refactoring Workflow

You are refactoring existing code. The cardinal rule: **behavior must not change**. Tests are your proof that behavior is preserved. If the scope grows to include new behavior, escalate to `/feature`.

## Execution Protocol

**REQUIRED SUB-SKILL**: load and follow the skill — do not substitute judgment.
Step summaries describe outcomes; the loaded skill defines the process.

## Input

Ask the user for:
1. **What to refactor** — which code, module, or pattern
2. **Why** — tech debt, performance, readability, testability
3. **Constraints** — areas that must NOT be touched, deadlines

## Step 0: Repo-State Detection & Routing Redirect

Before any other check, detect whether this repo is in **prototype mode** or **production mode** per `rules/common/skill-selection.md` Step 1.

1. **Local context wins** (the mixed-mode override). Check work-item-local signals first; these override the project-level declared mode: path under `pocs/` or `*-prototype/`; manifest shows prototype-phase active. If either fires, treat as prototype and proceed to the redirect.
2. **Otherwise, read `.claude/CLAUDE.md`'s `project.mode:`** (set by `/setup` Step 2.5):
   - `prototype` or `greenfield` → offer the redirect below.
   - `production` → skip the redirect and proceed straight to Step 0a. Refactoring legacy production code is exactly what `/refactor` is for.
   - Absent → ask the user once and persist per `rules/common/skill-selection.md` Step 1.

**A "missing `aiwiki/architecture/`" check is intentionally NOT a signal here** — legacy production codebases that adopt forge always have empty `aiwiki/architecture/`, and using that as a prototype-mode signal would misclassify every `/refactor` invocation against existing code. The behavioral signals above (path + manifest) are stronger.

**If prototype mode is detected**, stop and offer the redirect:

```
This looks like prototype iteration, not refactoring of production code (signals: <list matched signals>).

/refactor enforces no-behavior-change with coverage baseline + comprehensive tests as the safety net — appropriate for production code that has those tests, overkill for prototype work where mocks ARE the verification surface.

Redirect to iterate-prototype? [Y]es / [n]o continue with /refactor anyway / [a]bort
```

User responses:
- **Y / yes**: invoke `iterate-prototype` with the refactor description as input. Skip the rest of /refactor.
- **n / no**: proceed to Step 0a. User confirms there IS production-grade test coverage to refactor against.
- **a / abort**: stop.

If production mode, proceed to Step 0a directly.

## Step 0a: Preflight Checks

1. **Git is clean** — no uncommitted changes
2. **ALL tests pass** — the test suite is your safety net
3. **Test coverage baseline** — record current coverage; refactoring must not reduce it
4. **Branch** — `refactor/{description-slug}`

## Step 0b: Wiki Bootstrap

REQUIRED SUB-SKILL: Use **support-wiki-bootstrap** to ensure aiwiki/ exists.

Refactor decisions and any newly-discovered conventions write to `aiwiki/`.

Check if `.forge/work/refactor/{name}/manifest.yaml` exists.

**If it exists**: Read the manifest. Resume from the last incomplete phase. Report what has already been completed and what remains. If `status: escalated` or `status: completed`, do NOT resume.

**If it does not exist**: Create the work directory (`.forge/work/refactor/{name}/`) and manifest using the template at `.claude/templates/manifests/refactor.yaml`. Fill placeholders `{name}`, `{description}`, `{date}`. Record coverage baseline in `coverage-baseline`.

If this refactor was escalated from a bugfix, set `escalated_from: work/bugfix/{predecessor-name}`.

## Step 1: Discover — Codebase Analysis

REQUIRED SUB-SKILL: Use **discover-codebase-analysis**.

### GATE: Codebase Analysis
Present the analysis to the user. User must approve before planning begins. Update manifest: `discover.codebase-analysis.status: complete, gate-passed: true`.

## Step 2: Plan — Brainstorm Refactoring Approach

REQUIRED SUB-SKILL: Use **plan-brainstorm** (scoped to refactoring).

### GATE: Brainstorm Approval
User must explicitly approve the refactoring approach. Update manifest: `plan.brainstorm.status: complete, gate-passed: true`.

## Step 3: Plan — Task Decomposition

REQUIRED SUB-SKILL: Use **plan-task-decompose**.

### GATE: Task Plan Review
User approves the task breakdown. Update manifest: `plan.task-decompose.status: complete, gate-passed: true`.

## Step 4: Build — Implement Refactoring (Phase Loop)

Execute tasks phase by phase from the task plan. Phases run sequentially. Tasks within a phase run in parallel when `execution.mode` is `subagent`.

For each phase, run full test suite first to confirm baseline passes, then for each task:

1. REQUIRED SUB-SKILL: Use **build-tdd** — write characterization tests first if missing, then refactor, then verify. For subagent execution mode, run with `isolation: "worktree"` so phase tasks parallelize cleanly.
2. REQUIRED SUB-SKILL: Use **quality-code-review** — fix any Critical or Important findings before the task closes.
3. Commit: `refactor: {what was improved}` (inline mode) or merge the worktree (`git merge --no-ff`) into the refactor branch (subagent mode).

After every phase completes, re-run the full test suite on the merged result before moving to the next phase.

**If ANY test breaks and you cannot immediately see why, REVERT.** Do not fix the test to match new behavior — that means you changed behavior.

### GATE: Implementation Complete
All phases complete. All per-task code reviews passed. All tests pass on merged result. Coverage equals or exceeds baseline.
Update manifest: mark all tasks in `build.tasks` as complete.

## Step 5: Quality — Test Execution

REQUIRED SUB-SKILL: Use **quality-test-execution**.
Coverage must be equal or higher than baseline.

### GATE: Test Results
All tests pass. Coverage equals or exceeds baseline recorded in Step 0. Fix failures before proceeding.
Update manifest: `quality.test-execution.status: complete, gate-passed: true`.

## Step 5.5: Quality — Refactoring Assessment

Produce a before/after summary of what the refactoring improved.

**Quantitative** (from `git diff --stat`):
- Files changed, lines added/removed
- Functions/methods before vs after

**Qualitative** — assess which of these improved, stayed the same, or got worse (tradeoffs):
- Readability, simplicity, consistency
- Maintainability, testability, debuggability
- Predictability, correctness

Present the assessment to the user. This feeds into the PR description.
Update manifest: `quality.assessment.status: complete, gate-passed: true`.

### GATE: Refactoring Assessment
User has reviewed the before/after assessment. Assessment feeds into the PR description.

## Step 6: Deliver — Create PR

REQUIRED SUB-SKILL: Use **build-pr-workflow**.
Keep the PR focused — refactoring only, no feature work mixed in.

## Step 7: Support — Record Lessons

REQUIRED SUB-SKILL: Use **support-gotcha**.

## Gate Exemptions

| Standard Gate | Refactor Equivalent | Rationale |
|---|---|---|
| quality-test-plan | Skipped | Refactoring preserves behavior — the existing test suite IS the test plan. Characterization tests are added in Step 4 via build-tdd when coverage gaps exist. |
| requirements → brainstorm | Compressed (discover → brainstorm) | No new requirements — scope is existing code quality. |
| architecture phase | Skipped | Refactoring operates within existing architecture. If architecture changes are needed, escalate to `/feature`. |
