---
name: refactor-safely
description: Refactors code without changing behavior - lock current behavior with tests first, apply small mechanical steps, run tests after each, keep refactor commits separate from behavior changes, and stop when scope grows. Use when asked to clean up, restructure, rename or simplify code.
---

# Refactor Safely

A refactor changes structure, not behavior. The only proof that behavior is unchanged is a test that passed before and passes after. Work in steps small enough that a failure points to exactly one change.

## Workflow

1. Define the scope in one sentence: what is being restructured and why (for example "split `orders.py` into parsing and pricing"). List the files in scope. Anything outside is out of scope.
2. Check the starting state. The working tree should be clean or the user's unrelated changes noted. Run the full test suite and record the result. If tests already fail, tell the user and agree on the baseline before going on.
3. Lock behavior. For the code in scope, check whether tests cover what it does today. If coverage is thin, write characterization tests first: call the code with realistic and edge inputs and assert on the current output, even where the output looks odd. Commit these tests on their own.
4. Refactor in small mechanical steps. One kind of move per step:
   - rename a symbol (use the language server or a careful search of all references)
   - extract a function or module, with no logic edits
   - inline a trivial wrapper
   - move code between files
   - remove dead code confirmed unused by search and by the test run
   - replace duplication with one shared function
5. After every step: run the tests (or the affected subset, then the full suite at milestones), and the type checker or linter if the project has one. Commit when green (with the user's agreement given at the start), with a message in the repo's convention marked as a refactor (e.g. `refactor: ...` if the repo uses Conventional Commits).
6. If a step turns red, do not fix forward by editing the tests. Undo that step (`git restore` of the files you touched in this step; ask the user before discarding anything you cannot identify) and retry it in a smaller form.
7. Finish with a diff review: read the whole diff once looking for accidental behavior changes (changed defaults, reordered side effects, altered error types, swallowed exceptions).

## Rules

- Never mix a behavior change and a refactor in one commit. If you notice a bug while refactoring, note it, finish or pause the refactor, and fix the bug in a separate commit after asking the user.
- Public interfaces (exported functions, HTTP routes, CLI flags, database columns, file formats) stay the same unless the user explicitly asked to change them. If they must change, update every caller in the same step.
- Do not change formatting of untouched code. Run the formatter only on files you edit, and put a formatting-only change in its own commit.
- Prefer deleting code to adding abstractions. Do not introduce patterns, layers or generic helpers for a single use.
- Keep the diff reviewable: aim for commits under a few hundred changed lines.

## Characterization test example

When no tests exist, pin today's behavior, even if it looks odd:

```
def test_price_current_behavior():
    assert price(qty=0) == 0
    assert price(qty=3, coupon="X") == 25.5   # observed, not specified
    assert price(qty=-1) is None              # odd, but this is what it does today
```

Commit such tests first. Mention the odd cases to the user instead of fixing them during the refactor.

## Useful checks

```
git diff --stat          # is the change as small as you think?
git diff -w              # ignore whitespace to spot real edits
git grep -n "oldName"    # leftover references, including strings and configs
```

## Stop conditions

Pause and ask the user when:
- the scope grows beyond the files you listed, or more than about a dozen files need edits
- behavior cannot be pinned by tests (network, time, randomness) and you have no safe way to isolate it
- you find that two modules depend on each other in a cycle that needs a design decision
- tests are flaky, so a green run proves nothing
- the refactor needs a dependency upgrade or a migration

## Pitfalls

- "Just a rename" across string-based references (reflection, config keys, templates, SQL, JSON) that a compiler will not catch. Search for the old name as plain text too.
- Changing the order of operations with side effects while extracting a function.
- Deleting code that looks unused but is called dynamically or from outside the repo.
- Rewriting a test to make it pass.
- Declaring the refactor done without running the full suite.

## Report back

Scope, the starting test status, the list of commits (message and purpose), the final test result, behavior risks you checked, and any bugs or follow-ups you noticed but did not touch.

Source: [AnyModel skills catalog](https://anymodel.org/en/skills) · License: [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/)
