
Code Refactoring
- 30 installs
- 40 repo stars
- Updated August 4, 2026
- akillness/skills-template
Code Refactoring is a skill that turns a cleanup packet into one behavior-preserving refactor brief with explicit verification guardrails and reviewable slices.
About
Code Refactoring is a skill that turns a cleanup request into one behavior-preserving refactor brief. A developer uses it to simplify a messy function or module, split an oversized diff into safer slices, freeze behavior before touching fragile legacy code, or plan a repeated codemod migration. It picks one refactor mode, makes the behavior guardrail explicit, and stages the work in reviewable slices.
- Turns a cleanup packet into one behavior-preserving refactor brief with an explicit verification guardrail
- Offers four refactor modes: local-safe-refactor, behavior-freeze-first, repetitive-migration-codemod, diff-shaping-clean
- Stages work into reviewable slices and routes diagnosis, review, and performance work to other skills
Code Refactoring by the numbers
- 30 all-time installs (skills.sh)
- Ranked #667 of 1,352 Code Review & Quality skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
code-refactoring capabilities & compatibility
- Capabilities
- code refactoring · codemod migration · diff shaping · legacy cleanup
- Use cases
- refactoring · code review
- Pricing
- Free
What code-refactoring says it does
Use this skill when the job is to **improve structure without changing intended behavior**.
Before broad edits, decide how you will prove intent stayed the same.
npx skills add https://github.com/akillness/skills-template --skill code-refactoringAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 30 |
|---|---|
| repo stars | ★ 40 |
| Last updated | August 4, 2026 |
| Repository | akillness/skills-template ↗ |
What it does
Plan a behavior-preserving cleanup of a tangled function or a repeated migration, staged in reviewable slices with a verification guardrail.
Who is it for?
CLI, backend, frontend, fullstack, and game codebases where the task is structural cleanup with explicit verification.
Skip if: Proving a bug exists, approving a PR, choosing org-wide test policy, or isolating a performance bottleneck.
When should I use this skill?
The job is to improve structure without changing intended behavior - refactor, decompose, deduplicate, rename safely, or plan a codemod.
What you get
A behavior-preserving refactor brief with an explicit verification path and small reviewable slices.
- Behavior-preserving refactor brief staged in reviewable slices
By the numbers
- Four refactor modes; five preferred cleanup slices
Files
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: 1. identify the cleanup packet you actually have, 2. choose one refactor mode, 3. make the behavior guardrail explicit, 4. stage the work in reviewable slices, 5. 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-refactorbehavior-freeze-firstrepetitive-migration-codemoddiff-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: 1. rename / move / extract work 2. duplicated or dead-code cleanup 3. mechanical migration or codemod rollout 4. semantic follow-up only if still needed 5. 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 duplicationbehavior-freeze-first→ capture examples, add characterization tests, identify one seam, refactor behind that seamrepetitive-migration-codemod→ define source/target pattern, sample first, inspect false positives, expand only after the pilot is trustworthydiff-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
debuggingif 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-refactoringpositioned as the cleanup lane after the impact map exists
Best practices
1. Start from the packet the user actually has, not an idealized cleanup workflow. 2. Pick one primary mode before proposing actions. 3. Make behavior preservation explicit; do not assume it. 4. Prefer small, reviewable slices over one giant cleanup diff. 5. Use codemods or structural rewrites only when repetition justifies the setup cost. 6. Keep diagnosis, review judgment, test-policy design, performance tuning, and symbol inventory routed to neighboring skills instead of absorbing them. 7. Preserve evidence of what was verified and what still remains risky.
References
- Intake packets and route-outs
- Refactor modes
- Handoff boundaries
- Safe refactor checklist
- Martin Fowler — Refactoring
- VS Code refactoring docs
- IntelliJ IDEA refactoring docs
- OpenRewrite docs
- jscodeshift
- ast-grep
{
"skill_name": "code-refactoring",
"evals": [
{
"id": 1,
"prompt": "Refactor this 180-line checkout handler into smaller units without changing behavior. We already have unit tests, but the integration suite is slow.",
"expected_output": "Chooses a local safe refactor mode, states the behavior to preserve, proposes reviewable slices, and uses existing tests/typecheck as guardrails rather than redesigning everything.",
"assertions": [
"Response explicitly chooses a refactor mode",
"Response names preserved behavior or invariants",
"Response includes verification steps",
"Response avoids routing the whole task to debugging unless behavior is unclear"
]
},
{
"id": 2,
"prompt": "We need to replace a deprecated client API across 220 TypeScript files before the framework upgrade. What refactor workflow should we use?",
"expected_output": "Chooses repetitive migration / codemod mode, recommends piloting on a subset before repo-wide rollout, and keeps mechanical migration separate from semantic follow-up.",
"assertions": [
"Response chooses repetitive migration or codemod mode",
"Response mentions source and target pattern definition",
"Response recommends sample-first or pilot-first verification",
"Response includes verification beyond just trust in automation"
]
},
{
"id": 3,
"prompt": "This reporting module is full of conditionals and globals, but we barely trust the tests. Help me refactor it safely.",
"expected_output": "Chooses behavior freeze first mode, recommends characterization or guardrail creation before broad structural edits, and emphasizes small seams instead of a heroic rewrite.",
"assertions": [
"Response chooses behavior freeze first mode",
"Response recommends characterization tests, captured examples, or another behavior-freezing guardrail",
"Response emphasizes incremental cleanup",
"Response does not frame the task as a pure design-pattern catalog"
]
},
{
"id": 4,
"prompt": "Review this refactor PR and tell me whether it is safe to merge.",
"expected_output": "Routes primary ownership to code-review because the task is review judgment rather than planning or applying a refactor.",
"assertions": [
"Response mentions routing to code-review",
"Response distinguishes refactor planning from review judgment"
]
},
{
"id": 5,
"prompt": "Before we refactor anything, find every call site and wrapper around this old helper so we can see the blast radius.",
"expected_output": "Routes the primary task to codebase-search because the immediate need is symbol inventory / impact mapping rather than a cleanup brief.",
"assertions": [
"Response routes to codebase-search or explicitly says the task is impact mapping first",
"Response does not present a full refactor plan as the primary answer",
"Response keeps code-refactoring positioned as the behavior-preserving cleanup lane after the map exists"
]
}
]
}
Handoff Boundaries
Use code-refactoring only while the main task is structural improvement with behavior preservation.
Route to debugging
Use debugging when the unanswered question is:
- why the bug exists
- which recent change caused a regression
- how to reproduce or isolate the failure
- whether hidden runtime behavior still needs investigation before cleanup
Rule of thumb: if expected behavior is still unclear, diagnose first.
Route to code-review
Use code-review when the unanswered question is:
- is this diff ready to merge
- what comments should a reviewer leave
- which risks or missing evidence should block approval
- how to classify findings by severity
Rule of thumb: code-refactoring plans or applies cleanup; code-review judges the finished change.
Route to testing-strategies
Use testing-strategies when the unanswered question is:
- what test layers should exist for this area
- what merge/release gates are appropriate
- how much validation depth is needed across the org or repo
- how to manage flake policy, risk tiers, or environment coverage
Rule of thumb: code-refactoring chooses enough verification for one cleanup; testing-strategies designs the policy.
Route to performance-optimization
Use performance-optimization when the unanswered question is:
- where the bottleneck is
- what should be measured or profiled
- which latency, throughput, memory, or bundle tradeoffs matter most
- how to tune for speed rather than structure
Rule of thumb: if performance evidence drives the work, profiling owns the next step and refactoring becomes a follow-up.
Route to codebase-search
Use codebase-search when the next task is mostly inventory:
- find all call sites
- map ownership or import edges
- identify which modules or files use a pattern
- collect the raw impact set before designing the cleanup
Intake Packets and Route-outs
Use this note when the incoming request is ambiguous. Normalize the request into one packet before writing a cleanup plan.
Packet 1: Local cleanup
Use when the user has one file, function, component, service, script, or narrow module that is obviously too tangled.
Best fit
- Oversized handler / component
- Duplication between close variants
- Rename / extract / split cleanup
- Move side effects to a clearer edge
Output shape
- one primary cleanup goal
- one behavior guardrail
- two to four reviewable slices
- one short verification plan
Packet 2: Fragile legacy area
Use when the structure is messy and confidence in current behavior is weak.
Best fit
- hidden invariants
- weak or missing tests
- globals / side effects / mystery branches
- high fear of accidental regressions
Output shape
- freeze-first framing
- characterization examples or tests
- smallest safe seam
- strict warning against a heroic rewrite
Route-out
If the current behavior is still not understood well enough to define what must stay the same, send the diagnosis step to debugging before continuing.
Packet 3: Repeated migration / codemod
Use when the same change repeats across many files.
Best fit
- deprecated API replacement
- naming migration
- syntax modernization
- pattern rewrite across a directory or repo
Output shape
- source pattern
- target pattern
- known exceptions
- pilot subset
- repo-wide rollout guardrail
- rollback note
Route-out
If the main need is only to map symbols, files, or impact scope before choosing a transform, use codebase-search first.
Packet 4: Diff-shaping cleanup
Use when the code technically changed already, but the diff is too mixed or risky to review cleanly.
Best fit
- cleanup tangled with semantic behavior changes
- generated/mechanical edits mixed with hand-tuned changes
- hard-to-review rename + logic + test changes in one stack
Output shape
- split suggestion by commit or patch layer
- note which edits are mechanical vs semantic
- explicit review-risk note
- route review judgment to
code-review
Route-out ladder
Use these checks before claiming code-refactoring should own the whole task:
| If the main job is... | Route to... |
|---|---|
| Proving why behavior is wrong | debugging |
| Judging whether a specific diff is safe / merge-ready | code-review |
| Designing validation depth or gate policy | testing-strategies |
| Naming the bottleneck from traces, CWV, profiler output, or benchmarks | performance-optimization |
| Mapping symbols, call sites, wrappers, or blast radius | codebase-search |
Compact decision rule
- Known cleanup shape + behavior guardrail exists →
code-refactoring - Known cleanup shape + no trustworthy behavior definition yet →
debuggingfirst, thencode-refactoring - Known cleanup shape + only impact mapping is needed first →
codebase-searchfirst, thencode-refactoring - Cleanup request is actually about merge confidence →
code-review - Cleanup request is really a performance bottleneck complaint →
performance-optimization
Refactor Modes
Use one mode per request unless there is a clear staged handoff.
1. Local safe refactor
Choose this when the scope is narrow and tooling confidence is decent.
Typical signs:
- one oversized function or component
- duplicate helpers in one package
- confusing names or responsibility boundaries
- stable tests already exist
Preferred moves:
- rename
- extract method / helper / component
- move side effects to the edge
- consolidate duplicated branches
- split orchestration from pure logic
2. Behavior freeze first
Choose this when the code is fragile, legacy-heavy, or poorly understood.
Typical signs:
- weak test suite
- hidden invariants
- dynamic behavior the team does not fully trust
- history of regressions in this area
Preferred moves:
- capture characterization tests
- save before/after examples
- build a tiny reproduction surface
- refactor behind one seam at a time
3. Repetitive migration / codemod
Choose this when the same change must happen across many files or repos.
Typical signs:
- deprecated framework or SDK APIs
- broad renames or import-path changes
- policy-driven replacement of old patterns
- mechanical edits large enough to overload manual review
Preferred moves:
- define source/target patterns precisely
- test on a representative sample first
- decide between text replace, structural rewrite, or AST/codemod tooling
- separate mechanical transforms from semantic edge-case fixes
Selection heuristics
- If the user says "simplify this one thing", start with local safe refactor.
- If the user says "we do not trust this area", start with behavior freeze first.
- If the user says "same change everywhere", start with repetitive migration / codemod.
Safe Refactor Checklist
Use this before broad or risky cleanup.
Before editing
- State the structural problem in one sentence.
- Write down the intended behavior that must remain unchanged.
- Pick one refactor mode: local safe refactor, behavior freeze first, or repetitive migration / codemod.
- List existing safety signals: tests, typecheck, linter, screenshots, fixtures, golden outputs, or manual smoke steps.
- Decide what belongs in this diff versus a follow-up diff.
During the change
- Keep mechanical cleanup separate from semantic behavior changes when possible.
- Prefer a sequence of small diffs or commits over one giant rewrite.
- Check for hidden references in config, docs, generated files, serialized names, or string lookups.
- Stop and reframe if the task turns into bug diagnosis instead of cleanup.
Before saying it is done
- Re-run the chosen verification steps.
- Summarize what behavior was preserved and how you proved it.
- Name the risky edges that were checked explicitly.
- Call out what remains messy but intentionally untouched.
- Route the next step if review, debugging, testing policy, or profiling now owns the work.
Smells that should trigger caution
- giant rename touching code, docs, config, and generated files at once
- weak or flaky tests around the target area
- unclear expected behavior
- dynamic references or reflection-heavy code
- temptation to mix redesign with cleanup in the same pass
N:code-refactoring
D: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.
G:refactoring code-quality behavior-preservation cleanup codemod migration legacy-code technical-debt
U[5]:
messy function/component/service that needs structural cleanup
fragile legacy area that needs freeze-first cleanup
repeated API or naming migration across many files
cleanup-heavy diff that needs reshaping before review
requests to refactor, decompose, deduplicate, rename safely, or stage cleanup
S[5]{n,action}:
1,Start from the cleanup packet already available
2,Choose one primary refactor mode
3,Freeze the behavior guardrail
4,Build the smallest credible cleanup plan
5,Verify and route remaining work honestly
Related skills
FAQ
What refactor modes does this skill support?
local-safe-refactor, behavior-freeze-first, repetitive-migration-codemod, and diff-shaping-cleanup - one primary mode per run.
How does it keep behavior unchanged?
It makes the behavior guardrail explicit first - tests, typecheck, characterization tests, snapshots, or before/after tables - before broad edits.