Allan Ramos
← Blog

Refactoring with AI without losing system intent

Ask a model to “clean this up” and it will. It may also erase a quirk that encodes a regulatory edge case or a performance trick paid for in production blood. Fluency is not understanding. Refactoring with AI is powerful when intent is fenced; dangerous when intent lives only in the heads of people who just left.

The goal of refactoring is to preserve behaviour while improving structure—or to change behaviour deliberately and visibly. AI is a strong pair for the mechanical moves. It is a weak guardian of unspoken purpose.

Anchor on behaviour

Characterize first: tests, contract checks, golden files, recorded traffic where lawful and practical. Then let AI propose structural moves inside that fence. Prefer small vertical slices over big-bang rewrites the model hallucinated as simple.

If you cannot describe the behaviour you must keep, you are not refactoring—you are rewriting under anaesthetic. Wake up before you cut.

Keep the story in the repo

Architecture decision records and domain glossaries are fuel for good AI assistance. Without them, the model invents a plausible history that never happened and “simplifies” away the compromise that made the system shippable.

Before a large assisted refactor, write a one-page intent brief: what must not change, what may change, known landmines, and the rollback plan. Paste that brief into the working context every session. Do not rely on chat memory across days.

Mechanical moves vs semantic moves

Safe mechanical moves: rename within a boundary, extract functions, reorganize files, update call sites to a new internal API with tests green. Risky semantic moves: changing concurrency, altering error handling, merging entities, removing validation “nobody uses.”

Route semantic moves through explicit human design. Let AI implement after the decision is recorded. Mixing both in one giant generated PR is how intent dies quietly.

Verify in production-like conditions

Unit greens are necessary and insufficient. Run contract tests against real dependencies in a controlled environment. Compare metrics that matter: latency, error codes, batch durations, memory. For data transformations, compare outputs on held-aside corpora.

When behaviour is probabilistic, refactor the deterministic shell first. Do not “clean” prompts and business rules in the same change set if you can avoid it.

Team habits

Make it normal to say what the assistant did and what you verified. Prefer reviewers who challenge intent loss over reviewers who only discuss style. Celebrate deletions of duplicate generated modules as much as new features.

Used this way, AI shortens the grind of refactoring without selling the system’s purpose for a tidier file tree.

How this plays out in delivery

In practice, the difference between a slide and an operable change is whether teams can point to owners, controls, and evidence under pressure. That pressure arrives as an incident, an audit question, a vendor outage, or a steering committee that wants to scale a demo. If those answers are improvisations, the feature was never production-ready—regardless of how polished the interface looked in a pilot.

Delivery leaders should therefore reserve explicit capacity for the boring work: contracts, runbooks, evaluation packs, fallback paths, and decision records. Boring work is what makes ambitious AI and platform change survivable. Skipping it to protect a velocity chart is how organizations repurchase the same programme every three years under a new name.

Questions worth asking in design review

Who owns the outcome after launch? What fails first when the dependency is slow or wrong? Which data classes are in motion, and under which policy? What would make us pause or roll back within an hour? What evidence will we examine weekly to know quality is holding?

If a proposal cannot answer those questions without hand-waving, keep the scope in a controlled experiment. Experiments are useful. Unowned production traffic is not an experiment—it is a risk acceptance you forgot to record.

Working habits that keep quality compounding

Write short decision records when you cross a boundary. Keep a living list of invariants for each critical capability. Review with a checklist that targets blast radius rather than style. Instrument silent failure modes, not only HTTP errors. Revisit model, prompt, and vendor changes with the same seriousness as database migrations.

None of these habits require a new framework brand. They require leadership attention and a refusal to confuse demos with operable systems. Teams that practice them can adopt assistants, agents, and new platforms without losing the enterprise plot.

A note on language and accountability

Replace slogans with operational nouns: capability, owner, control, fallback, evidence, exit. Language shapes governance. Teams that speak only in broad transformation slogans struggle to assign accountability. Teams that speak in capabilities can fund, staff, measure, and stop work when the evidence says stop.

Hold that vocabulary in architecture forums and programme boards. Over time it becomes the shared spine that lets software development absorb AI tools without fragmenting into disconnected experiments.

Closing

The through-line is simple: treat AI-related change as architecture and operations work, not as magic. Make ownership explicit, put uncertainty where blast radius is acceptable, measure what can silently fail, and refuse to scale what you cannot run. That discipline is how software organizations get durable value from new techniques instead of a temporary theatre of progress.

How this plays out in delivery

In practice, the difference between a slide and an operable change is whether teams can point to owners, controls, and evidence under pressure. That pressure arrives as an incident, an audit question, a vendor outage, or a steering committee that wants to scale a demo. If those answers are improvisations, the feature was never production-ready—regardless of how polished the interface looked in a pilot.

Delivery leaders should therefore reserve explicit capacity for the boring work: contracts, runbooks, evaluation packs, fallback paths, and decision records. Boring work is what makes ambitious AI and platform change survivable. Skipping it to protect a velocity chart is how organizations repurchase the same programme every three years under a new name.

Questions worth asking in design review

Who owns the outcome after launch? What fails first when the dependency is slow or wrong? Which data classes are in motion, and under which policy? What would make us pause or roll back within an hour? What evidence will we examine weekly to know quality is holding?

