Safe refactors with AI agents on legacy code

Legacy refactors with agents go wrong when the model treats old code as a blank canvas.

Published 2026-11-09 · Translation: VI

Legacy refactors with agents go wrong when the model treats old code as a blank canvas. Safe refactors pin behavior with characterization tests, move in strangler steps, and forbid big-bang rewrites without proof. The trap is merging “cleaner” code that quietly dropped an implicit contract ops still depends on.

When agents may touch legacy

When this fits vs when it does not

When this fits vs when it does not

Hand the agent a seam: a module boundary where calls can redirect without changing external behavior. Do not ask for a full rewrite because a file “looks messy.” Related: Spec-driven agent workflow when the seam itself is still ambiguous.

Characterize → strangler → verify

Strangle

Strangle

  1. Find the seam and name the external behavior that must not change.
  2. Add characterization tests or golden fixtures, including ugly edge cases you wish did not exist.
  3. Implement one strangler step with dual paths briefly if needed and a written rollback.
  4. Compare outputs/metrics on the characterization suite before calling it done.
  5. Forbid drive-bys in rules: no framework swaps, no silent schema changes, no whole-package renames in the same PR as behavior moves.

Three traps that show up first

Failure modes to catch early

Failure modes to catch early

  • Blank-canvas rewrite. Everything at once. Fix: one seam, one step, path locks.
  • Deleted safety net. Characterization removed after the new code “looks fine.” Fix: keep the suite until dual-path retirement is a separate PR.
  • Feature smuggle. Behavior changes hide inside refactor noise. Fix: reject mixed PRs; features get their own ticket.

A one-week practice loop

Pick one legacy hot spot. Add characterization only this week. Next week: one strangler step with parity evidence in the PR. If the agent proposes a rewrite, answer with the seam and the suite, not enthusiasm.

Bottom line

Agents are eager rewriters. Legacy systems hide contracts in call sites, data, and ops scripts. Pin behavior, strangle in small steps, and refuse blank-canvas PRs. Pair with stop rules for agents when the rewrite urge turns into thrash.

Share

X Facebook LinkedIn
Educational content only. Rankings reflect stated criteria at the update date—not investment advice or permanent performance guarantees.