Characterization tests before refactoring a production system
A refactor starts with a question: Which behavior does someone depend on? The answer often lives in production data and integration contracts as much as in the implementation. Write tests around those boundaries before changing the code.
Capture one workflow end to end
For a payment callback, start with an integration test that receives the same event twice. Assert the externally visible outcome: one payment state transition and one downstream effect. Run it against the existing implementation and confirm that its result matches the intended contract.
Test the states that survive retries
Include invalid input, an out-of-order event, and a retry after a partial failure when the integration supports those cases. Distinguish a behavior you intend to preserve from a defect that needs its own fix. When the old implementation disagrees with the contract, write down the desired behavior before changing it.
Move in small steps
Keep the new tests stable while moving code behind the same public boundary. If an AI agent helps with the refactor, give it the test commands, the permitted files, and a short statement of the invariants. Review the diff, run the integration suite, and watch the production signals tied to the changed workflow after release.