Code Refactoring
Use this skill when the job is to improve structure without changing intended behavior.
The center of the skill should stay small and repeatable:
- identify the cleanup packet you actually have,
- choose one refactor mode,
- make the behavior guardrail explicit,
- stage the work in reviewable slices,
- verify and route remaining work honestly.
Read these support docs before handling unfamiliar cleanup work:
- references/intake-packets-and-route-outs.md
- references/refactor-modes.md
- references/handoff-boundaries.md
- references/safe-refactor-checklist.md
When to use this skill
- A function, component, service, script, or module is too tangled and needs structural cleanup without a behavior change.
- A legacy area needs a freeze-first cleanup because the current behavior is fragile or poorly understood.
- The same API, naming, or structure change repeats across many files and needs a codemod / migration brief.
- A diff mixes cleanup with too much semantic work and needs to be split into smaller reviewable slices.
- The user asks to refactor, decompose, deduplicate, rename safely, stage a cleanup, or plan a behavior-preserving migration.
When not to use this skill
- The main job is proving why behavior is wrong, reproducing a failure, or isolating a regression →
debugging
- The main job is deciding whether a concrete diff / PR is safe to merge →
code-review
- The main job is choosing org-wide validation depth, benchmark policy, or release gates →
testing-strategies
- The main job is finding the bottleneck from traces, flamegraphs, CWV reports, or profiler output →
performance-optimization
- The main job is finding symbols, call sites, or impact scope before any cleanup tactic is chosen →
codebase-search
Instructions
Step 1: Start from the cleanup packet
Use references/intake-packets-and-route-outs.md.
Choose the packet the user already has:
- one messy file / component / service
- a fragile legacy area with weak confidence in current behavior
- a repeated migration pattern across many files
- a cleanup-heavy diff that needs reshaping before review
- only a vague desire to “find all the places first”
Output the intake briefly:
## Cleanup Packet
- Current artifact:
- Why it is enough (or not enough):
- Missing evidence to collect next:
Rule: do not force a giant refactor plan when the immediate need is only search, diagnosis, review, or performance evidence.
Step 2: Choose one primary refactor mode
Pick exactly one primary mode from references/refactor-modes.md.
Primary modes:
local-safe-refactor
behavior-freeze-first
repetitive-migration-codemod
diff-shaping-cleanup
Quick selector:
| Signal |
Mode |
| One file or narrow module, clear intent, at least one fast guardrail exists |
local-safe-refactor |
| Fragile legacy area, hidden invariants, weak test trust |
behavior-freeze-first |
| Same API or structure repeats across many files |
repetitive-migration-codemod |
| Cleanup is mixed into a risky review diff and needs smaller slices |
diff-shaping-cleanup |
Rule: one primary mode, optional secondary note. Do not mix every cleanup tactic into one answer.
Step 3: Freeze the behavior guardrail
Before broad edits, decide how you will prove intent stayed the same.
Guardrail sources can include:
- existing unit / integration / end-to-end tests
- typecheck and linter
- characterization tests or captured examples
- fixture snapshots or golden outputs
- screenshots / preview captures for UI work
- before/after sample input-output tables
- manual smoke steps when automation is thin
Minimum rule:
- Local cleanup → at least one fast verification path
- Fragile legacy cleanup → freeze behavior first
- Repeated migration → pilot on a small representative sample first
- Diff reshaping → separate mechanical cleanup from semantic follow-up
If the user mainly needs help designing the entire validation program, route to testing-strategies.
Step 4: Build the smallest credible cleanup plan
Keep the plan reviewable.
Preferred slices:
- rename / move / extract work
- duplicated or dead-code cleanup
- mechanical migration or codemod rollout
- semantic follow-up only if still needed
- verification + handoff
For each slice, capture:
- goal
- behavior to preserve
- evidence / guardrail
- risk edge
- whether another skill owns the next step
Rules:
- Prefer a sequence of boring diffs over one heroic rewrite.
- Keep structural cleanup and semantic behavior changes separate when possible.
- For migrations, define source pattern, target pattern, known exceptions, and rollback path before scaling up.
Step 5: Use the right mode packet
Use the matching packet in references/intake-packets-and-route-outs.md:
- local cleanup packet
- fragile legacy / freeze-first packet
- repeated migration / codemod packet
- diff-shaping packet
Good moves by mode:
local-safe-refactor → rename unclear concepts, extract pure logic, move side effects to edges, collapse close duplication
behavior-freeze-first → capture examples, add characterization tests, identify one seam, refactor behind that seam
repetitive-migration-codemod → define source/target pattern, sample first, inspect false positives, expand only after the pilot is trustworthy
diff-shaping-cleanup → split cleanup from semantic changes, isolate generated or mechanical edits, leave review notes about remaining hotspots
Step 6: Verify and route remaining work
Do not stop at “looks cleaner.”
Verification brief:
## Refactor Brief
- Primary mode:
- Behavior to preserve:
- Guardrail used:
- Smallest planned slices:
- Risks still open:
- Recommended next move:
Always call out:
- what behavior was intended to stay the same
- what evidence was used to verify that
- what still remains risky or out of scope
- which neighboring skill should own the next step when the job shifts
Output format
## Cleanup Packet
- Current artifact:
- Primary mode:
- Why this mode fits:
## Behavior Guardrail
- Intended behavior to preserve:
- Evidence available:
- Missing evidence:
## Planned slices
1. ...
2. ...
3. ...
## Verification
- Fast checks:
- Higher-risk checks:
## Route-outs
- Use `debugging` for:
- Use `code-review` for:
- Use `testing-strategies` for:
- Use `performance-optimization` for:
- Use `codebase-search` for:
Examples
Example 1: Oversized service handler
Input: "Refactor this 180-line checkout handler into something readable without changing behavior."
Good response shape:
- choose
local-safe-refactor
- preserve coupon / tax / out-of-stock behavior explicitly
- extract validation, pricing, and persistence helpers
- keep tests / typecheck as guardrails
- split structural cleanup from later semantic follow-up
Example 2: Fragile legacy module
Input: "This reporting service is impossible to maintain, but we barely trust the tests. Help me refactor it safely."
Good response shape:
- choose
behavior-freeze-first
- capture characterization cases before broad cleanup
- identify one seam at a time instead of redesigning everything
- route deep failure investigation to
debugging if expected behavior is still unclear
Example 3: Repeated API migration
Input: "We need to replace a deprecated client API across 220 TypeScript files before the framework upgrade."
Good response shape:
- choose
repetitive-migration-codemod
- define source and target patterns
- pilot the transform on a subset first
- keep mechanical rewrite separate from semantic follow-up
- verify with tests, typecheck, and repo search
Example 4: Search-first route-out
Input: "Before we refactor anything, find every call site and wrapper around this old helper so we can see the blast radius."
Good response shape:
- route the primary task to
codebase-search
- do not present a full refactor plan as the main answer
- keep
code-refactoring positioned as the cleanup lane after the impact map exists
Best practices
- Start from the packet the user actually has, not an idealized cleanup workflow.
- Pick one primary mode before proposing actions.
- Make behavior preservation explicit; do not assume it.
- Prefer small, reviewable slices over one giant cleanup diff.
- Use codemods or structural rewrites only when repetition justifies the setup cost.
- Keep diagnosis, review judgment, test-policy design, performance tuning, and symbol inventory routed to neighboring skills instead of absorbing them.
- Preserve evidence of what was verified and what still remains risky.
References
1---2name: code-refactoring3description: Turn a cleanup packet into one behavior-preserving refactor brief. Use when simplifying a messy function/component/service, freezing behavior before touching fragile legacy code, splitting a cleanup-heavy diff into reviewable slices, or planning a repeated migration / codemod without changing intended behavior. Route diagnosis to debugging, review judgment to code-review, validation-program design to testing-strategies, bottleneck-led tuning to performance-optimization, and pure symbol inventory to codebase-search.4---567891011# Code Refactoring1213Use this skill when the job is to **improve structure without changing intended behavior**.1415The center of the skill should stay small and repeatable:161. identify the cleanup packet you actually have,172. choose one refactor mode,183. make the behavior guardrail explicit,194. stage the work in reviewable slices,205. verify and route remaining work honestly.2122Read these support docs before handling unfamiliar cleanup work:23- [references/intake-packets-and-route-outs.md](references/intake-packets-and-route-outs.md)24- [references/refactor-modes.md](references/refactor-modes.md)25- [references/handoff-boundaries.md](references/handoff-boundaries.md)26- [references/safe-refactor-checklist.md](references/safe-refactor-checklist.md)2728## When to use this skill29- A function, component, service, script, or module is too tangled and needs structural cleanup without a behavior change.30- A legacy area needs a **freeze-first** cleanup because the current behavior is fragile or poorly understood.31- The same API, naming, or structure change repeats across many files and needs a codemod / migration brief.32- A diff mixes cleanup with too much semantic work and needs to be split into smaller reviewable slices.33- The user asks to refactor, decompose, deduplicate, rename safely, stage a cleanup, or plan a behavior-preserving migration.3435## When not to use this skill36- **The main job is proving why behavior is wrong, reproducing a failure, or isolating a regression** → `debugging`37- **The main job is deciding whether a concrete diff / PR is safe to merge** → `code-review`38- **The main job is choosing org-wide validation depth, benchmark policy, or release gates** → `testing-strategies`39- **The main job is finding the bottleneck from traces, flamegraphs, CWV reports, or profiler output** → `performance-optimization`40- **The main job is finding symbols, call sites, or impact scope before any cleanup tactic is chosen** → `codebase-search`4142## Instructions4344### Step 1: Start from the cleanup packet45Use [references/intake-packets-and-route-outs.md](references/intake-packets-and-route-outs.md).4647Choose the packet the user already has:48- one messy file / component / service49- a fragile legacy area with weak confidence in current behavior50- a repeated migration pattern across many files51- a cleanup-heavy diff that needs reshaping before review52- only a vague desire to “find all the places first”5354Output the intake briefly:5556```markdown57## Cleanup Packet58- Current artifact:59- Why it is enough (or not enough):60- Missing evidence to collect next:61```6263Rule: do not force a giant refactor plan when the immediate need is only search, diagnosis, review, or performance evidence.6465### Step 2: Choose one primary refactor mode66Pick exactly one primary mode from [references/refactor-modes.md](references/refactor-modes.md).6768Primary modes:69- `local-safe-refactor`70- `behavior-freeze-first`71- `repetitive-migration-codemod`72- `diff-shaping-cleanup`7374Quick selector:75| Signal | Mode |76|---|---|77| One file or narrow module, clear intent, at least one fast guardrail exists | `local-safe-refactor` |78| Fragile legacy area, hidden invariants, weak test trust | `behavior-freeze-first` |79| Same API or structure repeats across many files | `repetitive-migration-codemod` |80| Cleanup is mixed into a risky review diff and needs smaller slices | `diff-shaping-cleanup` |8182Rule: one primary mode, optional secondary note. Do not mix every cleanup tactic into one answer.8384### Step 3: Freeze the behavior guardrail85Before broad edits, decide how you will prove intent stayed the same.8687Guardrail sources can include:88- existing unit / integration / end-to-end tests89- typecheck and linter90- characterization tests or captured examples91- fixture snapshots or golden outputs92- screenshots / preview captures for UI work93- before/after sample input-output tables94- manual smoke steps when automation is thin9596Minimum rule:97- **Local cleanup** → at least one fast verification path98- **Fragile legacy cleanup** → freeze behavior first99- **Repeated migration** → pilot on a small representative sample first100- **Diff reshaping** → separate mechanical cleanup from semantic follow-up101102If the user mainly needs help designing the entire validation program, route to `testing-strategies`.103104### Step 4: Build the smallest credible cleanup plan105Keep the plan reviewable.106107Preferred slices:1081. rename / move / extract work1092. duplicated or dead-code cleanup1103. mechanical migration or codemod rollout1114. semantic follow-up only if still needed1125. verification + handoff113114For each slice, capture:115- goal116- behavior to preserve117- evidence / guardrail118- risk edge119- whether another skill owns the next step120121Rules:122- Prefer a sequence of boring diffs over one heroic rewrite.123- Keep structural cleanup and semantic behavior changes separate when possible.124- For migrations, define source pattern, target pattern, known exceptions, and rollback path before scaling up.125126### Step 5: Use the right mode packet127Use the matching packet in [references/intake-packets-and-route-outs.md](references/intake-packets-and-route-outs.md):128- local cleanup packet129- fragile legacy / freeze-first packet130- repeated migration / codemod packet131- diff-shaping packet132133Good moves by mode:134- `local-safe-refactor` → rename unclear concepts, extract pure logic, move side effects to edges, collapse close duplication135- `behavior-freeze-first` → capture examples, add characterization tests, identify one seam, refactor behind that seam136- `repetitive-migration-codemod` → define source/target pattern, sample first, inspect false positives, expand only after the pilot is trustworthy137- `diff-shaping-cleanup` → split cleanup from semantic changes, isolate generated or mechanical edits, leave review notes about remaining hotspots138139### Step 6: Verify and route remaining work140Do not stop at “looks cleaner.”141142Verification brief:143```markdown144## Refactor Brief145- Primary mode:146- Behavior to preserve:147- Guardrail used:148- Smallest planned slices:149- Risks still open:150- Recommended next move:151```152153Always call out:154- what behavior was intended to stay the same155- what evidence was used to verify that156- what still remains risky or out of scope157- which neighboring skill should own the next step when the job shifts158159## Output format160161```markdown162## Cleanup Packet163- Current artifact:164- Primary mode:165- Why this mode fits:166167## Behavior Guardrail168- Intended behavior to preserve:169- Evidence available:170- Missing evidence:171172## Planned slices1731. ...1742. ...1753. ...176177## Verification178- Fast checks:179- Higher-risk checks:180181## Route-outs182- Use `debugging` for:183- Use `code-review` for:184- Use `testing-strategies` for:185- Use `performance-optimization` for:186- Use `codebase-search` for:187```188189## Examples190191### Example 1: Oversized service handler192**Input:** "Refactor this 180-line checkout handler into something readable without changing behavior."193194**Good response shape:**195- choose `local-safe-refactor`196- preserve coupon / tax / out-of-stock behavior explicitly197- extract validation, pricing, and persistence helpers198- keep tests / typecheck as guardrails199- split structural cleanup from later semantic follow-up200201### Example 2: Fragile legacy module202**Input:** "This reporting service is impossible to maintain, but we barely trust the tests. Help me refactor it safely."203204**Good response shape:**205- choose `behavior-freeze-first`206- capture characterization cases before broad cleanup207- identify one seam at a time instead of redesigning everything208- route deep failure investigation to `debugging` if expected behavior is still unclear209210### Example 3: Repeated API migration211**Input:** "We need to replace a deprecated client API across 220 TypeScript files before the framework upgrade."212213**Good response shape:**214- choose `repetitive-migration-codemod`215- define source and target patterns216- pilot the transform on a subset first217- keep mechanical rewrite separate from semantic follow-up218- verify with tests, typecheck, and repo search219220### Example 4: Search-first route-out221**Input:** "Before we refactor anything, find every call site and wrapper around this old helper so we can see the blast radius."222223**Good response shape:**224- route the primary task to `codebase-search`225- do not present a full refactor plan as the main answer226- keep `code-refactoring` positioned as the cleanup lane after the impact map exists227228## Best practices2291. Start from the packet the user actually has, not an idealized cleanup workflow.2302. Pick one primary mode before proposing actions.2313. Make behavior preservation explicit; do not assume it.2324. Prefer small, reviewable slices over one giant cleanup diff.2335. Use codemods or structural rewrites only when repetition justifies the setup cost.2346. Keep diagnosis, review judgment, test-policy design, performance tuning, and symbol inventory routed to neighboring skills instead of absorbing them.2357. Preserve evidence of what was verified and what still remains risky.236237## References238- [Intake packets and route-outs](references/intake-packets-and-route-outs.md)239- [Refactor modes](references/refactor-modes.md)240- [Handoff boundaries](references/handoff-boundaries.md)241- [Safe refactor checklist](references/safe-refactor-checklist.md)242- [Martin Fowler — Refactoring](https://martinfowler.com/books/refactoring.html)243- [VS Code refactoring docs](https://code.visualstudio.com/docs/editor/refactoring)244- [IntelliJ IDEA refactoring docs](https://www.jetbrains.com/help/idea/refactoring-source-code.html)245- [OpenRewrite docs](https://docs.openrewrite.org/)246- [jscodeshift](https://github.com/facebook/jscodeshift)247- [ast-grep](https://ast-grep.github.io/)