cd /news/ai-agents/ai-code-migration-security-how-to-le… · home › topics › ai-agents › article
[ARTICLE · art-157831] src=blog.stackademic.com ↗ pub= topic=ai-agents verified=true sentiment=· neutral

AI Code Migration Security: How to Let AI Rewrite Legacy Code Safely

A software engineering firm recommends four controls for AI-led legacy code migration: an implementation-ready specification written before any code is generated, characterization tests that capture existing system behavior, sandboxed autonomous coding agents on an isolated cloud VM with secrets held in Azure Key Vault, and risk-tiered AI code review. The firm cites a UK travel-sector legacy Perl system whose business rules were duplicated across booking and accounting layers as a case where blind AI migration would reproduce or break inconsistencies, and warns that the biggest CTO fear is AI silently dropping undocumented business logic — such as a 15-year-old refund rounding rule on part-cancelled bookings — rather than writing bad syntax. The firm says its entire engineering team uses Claude Code for all development, with agent sandboxing via Bubblewrap on Linux and Seatbelt on macOS plus network egress controls.

by read9 min views1 publishedOct 26, 2026

Here is an AI code migration story that should worry you more than any security breach headline.

The new system compiles. Every test passes. The demo goes beautifully. Three weeks after go-live, finance notices that refunds on part-cancelled bookings are being rounded differently than they were for the last fifteen years. Nobody changed that rule on purpose. Nobody even knew it existed. It lived inside a tangle of old code, and the migration quietly dropped it.

When CTOs talk to us about AI-led legacy modernisation, this is the fear they raise most. It is rarely “will the AI write bad syntax?” It is “will it silently break business logic that lives in undocumented code and hidden dependencies?” The security questions that follow, such as leaked source code, vulnerable output and an agent doing things nobody approved, are all real. But they sit on top of that first worry.

This post is about how we answer both. Our short version: AI can write most of a migration, but only inside a system of boundaries, checks and human accountability that someone designs and owns.

Before getting into controls, it helps to be fair about what each approach is good and bad at. AI-led migration is not simply a faster version of manual migration. It trades one set of risks for another.

A chatbot answers questions. An agent acts. It reads whole repositories, executes code, installs packages and calls tools. That is exactly what makes it useful for migrations, and exactly why it needs containment. The risks worth planning for are specific:

We build around four principles. None of them depends on the AI being perfect.

Principle 1: Specify before you generate

Agents do well inside clear boundaries and badly with ambiguity. So on a migration, the first deliverable is not code. It is an implementation-ready specification.

Take a legacy Perl system in the UK travel sector. Its business rules live in the code itself and are duplicated across the booking and accounting layers. An AI migrating that blind would either reproduce the inconsistencies or break them in new and creative ways. Our approach there is to start with a discovery phase whose output is a specification, and to send the client a short “current architecture: our understanding” document to correct before scope is fixed. If the client’s own engineers spot something we misread, we want to hear it before a single line is generated.

Then comes the most useful safety net in the whole process: characterization tests. These are tests that capture how the current system actually behaves, warts included, before anyone touches it. After migration, they let the AI prove that the new code behaves like the old. They are the bridge between “hidden business logic” and “AI-safe migration”.

Principle 2: Contain the agent with sandboxing

The agent works in a box, and the box has no keys to anything that matters.

• A dedicated, isolated cloud VM hosts the autonomous coding agents. It is reachable only over a private network, with no public exposure, OAuth on every agent endpoint and automatic shutdown outside working hours.

• No live or production credentials on development machines. Secrets live in a managed vault (Azure Key Vault) and never in .env files in the repository.

• The coding agent’s own sandbox mode is switched on. That means OS-level isolation (Bubblewrap on Linux, Seatbelt on macOS) plus network egress controls that block arbitrary sites.

The point of all three is the same. If a hidden instruction in some forgotten comment tells the agent to send data somewhere, there is nowhere for it to go and nothing valuable to send.

This is not theory for us. Our whole engineering team uses Claude Code for all development, so these controls are daily habits rather than slideware.

Principle 3: Risk-tier your AI code review

Treating every file as equally dangerous wastes effort. Treating them all as harmless is worse. So we classify code paths by risk and match the model and the review to the stakes.

Two details make this work. First, the reviewer is chosen from the actual diff, not the plan. A story labelled low-risk that ends up touching a sensitive file is escalated automatically. Second, before we trust the cheaper tier, a sample of its reviews is re-audited by the stronger model, to confirm nothing is slipping through.

Principle 4: Done means verified, with CI/CD security checks

Work is only accepted when automated tests pass and a reviewer, human or a stronger review model, has checked the actual diff. In practice that looks like this:

• A phased workflow (create, implement, gates, repair, review, integrate) based on the BMAD method, so every story passes the same checkpoints.

• Tests written alongside the code. A story counts as delivered only when its tests pass.

• Static analysis in CI, using tools like Semgrep, tuned for vulnerability patterns common in AI-generated code.

• A dedicated review agent for modules that handle sensitive data, such as the personal data of students on an education platform.

