TLDR overview
- Legacy code refactoring uses AI agents to rapidly map architecture and generate automated test safety nets.
- Version control allows developers to treat large structural refactors as safe, disposable experiments.
- Human judgment and zero-trust verification prevent AI agents from eroding underlying system architecture.
- SonarQube retires technical debt agentically by verifying every automated code fix before production merge.
For twenty years, the case against refactoring a legacy system was an economic one, and it was hard to argue with.
A system needs to improve precisely because its structure makes every change harder. But understanding it, testing it, and reshaping it consume the same scarce engineering time that visible features need. Technical debt wins by default because the alternative always costs something today for a benefit that arrives later.
The rewrite promises escape but usually costs far more than expected, and incremental refactoring, though safer, is hard for teams to sustain under delivery pressure.
The economics behind that decision are now shifting. In episode 2 of The Next Commit podcast, Tim "Agile Otter" Ottinger discusses how agentic development changes what teams can afford to attempt on real legacy systems.
How do AI agents help with legacy code refactoring?
The expensive part of legacy work has always been the setup: figuring out what you are even looking at before you can touch it safely.
AI agents compress that setup dramatically. Ottinger points an architecture recovery tool at an unfamiliar codebase and lets it map the terrain: what deploys where, how the system is built, where the units and tests are, and what technology it rests on. From there he asks an agent to derive requirements from existing behavior and construct an initial safety net.
The result will not be perfect, but enough characterization and path coverage can make the first structural experiment a safe one. Ottinger reaches coverage that would once have taken days: "70 or 80% is a pretty good place to start," he says, "and now that's probably enough to do some refactoring."
Tests went through the same economic change. Legacy code often stays untested because a comprehensive safety net feels expensive, and modifying working code to make it testable feels dangerous. An agent can create a substantial first set of tests in minutes. That initial safety net is enough to start refactoring, and as the structure improves, the tests can be strengthened in turn.
Version control changes both the perceived risk and the practical cost of the experiment. A refactoring across hundreds of files does not have to survive just because the agent spent time on it, and if it does not improve the system, you abandon it and try something different.
As Ottinger puts it, "the agents make you not afraid to try…partly that's because there's git underneath them." Version control keeps an experiment from becoming a commitment.
The catch: Cheap experiments still need human judgment
Cheaper experiments don't eliminate the need for judgment—they simply shift its focus to deciding which changes are worth keeping. Agents tend to optimize for the smallest possible change that passes, a tendency Ottinger identifies as costly. They will openly acknowledge their own reasoning, saying "I made the most minimal change I could," while that minimal change quietly chips away at the underlying architecture.
The same instinct produces worse errors. When an agent is not grounded well, Ottinger says, "it'll start picking up things that are just coincidental duplication...and suggesting to refactor those out." The duplicated code was textually similar but represented different facts, so it should have stayed independent. Collapsing it was a defensible mechanical move that destroyed a distinction the code was carrying.
There is a second trap: truly cleaning the system. Ottinger employed the metaphor of Fibber McGee's closet. You can effectively clean one corner but then "everything is piled in there except for that one corner. Does that make the room better or worse?." Cleaning one isolated spot can reduce the coherence of the whole system. Refactoring has to be guided by a view of the wider system, not by whatever code the current ticket happens to expose.
Both failures share the same signature: the change looks right, passes a casual read, and would ship without objection. The speed that makes these experiments affordable is also the speed at which plausible mistakes accumulate faster than anyone can catch by hand.
Deciding which changes to keep
Deciding which agent-proposed changes are worth keeping starts with the developer, who understands the abstractions the code is meant to express. Verification is what confirms whether a change the team wants to keep is actually sound, since an agent has no concept of the intended design.
An AI agent reviewing its own refactoring shares its own blind spots, because AI cannot verify itself. Determining whether a change is sound requires independent, zero-trust, multilayered code verification across computational, reasoning-based, and runtime layers, so what one layer misses another catches.
This is where a cheap experiment becomes a change you can trust. Version control can make bad refactoring disposable, but only independent verification tells you whether the refactoring was bad in the first place, before it reaches production carrying a defect no one saw.
The code maintenance loop
Code verification does not stop at the merge. SonarQube with the SonarQube Remediation Agent runs the code maintenance loop, retiring backlog issues and technical debt agentically in the background over time. Each fix is re-verified against SonarQube's analysis engine through closed-loop verification and opened as a PR before it reaches human review, so only verified fixes reach production. Debt gets fixed, not just found.
This is what keeps the new economics durable. Agents perform best when they have a stable foundation to work from. A well-maintained codebase is one they can continue to reason about clearly—and that clarity is what makes each subsequent structural experiment faster and less costly.
The outcome shows up in the data, where Sonar users report 44% fewer AI-derived production outages and 24% lower AI-related vulnerability rates (State of Code survey).
How can teams start using AI agents to refactor legacy code safely?
The refactor you could never afford is now a few minutes away. That changes what teams can afford to attempt, and it raises the bar on what you verify.
- Review the architecture of the systems you have been avoiding with SonarQube's architecture analysis. Establishing structure is no longer the expensive part.
- Use an agent to wrap the existing code in tests before you change it. That safety net is what makes the first refactoring a safe one.
- Treat refactorings as disposable experiments protected by version control. The work does not have to survive just because an agent produced it.
- Never let the agent that proposed a change be the one that approves it. Independent verification is what catches the change that looks correct while eroding the design, and it is not a nicety to trade away under deadline.
- Verify against a view of the wider system, not just the code the current ticket exposes.
The old economics made technical debt the safe default. Agentic development changes that for teams equipped to tell which of an agent's improvements are real.
See how SonarQube's code maintenance loop retires technical debt agentically, with every fix validated through closed-loop verification before it reaches production.

