Safe Refactoring

AI

Restructure code without changing behavior. Use when asked to clean up, simplify, deduplicate, rename, or reorganize existing working code.

refactorcleanupmaintainability

Save this file as .agents/skills/safe-refactoring/SKILL.md in your repository.

Compatible with: Claude Code, GitHub Copilot, Cursor, Aider — any agent that reads SKILL.md-style instruction files.

---
name: safe-refactoring
description: Restructure code without changing behavior. Use when asked to clean up, simplify, deduplicate, rename, or reorganize existing working code.
---

# Safe Refactoring

Refactoring changes structure, never behavior. If behavior must change too, that is a separate commit.

## Ground rules

1. **Tests before moves.** If the code you are touching has no tests, write characterization tests first (lock in current behavior, including quirks). Do not refactor untested code blind.
2. **One transformation at a time.** Extract function, rename, move module, inline — each as its own step with tests run in between. Never stack five rewrites into one edit.
3. **Preserve public APIs** unless the task explicitly says otherwise. Check all call sites with `rg` before changing a signature.
4. **No scope creep.** Do not fix unrelated formatting, upgrade dependencies, or rename adjacent things. Note them, mention them, leave them.

## Procedure

1. Run the relevant test suite — it must be green before you start.
2. State the target structure in 2–3 sentences so the user can stop you if it is wrong.
3. Apply one transformation.
4. Run tests. Red? Undo that step, understand why, redo smaller.
5. Repeat until done, then run the full suite plus lint/typecheck.
6. Review the final diff yourself: `git diff` should show movement and renaming, not logic edits.

## Common safe transformations

- Extract function/component from a long body (copy the code verbatim, pass in what it uses)
- Rename with editor-wide rename or `rg -l old | xargs sed -i 's/old/new/g'` followed by import checks
- Move a module and update every import in the same commit
- Replace a conditional with a lookup table or early returns — only when branches map 1:1

## Report

- What was restructured and why it is more maintainable
- Proof behavior is unchanged: tests green before/after, diff summary
- Deliberately untouched issues you noticed

Related skills: writing-tests, code-review

Related commands: git add -p, npm test, git diff --stat

Related workflows: Ask an agent to refactor safely