• Rules enforced in tooling, not in prompts. What the AI may touch and what needs approval are hard limits in permissions. A prompt is guidance. A permission is a control.

And one human rule sits above all the automation: never commit code you can’t explain. AI writes the first draft. Engineers own every line that ships.

There is a spectrum, and the right point on it depends on how sensitive your data is and what regulation applies.

Here is what the middle option typically gives a client:

For security-sensitive clients we also design a hybrid approach: a self-hosted local model handles everyday queries, and only complex work escalates to a Foundry-hosted model inside an isolated Azure environment. One honest caveat. Regulated targets such as Azure Government and GCC High do not always offer the same models and features as commercial Azure. We check current Microsoft documentation before designing around any specific capability, and you should insist that your partner does too. It matters more as the compliance bar rises: we are currently working on moving a US additive-manufacturing company’s manufacturing execution system to Azure Government and GCC High, with ITAR and SOC 2 readiness in scope, and there the AI workflow, the environments and the handover all have to meet the same standard as the destination.

Most migration work happens far from live systems, which is the point of the sandbox. But cutover, validation and day-two operations sometimes put AI assistants within reach of real data and real admin functions. When that happens, our approach is to treat the AI like a new, very fast, slightly over-eager colleague and give it exactly this much trust:

None of this assumes the AI will behave. It assumes the AI will occasionally be confused or manipulated, and makes sure that does not matter much.

Treat these as a pre-flight check. For each question, here is why it matters and what a good answer looks like.

A “no” or “not sure” is not a failure. It is simply where to start.

Security in an AI-led migration is a process, not a prompt. That is why we run our own AI workflow inside an ISO 27001-certified management system, and why we treat migration and modernisation as core work as a Microsoft Solutions Partner for App Modernization rather than a side experiment.

The interesting part is how unglamorous the answer turns out to be. Write the spec first. Build the box. Match the scrutiny to the risk. Verify everything. Keep a human accountable. If you are weighing a migration and want to talk through where to begin, a discovery conversation is a good place to start, and our application modernization page has more on how we work.

Related reading: AI agentic integration and our legacy application modernization case study*.*

1. Is it safe to let AI write an enterprise code migration? It can be, when the AI works inside a system someone designs and owns: a written specification, an isolated environment, risk-based review, automated gates and engineers who are accountable for every line that ships. Safety comes from that system, not from trusting the model.

2. What is the biggest risk in an AI-led migration? In our experience it is not bad syntax. It is silently broken business logic that lives in undocumented code and hidden dependencies. That is why we start with a specification and characterisation tests rather than code.

3. What are characterisation tests? Tests that capture how the current system actually behaves, before anything is migrated. After the migration, they let the AI prove that the new code behaves like the old, including the quirks nobody remembered.

4. How do you stop an AI agent from leaking code or secrets? The agent runs on an isolated cloud VM reachable only over a private network, with no production credentials on development machines. Secrets live in a managed vault such as Azure Key Vault, and the agent’s own sandbox mode blocks arbitrary network access. Where the model itself runs matters too, which is covered above.

5. What is prompt injection, and why does it matter for migrations? It is when hidden instructions in content the AI reads, such as a code comment or a document, try to redirect its behaviour. A migration agent reads an entire legacy codebase, so it has plenty of exposure. Containment, hard permission limits, runtime protections and injection testing before go-live all reduce the risk.

6. Will our source code be used to train AI models? That depends on where the model runs. When models are hosted in your own Azure environment on Microsoft Foundry, prompts and outputs stay in your tenant and are not used to train the underlying models. With a fully self-hosted setup, nothing leaves your premises at all.

7. Does all code get the same level of review? No. Lower-risk paths such as UI, reporting and configuration use a faster model. Higher-risk paths such as money calculations, identity and access, data contracts, infrastructure and CI/CD pipelines use the strongest model for both implementation and review. The reviewer is chosen from the actual diff, so a change that turns out to be sensitive is escalated automatically.

8. Can AI-assisted migration work in a fully offline or air-gapped environment? Yes. Our approach for clients whose systems never touch the internet is a self-hosted stack of open-weight models running on client-owned hardware. We also design hybrid setups, where a local model handles everyday queries and only complex work escalates to an isolated Azure environment.

9. Does AI replace human code review? No. Work is accepted only when automated tests pass and a reviewer, human or a stronger review model, has checked the actual diff. Our team rule is that nobody commits code they cannot explain.

10. Does this approach apply to government or regulated clouds? The principles do, and the AI workflow, environments and handover need to meet the same compliance bar as the destination. Model and feature availability can differ in clouds such as Azure Government and GCC High, so we check current Microsoft documentation before designing around any specific capability.

AI Code Migration Security: How to Let AI Rewrite Legacy Code Safely was originally published in Stackademic on Medium, where people are continuing the conversation by highlighting and responding to this story.

── more in #ai-agents 4 stories · sorted by recency
── more on @claude code 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/ai-code-migration-se…] indexed:0 read:9min 2026-10-26 · —