| name | refactor |
| description | Systematic multi-file refactoring with pattern analysis, scope detection, batched execution, and progress tracking. Use for renames, pattern changes, API migrations, or any change affecting 6+ files. |
| category | process |
| triggers | ["rename","restructure","reorganize","pattern change","large-scale change","multi-file change"] |
Refactor
Purpose: Systematic refactoring with planning, pattern detection, and batched execution
Phases: Gather Context → Pattern Analysis → Plan → Execute → Validate → Commit
Usage: /refactor [scope flags] <refactor description>
Iron Laws
- NO BEHAVIOR CHANGE WITHOUT APPROVAL — Refactoring changes structure, not behavior. If the refactor would change what the code does, stop and confirm.
- ALL EXISTING TESTS MUST PASS — After every batch, run tests. If tests fail, the refactor introduced a bug.
- BATCH AND VERIFY — Never change more than 5 files without verifying. Large refactors are done in small, verified increments.
- REVERT ON FAILURE — If a batch breaks tests, revert the entire batch rather than debugging individual changes. Start fresh with a corrected approach.
When to Use
- Renaming functions, variables, or types across the codebase
- Migrating from one API/pattern to another
- Restructuring directories or modules
- Any change affecting 6+ files
When NOT to Use
- Changing behavior (adding features) →
/implement
- Fixing a bug →
/debug
- 1-5 file changes →
/implement
- Emergency fix →
/hotfix
Note: Command examples use npm as default. Adapt to the project's package manager per ai-assistant-protocol — Project Commands.
Gate Enforcement
See ai-assistant-protocol for valid approval terms and invalid responses.
Scope Flags
| Flag | Description |
|---|
--files=<paths> | Limit refactor to specific files/directories |
--project=<path> | Project root for monorepos |
Phase 1: Gather Context
Step 1.1: Clarify Requirements
Ask: (1) What pattern/code needs to change? (2) Target state? (3) Why? (4) Areas to exclude?
Wait for user response before exploring code.
Step 1.2: Explore and Categorize
Determine refactor type, file count, risk level:
| Scope | Files | Risk | Approach |
|---|
| Small | 1-5 | Low | Direct changes |
| Medium | 6-20 | Medium | Batched with testing |
| Large | 21-50 | High | Phased with checkpoints |
| Massive | 50+ | Critical | Multiple phases |
Wait for confirmation.
Phase 2: Pattern Analysis
Step 2.1: Find All Occurrences
Search for all instances of the pattern. Present findings (see references/refactor-templates.md — Pattern Analysis).
Step 2.2: Surface Edge Cases
Present edge cases for discussion. Wait for user guidance.
Phase 3: Plan
Present the refactor plan summary (see references/refactor-templates.md — Plan Summary).
Step 3.1: Evaluate Direct Change vs. Abstraction Layer
For most refactors, direct changes are fine. However, when a direct rename or change is too risky (high coupling, external API surface, published package), use the Introduce Abstraction Layer pattern:
- Introduce an abstraction layer — Create an adapter, wrapper, or re-export that maps the old name/interface to the new one
- Migrate consumers to the abstraction — Update import sites to use the adapter (this can be done incrementally and is safe to pause)
- Swap the implementation behind the abstraction — Replace the old implementation with the new one; consumers are unaffected because they use the adapter
- Remove the abstraction if desired — Once all consumers point to the new implementation, the adapter layer can be removed in a final cleanup pass
This pattern is safer for public APIs, published packages, and widely-used internal interfaces where a single atomic rename would be too disruptive or where the migration must be done incrementally across multiple PRs.
Present the chosen strategy (direct change or abstraction layer) as part of the plan summary.
GATE: Do NOT begin modifying files until user approves.
Phase 4: Execute
Step 4.1: Create Git Savepoint
Before starting any changes:
git stash push -m "savepoint: before refactor" --include-untracked 2>/dev/null; git stash pop 2>/dev/null
Or ensure all current work is committed so you can revert cleanly.
Step 4.2: Determine Change Order (Phased Refactoring)
Apply refactoring changes in a safe order to catch breakage early:
- Type definitions and interfaces first — These catch downstream breakage at compile time. If a type rename is wrong, the typecheck immediately surfaces every affected file.
- Implementation files second — Guided by type errors from the previous phase. Update services, handlers, and utilities.
- Test files last — Tests verify the refactoring works. Updating them last ensures they validate the final state, not an intermediate one.
Run typecheck after each phase. If the typecheck fails, fix issues in the current phase before proceeding.
Step 4.3: Group Changes into Batches
For large refactors, group changes into logical batches (max 5 files per batch). Present the batch grouping to the user for approval before executing.
Grouping strategies:
- By dependency layer (default): types/interfaces -> services/implementations -> routes/handlers -> tests. This ensures each batch is independently type-checkable.
- By feature area: When the refactor is cross-cutting (e.g., rename used in auth, billing, and notifications), group by feature so each batch leaves one feature area fully migrated.
- Mixed: Use dependency-layer ordering within each feature area for very large refactors.
Each batch should be independently type-checkable — after applying a batch and running typecheck, there should be no new type errors introduced by that batch (existing errors from not-yet-migrated code are expected and acceptable).
See references/safe-refactoring-patterns.md for pattern-specific risk and batch safety guidance.
Step 4.4: Execute Batches
For each batch:
- Apply changes
- Run typecheck
- Run affected tests
- Report progress
If tests fail after a batch: Revert the batch (git checkout -- [affected-files]), reassess the approach, and try again with a corrected strategy. Do not debug individual file changes within a broken batch.
Step 4.5: Handle Discrepancies
If a file doesn't match expected patterns, present discrepancy report. Wait for user decision. Don't force the change.
Phase 5: Validate
npm run typecheck
npm run lint
npm run test -- {affected-pattern}
npm run test
Test Updates Required
- Renamed public API → Update test references
- Changed signatures → Update calls and mocks
- Moved code → Update import paths
- Internal restructure → Existing tests should suffice
Present verification report (see references/refactor-templates.md — Verification Report).
GATE: All tests must pass before proceeding.
Phase 6: Commit
Present commit message. Refactoring commits should use refactor: type and clearly describe what changed structurally.
Keep refactoring commits separate from feature commits. Never mix refactoring and behavior changes in the same commit.
GATE: Wait for explicit confirmation.
Principles
- Ask, don't assume — Clarify requirements and edge cases
- Get approval before executing — Never refactor without explicit approval
- Preserve behavior — Refactors should not change functionality
- Surface issues early — Report discrepancies, don't silently skip
- Revert freely — Failed batches get reverted, not debugged
- Confirm before committing — User verification required
Quick Reference
| Phase | Gate |
|---|
| 1. Gather Context | User confirms scope |
| 2. Pattern Analysis | User guides edge cases |
| 3. Plan | User approves |
| 4. Execute | Tests pass per batch |
| 5. Validate | All tests pass |
| 6. Commit | User confirms |
References
- Refactor Templates — Display templates for plan summaries, batch progress, discrepancy reports, verification reports, and commit messages
- Safe Refactoring Patterns — Pattern-specific risk levels, before/after examples, batch safety guidance, and import/export chaining
Acceptance Tests
| ID | Type | Prompt / Condition | Expected |
|---|
| REF-T1 | Positive | "Rename all utils to helpers across the codebase" | Skill triggers |
| REF-T2 | Positive | "Restructure the components directory" | Skill triggers |
| REF-T3 | Positive | "Migrate from callbacks to async/await" | Skill triggers |
| REF-T4 | Negative | "Add a new helper function" | Does NOT trigger (→ /implement) |
| REF-T5 | Negative | "Fix the broken import" | Does NOT trigger (→ /debug) |
| REF-T6 | Negative | "Change 2 files to use new pattern" | Does NOT trigger (→ /implement, <6 files) |
| REF-T7 | Boundary | "Rename this function in 4 files" | Does NOT trigger (→ /implement, <6 files) |
| REF-T8 | Boundary | "Rename this function across 8 files" | Skill triggers (6+ files) |