// walkthrough · 2026-09-28

Refactoring legacy code with an AI agent: where the tool proves itself or fails.

A large codebase. No tests. Inconsistent style. Functions that do five things each. You have two options: spend a month refactoring by hand, or point an AI agent at it and let it suggest changes. The problem is knowing when the agent is right and when it is confidently wrong. Here is how to use an agent effectively for legacy refactors, where the stakes are high and a bad rewrite breaks production.

// the short version

  • Legacy refactors are high-risk — the agent cannot always tell if a change is safe, and revert costs time.
  • Start with characterization tests before touching anything — lock down the current behavior, then change with confidence.
  • Staged diffs are non-negotiable — let the agent refactor one function at a time, one logical change per diff, so humans can review.
  • Agents often make silent assumptions (deleting "dead" code that is actually used via reflection, removing error handling that looks unnecessary but isn't).
  • Know where to stop — big architectural decisions (splitting modules, changing APIs) should stay human. Refactoring should be mechanical.

Why legacy refactors break even with good agents

Legacy code is hard because it is full of unspoken contracts. A function looks pointless until you realize it is called from two places via reflection. An exception catch looks paranoid until you see the comment from 2015 that says "this happens in production every other Thursday." A variable looks unused until a runtime debug session shows it is set by a third-party library that modifies the module namespace.

Agents read the code. They see no tests, no comments explaining the quirks, no running history of why something is there. They see a function that could be deleted, or logic that could be simplified, and they recommend the change confidently. Often they are right. Sometimes production breaks at 2 AM.

An agent cannot know if code is "dead" or "used in ways that aren't textually obvious." You have to lock that down first.

Step 1: Characterization tests — before you change anything

Before the agent touches a line, write tests that capture the current behavior exactly as it is. Do not write tests for the behavior you want. Write tests that say: "This function, with these inputs, produces exactly this output — for better or worse."

tartarus · ~/lab
$ tartarus
› write characterization tests for payment_processor.py. run the current code with sample invoices, capture every output (including errors), and generate tests that pin that behavior exactly
# agent generates 50 test cases…
✓ wrote test_payment_processor.py (120 lines)
  fixtures cover: valid invoices, missing fields, edge amounts, double charges, timezone quirks
  all 50 tests pass against current code

The tests are not pretty. They include behaviors that are probably bugs. That is fine. The point is: any refactor that breaks a characterization test has changed the external behavior. You catch it immediately, and you revert.

Step 2: Staged, reviewable diffs — not one giant rewrite

Once the characterization tests are in place, you can refactor confidently. But do not ask the agent for a complete rewrite. Ask for one logical change per diff:

tartarus · ~/lab
$ tartarus
› refactor payment_processor.py: extract the invoice validation logic into its own function. make one focused change. keep all other code exactly the same
✓ done. refactored extract_invoice_validation()
  … [shows diff] …
# 
$ pytest test_payment_processor.py
✓ all 50 tests pass

Then move to the next change:

tartarus · ~/lab
$ tartarus
› next: rename the amount_cents variable to amount_in_cents for clarity. one change only
✓ done. renamed variable everywhere in the function
# 
$ pytest test_payment_processor.py
✓ all 50 tests pass

This is tedious. It takes longer than one massive refactor. But every step is reviewable, testable, and revertible. If something breaks, you know exactly which change did it.

Step 3: Where the agent should stop — and where you make the call

Agents are good at mechanical refactors: extracting functions, renaming variables, removing duplicate logic, reordering code. They are bad at architectural decisions: splitting a module into two, changing the public API, moving responsibility between classes.

When the agent suggests a big structural change, you have two options: (1) accept it and run a full integration test suite to make sure nothing broke in ways the characterization tests do not catch, or (2) tell the agent to stop and make that decision yourself. For most legacy refactors, option 2 is the right call. The agent is a tool for mechanical work. The strategy is yours.

Common failure modes — what to watch for

Even with characterization tests and staged diffs, agents make predictable mistakes:

  • → "Dead" code that isn't dead. A function with no callers in the repo. The agent deletes it. But it is part of the public API, and an external user relies on it. The test suite does not catch this because there are no internal tests for the public API surface.
  • → Reflection and metaprogramming. Code that uses getattr(), setattr(), or __getattribute__() is often brittle. The agent sees a variable that is set but never read, and does not realize it is set by reflection. Deleting it breaks at runtime.
  • → "Unnecessary" error handling. An exception that has not been raised in 5 years of logs. The agent says it is dead code. But it handles the one edge case that happens once a quarter, and deleting it means 4 times a year, something fails with no safety net.
  • → Silent semantic changes. Reordering operations that look independent. Moving a print statement, removing a temporary variable, inlining a function. Each change looks safe. Cumulatively, they change the timing or side effects in ways the tests do not catch.

The full workflow: a concrete example

Here is how a real legacy refactor looks from start to finish:

  1. 1. You have a 2000-line payment module that is a mess. No tests.
  2. 2. You ask the agent to write characterization tests for the main entry points. It generates 100+ tests that cover edge cases you did not think of. All pass against the current code.
  3. 3. You ask the agent to extract the validation logic into its own function. One focused change. Diff is 40 lines. Tests still pass.
  4. 4. You ask the agent to rename variables for clarity. 15-line diff. Tests still pass.
  5. 5. The agent suggests moving the database logic into a separate layer. You decide that is an architectural change — you will make that decision yourself. The agent does not touch it.
  6. 6. You ask the agent to simplify the error handling in the validation function. It removes some redundant try/catches. Tests still pass. You review the diff and approve it.
  7. 7. After 10 staged changes, the module is cleaner, better structured, and 100% of the characterization tests still pass. You have a revert point at every step.

// legacy code made manageable

An agent that refactors under your control.

A CLI coding agent that works in staged, reviewable diffs, with /undo and /redo to roll back changes. It can still be wrong, so keep your tests and review in the loop. Plans from $20/mo.

See plans →