If a proposal cannot answer those questions without hand-waving, keep the scope in a controlled experiment. Experiments are useful. Unowned production traffic is not an experiment—it is a risk acceptance you forgot to record.

Working habits that keep quality compounding

Write short decision records when you cross a boundary. Keep a living list of invariants for each critical capability. Review with a checklist that targets blast radius rather than style. Instrument silent failure modes, not only HTTP errors. Revisit model, prompt, and vendor changes with the same seriousness as database migrations.

None of these habits require a new framework brand. They require leadership attention and a refusal to confuse demos with operable systems. Teams that practice them can adopt assistants, agents, and new platforms without losing the enterprise plot.

A note on language and accountability

Replace slogans with operational nouns: capability, owner, control, fallback, evidence, exit. Language shapes governance. Teams that speak only in broad transformation slogans struggle to assign accountability. Teams that speak in capabilities can fund, staff, measure, and stop work when the evidence says stop.

Hold that vocabulary in architecture forums and programme boards. Over time it becomes the shared spine that lets software development absorb AI tools without fragmenting into disconnected experiments.

Closing

The through-line is simple: treat AI-related change as architecture and operations work, not as magic. Make ownership explicit, put uncertainty where blast radius is acceptable, measure what can silently fail, and refuse to scale what you cannot run. That discipline is how software organizations get durable value from new techniques instead of a temporary theatre of progress.

A safe assisted refactor playbook

Characterize behaviour. Write or generate the intent brief. Choose a thin vertical slice. Generate the structural change. Run the suite. Compare metrics. Pair-review for intent loss. Merge. Delete the dead path. Repeat. Resist the urge to “just clean the whole package” in one weekend branch.

When the assistant proposes a large redesign, ask it to list assumptions. Then verify each assumption against ADRs and production knowledge. Discard confident nonsense early.

Domain language during refactors

Refactors are a prime moment to repair glossary drift—or to accidentally worsen it. Provide the canonical terms in the prompt context. Forbid silent renames of ubiquitous language without an ADR. A tidier class name that breaks ubiquitous language is not a win.

If you must rename, do it as an explicit step with translation windows and consumer communication. AI can execute the mechanical rename; humans own the semantic commit.

When not to use AI for the refactor

Concurrency redesigns, security-sensitive auth changes, and subtle numerical code often deserve hand crafting with assisted review rather than assisted authorship. Use the tool to explain and test, not to invent the core logic.

Judgment about when to put the tool down is a senior engineering skill. Teams that never put it down will eventually ship a fluent mistake.

Putting it into the operating rhythm

None of this sticks if it appears only in a one-off workshop. Put the checkpoints into existing forums: design authority, risk intake, sprint reviews, and operations reviews. Assign named owners. Review the same metrics until the behaviour becomes muscle memory. Tools change. Operating rhythm is how architecture survives tool change.

When you expand scope—new channel, new market, new model provider—re-run the same questions rather than assuming last quarter’s controls still fit. Scope expansion is where quiet regressions hide. A short re-certification beats a long incident report.

What good looks like after six months

You can name owners for each AI-touched capability. You can show evaluation trends and cost trends. You can pause a feature without heroics. Engineers can explain the boundaries without opening a chat history. Sponsors hear outcome language and evidence, not only model brand names. That is the standard. Aim for it deliberately.

Field notes from programmes that stuck

The programmes that keep their gains share a few unglamorous traits. They name a single accountable owner for each capability touched by AI or platform change. They keep a thin evidence pack current: what the feature does, which data it uses, how quality is measured, and how to pause it. They review cost and quality on a fixed weekly or biweekly cadence instead of waiting for a quarterly surprise.

They also refuse to expand scope while basic controls are missing. That refusal feels slow in the week it happens and fast in the year it saves. Sponsors accept it more readily when you offer a dated path: we can widen to segment B when override rates stay under threshold and fallback drills pass. Conditional speed is still speed—just adult speed.

Common failure modes to watch for

Eternal pilots that serve real customers without on-call. Prompt edits in production with no version history. Retrieval corpora that mix clearance levels. Success metrics that count messages sent instead of outcomes achieved. Architecture reviews that only admire diagrams after contracts are signed. Cleanup work that is always scheduled after this critical launch.

Each failure mode is preventable with a small control. The danger is not that teams cannot invent controls. The danger is that delivery pressure makes skipping them look rational until the incident report is written.

A ninety-day improvement plan

Days 1 to 30: inventory AI-touched journeys, owners, and gaps in logging, evaluation, and fallback. Publish the list without blame. Days 31 to 60: close the top three blast-radius gaps; stand up a short design-authority slot for new use cases; put cost alerts in place. Days 61 to 90: run one controlled promotion from pilot to production using a written exit report; kill or contain at least one unmanaged experiment.

At day ninety, present evidence trends rather than tool logos. Leaders can fund what they can see. Visibility is a prerequisite for sustained investment in quality.

How this article should change Monday morning

Pick one capability you touch. Write the owner, the invariant that must not break, the fallback if the AI dependency fails, and the metric you will check next week. Share it with the people who can correct you. Then make one concrete backlog item that turns a gap into a control.

Long articles do not improve estates. Changed operating habits do. Use this piece as a mirror, not as literature. If nothing in your plan of record moves after reading it, the reading did not count.