Blog

How to refactor a legacy codebase with an AI agent, safely

A code diff with removed lines in red and added lines in green

Old code is where an agent saves the most time and where it can do the most harm. The difference is how you structure the work.

Where should I start?

With tests. If the code has none, ask the agent to write characterization tests: tests that record what the code does today, even when that behaviour looks odd. They are your safety net.

How big should each step be?

Small enough to review in a few minutes. Rename one module. Extract one function. Replace one deprecated call across the repository. Ask for a diff, not a rewrite, as in change the lines, do not reprint the file.

A safe loop

  1. Run the tests. They should pass before you start.
  2. Ask for one refactor and a short plan.
  3. Apply it, run the tests again.
  4. Commit. Then repeat.

Commit after every green step, as described in a safe Git workflow with an AI agent. If a step goes wrong, you lose minutes, not an afternoon.

What should I not hand over?

Decisions about the architecture itself. Let the agent do the mechanical changes while you decide the direction.

Install Toknary and try it on one small module first.

Keep reading

Try Toknary freeAll guides