Refactor code in small, test-protected steps: pin current behavior first, change one thing at a time, and rerun tests after every step.
---
name: refactor
description: Restructures existing code without changing its behavior - extract function, rename, simplify conditionals, remove duplication or dead code - in small steps protected by tests. Pins current behavior with tests first, makes one change at a time, and reruns the tests after each step. Use when asked to refactor, clean up, simplify, untangle, or improve the readability of code while keeping it working.
compatibility: Needs read/write access to the code and a way to run its tests (for example npm test, pytest, go test, cargo test).
metadata:
version: "2.1.0"
---
# Refactor
Refactoring changes structure, not behavior. If a request also changes behavior (new feature, bug fix, different output), split it: refactor first under passing tests, then make the behavior change as a separate step the user can review.
## Inputs to collect
- The file(s) or function(s) to refactor and the goal (readability, duplication, testability, smaller functions, clearer names).
- How to run the tests. If there are none for this code, say so.
- Constraints: public API that must not change, performance-sensitive paths, style rules.
## Workflow
1. **Read the code and its callers.** Note the public surface (exported names, signatures, return values, thrown errors, side effects). These must stay the same unless the user agrees otherwise.
2. **Pin behavior with tests before changing anything.**
- Run the existing tests and record the result. If they already fail, stop and report; do not refactor on a red baseline without the user's say-so.
- If coverage of the target is missing, add characterization tests that assert what the code does today, including edge cases (boundaries, empty input, error paths). These tests describe current behavior, even if it looks odd; flag oddities instead of "fixing" them.
3. **Plan small steps.** Name each one from the refactoring catalog: Extract Function, Inline Variable, Rename Variable / Rename Function, Replace Nested Conditional with Guard Clauses, Replace Magic Literal, Consolidate Conditional Expression, Slide Statements, Remove Dead Code. Show the plan for anything beyond a single function.
4. **Apply one step at a time and rerun the tests after each.** If a test fails, undo that step rather than adjusting the test. Use editor or language-server rename for renames across files when available, and search for dynamic references (string lookups, reflection, templates) that a rename might miss.
5. **Finish**: run the full test suite and linter/type checker, show the diff, and summarize each step and why it helps.
## Output format
```
Baseline: node --test shipping.test.js -> 6 pass, 0 fail
Steps:
1. Replace nested conditional with guard clause (free US shipping first)
2. Replace magic literals with a RATES table and FREE_SHIPPING_THRESHOLD_US
3. Consolidate the duplicated express/standard branches into a zone lookup
After: 6 pass, 0 fail. Public API unchanged: shippingCost(order) -> number
Noted, not changed: non-US orders never get free shipping (behavior question for you)
```
## Example
Before:
```js
export function shippingCost(order) {
if (order.country === "US") {
if (order.total >= 100) { return 0; }
else { if (order.express) { return 25; } else { return 8; } }
} else {
if (order.express) { return 40; } else { return 15; }
}
}
```
After (same results for all six characterization cases):
```js
const FREE_SHIPPING_THRESHOLD_US = 100;
const RATES = { domestic: { standard: 8, express: 25 }, international: { standard: 15, express: 40 } };
export function shippingCost(order) {
const domestic = order.country === "US";
if (domestic && order.total >= FREE_SHIPPING_THRESHOLD_US) return 0;
const zone = domestic ? RATES.domestic : RATES.international;
return order.express ? zone.express : zone.standard;
}
```
## Limitations
- Tests only protect the behavior they cover. Say which paths are untested instead of claiming the refactor is guaranteed safe.
- Do not mix formatting-only churn across unrelated files into the same change.
- Language-agnostic: works for TypeScript, JavaScript, Python, Go, Rust, Java and others, as long as the project's own test and type-check commands can run.
- Rollback is ordinary version control: keep the work in reviewable commits or a branch; do not discard the user's uncommitted work.
Review a git diff, commit or snippet for bugs, security, performance and maintainability, with file:line evidence and a concrete fix per finding.
Debug systematically: reproduce the bug, rank hypotheses by evidence, test them with logging, a debugger or git bisect, then fix the root cause with a regression test.
Set up transactional email
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A shipping-cost function has grown nested if/else branches with hard-coded rates; the team wants it readable without changing any prices.
Refactor shippingCost in shipping.js for readability. Don't change behavior. Tests: node --test shipping.test.js. Current code: US orders >= 100 ship free; US express 25, US standard 8; non-US express 40, non-US standard 15.
Baseline test run reported first (6 pass). A short step plan (guard clause for free US shipping, named constants/RATES table, zone lookup instead of duplicated branches), then the refactored function shown in the skill's example, the same test command rerun with 6 pass / 0 fail, unchanged signature, and a note that non-US free shipping does not exist (raised as a question, not changed).
AI Agent Skills are reusable workflow packages that extend your AI coding assistant with multi-step capabilities. Install refactor by following these steps.
SKILL.md inside, in the location documented by your client. Do not assume every AI application reads the same directory.Requires an Agent Skills-compatible client; supported locations and activation vary by version. Read the SKILL.md setup guide. MCP connects tools and data and does not, by itself, install a skill.
Review a git diff, commit or snippet for bugs, security, performance and maintainability, with file:line evidence and a concrete fix per finding.
Debug systematically: reproduce the bug, rank hypotheses by evidence, test them with logging, a debugger or git bisect, then fix the root cause with a regression test.
Set up transactional email