# Refactor old code with a coding agent: pin the behavior first

- Author: RomanMotion (https://wurk.fun/user/RomanMotion)
- Published: 2026-11-03
- Canonical (HTML): https://wurk.fun/blog/refactor-old-code-with-a-coding-agent-pin-the-behavior-first
- Cover image: https://ik.imagekit.io/wurk/browser-uploads/f1c626b5c17e7f0a61dfbbe7a20d85ae7b33a20527243aeec2ee1d0a8b87562a/bc30ba44-eb3c-410c-9d09-6f8be8f8c2d5/cover-refac.jpg?wurkUpload=v1.mP7-wUCgaGgs5tJuYWZ7Pr6FjhBRsl2Ju6ozTXzwujg

---

You’ve inherited a messy file and want your coding agent to clean it up. Without tests, a tidy-looking rewrite can quietly break a feature your client relies on. Characterization tests give you a baseline to check before and after each change.

Start by recording the existing behavior without changing the application code. Commit those tests on their own, then refactor in small, named steps, running the tests after each one. If a test fails, stop and find out why before continuing.

## The trap: “clean up this file”

Old code can be hard to read and still do important work. A function with repeated conditions might handle an unusual input that nobody remembers. A confusing default value might be used by another part of the app.

Ask an agent to “refactor this file” without a baseline, and it has to guess which details are accidental and which need to stay. The result may look cleaner, but you have little evidence that the app still behaves the same way.

A [characterization test](https://en.wikipedia.org/wiki/Characterization_test) records what existing code actually does for chosen inputs. It doesn’t declare that behavior correct. It gives you something to compare against when the code changes.

That includes odd behavior. If a function currently returns an empty string for a missing value, record that result if it matters to callers. Don’t silently change it to an error because the new version looks neater. You can decide whether to fix it later, with a separate change.

A passing set of tests covers the cases you wrote down, not every possible input. Your judgment still matters when choosing what to protect.

## Capture behavior before changing code

Ask the agent to inspect the target file and identify its observable behavior. That can include return values, errors, messages sent, and changes to stored data. A function may return the same value after a rewrite while producing a different side effect.

Start with inputs the app actually uses. Add relevant edge cases, such as empty values, missing fields, unusual formatting, and known failures. Use safe sample data rather than copying customer information into tests.

The agent should run the **existing implementation** to observe results, then write assertions against those results. It shouldn’t invent expected outputs from what it thinks the code ought to do. If a result is inconsistent or depends on a live service, have it explain that and make the test environment controlled where practical.

Use this prompt:

```
Inspect [file or function] and write characterization tests
for its current behavior. Do not change application code.

Use representative inputs, relevant edge cases, errors,
and observable side effects. Include known odd behavior
and bugs as they exist today.

Run the existing code to establish the expected results.
Do not guess outputs or change behavior to make a test pass.

Run the tests against the untouched code. Show the commands,
results, assumptions, and any behavior you could not test.
Stop for review before refactoring.
```

Review the assertions. A test that only checks “something was returned” may miss a meaningful change in the result.

## Commit the tests on their own

Run the new tests against the untouched application code. They should pass: their job is to describe what that code does today. If one fails, investigate the test, its setup, and the observed output before starting the refactor.

This differs from writing a failing test for a new feature or bug fix. In [test first, then let the agent code and prove it](https://wurk.fun/blog/test-first-then-let-the-agent-code-and-prove-it), the test describes behavior you want to add. A characterization test records behavior that is already present.

Check the diff before committing. The test changes should not hide application edits, weakened existing tests, or unrelated work. If test setup requires a configuration change, review it explicitly and make sure it doesn’t alter the behavior you’re recording.

Once the tests pass, commit the tests and necessary test setup separately from the refactor. A commit records the selected changes with a message, as described in the [Git commit documentation](https://git-scm.com/docs/git-commit). A clear message such as `test: characterize invoice formatting` makes the baseline easier to find.

Ask the agent to show the test command and result, not just say “green.” If it couldn’t run a test, record that gap and resolve it before relying on the baseline.

## Refactor in small, named steps

With the baseline saved, give the agent a narrow change: extract a function, rename a confusing variable, or remove a specific piece of duplication. Ask it to state the step before making it and explain why the observable behavior should remain the same.

After the step, run the characterization tests and the rest of the relevant suite. Review the diff and test output, then commit that step on its own. Repeat only after you have a passing result. Many small steps mean many short agent runs; if you’re choosing a plan for that rhythm, our referral link gives [10% off GLM coding plans](https://z.ai/subscribe?ic=R0K78RJKNW).

For example, extracting repeated formatting code into a helper is a reviewable step. Replacing the formatter, changing its defaults, and redesigning the screen around it in the same diff is much harder to assess.

Tell the agent not to edit or remove tests just to make them pass. A test may need correction, but that deserves an explanation and review separate from the refactor.

If you want a place to practice this loop, you can [try the zcode agent harness free](https://zcode.z.ai/invite/ALWM9JUA) through our invite and give it the same boundaries: small steps, visible results, and review before accepting changes.

Green tests are evidence for the cases they exercise, not a guarantee that nothing else changed. Look at the code, check important paths the tests don’t cover, and keep track of gaps the agent reports.

## When a test fails, stop and investigate

A failure is a signal to inspect, not permission to update the expected value. Read the failure output and compare it with the last passing step. The refactor may have changed behavior, but a setup problem or unreliable test can also cause a failure.

Ask the agent to show the relevant difference and explain its evidence. If the step accidentally changed behavior, undo or correct that step, then rerun the tests. Avoid piling another refactor on top while the failure is unresolved.

If the difference exposes an existing bug you actually want to fix, separate that decision from the cleanup. Return to a passing refactor baseline, describe the intended behavior, and make the bug fix in its own change with a test for the new result. Update any characterization test that recorded the old bug, with the change clearly explained.

Use this checklist for each step:

```
[ ] The step has a small, clear purpose
[ ] The diff contains only the intended change
[ ] Characterization tests pass
[ ] The relevant full suite passes
[ ] No test was weakened to get a pass
[ ] Failures and untested paths are explained
[ ] The passing step has its own commit
```

There is [more on our blog](https://jackgross-five.vercel.app) about keeping coding agents on a short leash.

If this guide helped you refactor with more confidence, you can leave a tip on WURK to support more practical posts.
