Refactor
Improve the structure of existing code without changing its observable behavior. Optimize for comprehension and maintainability, not fewer lines or personal style preferences.
Establish the contract
- Read the repository instructions and the code, tests, callers, and interfaces surrounding the requested scope.
- Define what must remain unchanged: public APIs, outputs, errors, side effects, ordering, persistence, performance-sensitive behavior, and compatibility boundaries.
- Use the user's stated scope. If none is stated, infer a narrow scope from the current task or diff; ask before treating the entire repository as the target.
- Separate intentional behavior changes from the refactor. Do not hide fixes or new features inside a behavior-preserving change.
Build a baseline
Run the smallest relevant tests, type checks, lint checks, or build before editing. Record pre-existing failures instead of attributing them to the refactor.
If important behavior lacks coverage, add characterization tests first. Capture what the code currently does, including surprising behavior. Flag suspected bugs rather than silently changing them or encoding a preferred result.
Choose worthwhile changes
Prioritize evidence-backed improvements such as:
- reducing deep nesting, mixed responsibilities, or difficult control flow;
- consolidating genuinely duplicated business logic;
- replacing misleading names with names that expose intent;
- removing abstractions that add indirection without a current purpose;
- removing code proven unreachable or unused;
- making boundaries and data flow easier to follow.
Preserve useful abstractions, explanatory comments, compatibility code, and apparent oddities until their purpose is understood. Follow local conventions rather than importing a new style.
Refactor incrementally
Make small, reviewable changes. Run focused validation after each meaningful step so a regression can be tied to a specific edit. Avoid unrelated cleanup and broad rewrites when a local change solves the problem.
For large mechanical transformations, prefer an auditable codemod or other deterministic method with spot checks over many manual edits.
Do not weaken types, error handling, security checks, or tests to make the refactor pass. Do not update behavior-defining tests unless the user has explicitly approved a contract change.
Verify and report
Re-run the baseline checks, then run broader checks proportional to the affected surface. Review the final diff for accidental API, schema, configuration, generated-file, or side-effect changes.
Report:
- the scope and behavior contract preserved;
- the structural improvements made;
- validation performed and its results;
- pre-existing failures, coverage gaps, or remaining risks.
If the work reveals a durable constraint, non-obvious dependency, important failed approach, or follow-up that a future conversation could otherwise lose, use the document skill to record it. Do not record routine refactoring details.