<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Lakshyabengani on Medium]]></title>
        <description><![CDATA[Stories by Lakshyabengani on Medium]]></description>
        <link>https://medium.com/@lakshyabengani14?source=rss-343c20d22080------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*b2svala4rhbApfP1</url>
            <title>Stories by Lakshyabengani on Medium</title>
            <link>https://medium.com/@lakshyabengani14?source=rss-343c20d22080------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 08:41:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lakshyabengani14/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Stop Migrating Code Manually— Build an AI Agent to Do It For You]]></title>
            <link>https://medium.com/@lakshyabengani14/stop-migrating-code-manually-build-an-ai-agent-to-do-it-for-you-95260842c05f?source=rss-343c20d22080------2</link>
            <guid isPermaLink="false">https://medium.com/p/95260842c05f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Lakshyabengani]]></dc:creator>
            <pubDate>Sat, 07 Mar 2026 14:25:55 GMT</pubDate>
            <atom:updated>2026-03-07T14:25:55.778Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Every engineering team dreads the words: <em>“We need to upgrade.”</em></blockquote><p>Maybe it’s <strong>Kotlin 1.x</strong> to <strong>2.0, </strong>or<strong> Spring Boot 2 to 3, </strong>or <strong>Java 11 to 21</strong>. Whatever the target, the story is always the same — hundreds of files to touch, APIs that changed quietly between versions, test suites that break in mysterious ways, and a dependency graph that feels like it was designed to punish you.</p><p>Most teams handle this manually. A senior developer sits down for two weeks, combs through change-logs, bumps versions one by one, fixes compile errors in a loop, and hopes nothing slips through. It works, but it doesn’t scale.</p><blockquote><strong><em>What if an AI agent could do this for you?</em></strong></blockquote><p>Not a chatbot you paste code into one file at a time. A structured, multi-phase pipeline that clones your repo, understands your project, upgrades your platform and dependencies, rewrites your source code, runs your build, fixes what breaks, and hands you a clean diff at the end.</p><p>That’s exactly what I built. In this post, I’ll walk you through the architecture, the design decisions, and the lessons learned — so you can build your own AI-powered migration agent for any use case.</p><h3>The One Rule That Makes It Work</h3><p>Before we look at any code, let me share the single most important design principle:</p><p><strong><em>Deterministic first. AI only where needed.</em></strong></p><p>This is the foundation everything else is built on. Here’s what it means in practice:</p><p><strong>Deterministic operations</strong> are things you can do without any AI at all — reading build files, parsing dependency versions, compiling the code and classifying compiler errors. These produce facts, not opinions.</p><p><strong>AI-assisted operations</strong> are things that require judgment — deciding how to rewrite a source file when an API changes, choosing a compatible dependency version when there’s no explicit rule, planning which files need migration, and proposing fixes when compilation fails.</p><p>The mistake most people make when building AI agents is letting the AI do everything. The AI picks the version. The AI reads the file system. The AI decides what to compile. This leads to hallucinated dependency versions, invented API signatures, and silent breakages that you discover weeks later in production.</p><p>Instead, I used deterministic tools to collect facts, and AI agents to reason over those facts. The AI never touches the file system directly. It never resolves versions. It never decides whether something compiled. It only receives structured data and returns structured responses.</p><p>Here’s what this split looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d1gr0jo7q18WJk9QTw2gkw.png" /></figure><p>This split gives you the best of both worlds: the reliability of deterministic tooling and the flexibility of AI reasoning — without the chaos of letting an LLM run unsupervised.</p><h3>The Architecture: Three Layers</h3><p>The system has three layers, each with a clear responsibility:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oitpuo8XL9IKSVT9U4FRDA.png" /></figure><p><strong>The CLI layer</strong> is thin — it parses command-line arguments using Click, loads the right migration plugin, and hands everything to the controller.</p><p><strong>The controller layer</strong> is the brain. It sequences the pipeline phases, passes state between agents, handles retries, and makes control-flow decisions (should I abort? should I retry? should I skip?). Critically, <em>it never performs reasoning itself</em>. It doesn’t decide how to rewrite a file or which version to pick. It just coordinates.</p><p><strong>The agent layer</strong> is where the actual work happens. Each agent has a single responsibility and a clear boundary on what it can and cannot do.</p><p>Here’s what the controller’s main run() method looks like — notice how it&#39;s just a sequence of phase calls:</p><pre>def run(self) -&gt; bool:<br>    try:<br>        self._phase_workspace_setup()<br>        self._load_release_notes()<br>        self._phase_platform_migration()<br>        self._phase_public_dep_resolution()<br>        self._phase_external_stabilization()<br>        self._phase_internal_dep_resolution()<br>        self._phase_code_migration()<br>        self._phase_verification()<br>        self._phase_diff_output()<br>    except PipelineAbort as e:<br>        self.logger.step_fail(f&quot;Pipeline aborted: {e}&quot;)<br>        self._save_state()<br>        return False<br>    <br>    self.state.finished_at = datetime.now(timezone.utc).isoformat()<br>    self._save_state()<br>    return self.state.tests_passing</pre><p>No conditionals. No AI reasoning. Just phases executed in order. This makes the system predictable and easy to debug.</p><h3>The Plugin System: Separating “What” from “How”</h3><p>One of the most important design decisions is separating the <em>migration definition</em> from the <em>migration engine</em>. The engine (controller + agents) handles <strong>how</strong> to migrate. Plugins define <strong>what</strong> to migrate.</p><p>Here’s the plugin interface:</p><pre>class MigrationPlugin(ABC):<br><br>    @property<br>    def name(self) -&gt; str: ...           # &quot;spring3&quot;<br><br>    @property<br>    def description(self) -&gt; str: ...    # &quot;Migrate Spring Boot 2.x to 3.x&quot;<br><br>    @property<br>    def target_platform_version(self) -&gt; str: ...  # &quot;3.3.5&quot;<br><br>    def platform_updates(self) -&gt; list[PlatformUpdate]: ...<br>    def dependency_rules(self) -&gt; list[DependencyRule]: ...<br>    def release_notes_sources(self) -&gt; list[ReleaseNoteSource]: ...<br>    def fallback_context(self) -&gt; str: ...<br>    def validation_tasks(self) -&gt; list[str]: ...</pre><p>A plugin provides five things:</p><ol><li><strong>Platform updates- </strong>version bumps to apply (e.g., “Spring Boot 2.x → 3.3.5”, “Java 8–16 → 17”)</li><li><strong>Dependency rules- </strong>which dependencies to remove, replace, or pin to specific versions</li><li><strong>Release note sources- U</strong>RLs to official migration guides (fetched at runtime, not hardcoded)</li><li><strong>Fallback context- </strong>2–3 sentence summary of critical changes, used only when URL fetching fails</li><li><strong>Validation tasks-</strong> tasks to run for verification (e.g., compileJava, test)</li></ol><p><strong><em>Why this matters?</em></strong></p><p>Adding a new migration is three steps — create the plugin file, register it in the plugin registry, and add it to the CLI choices. The entire pipeline, all agents, logging, and diff generation work automatically. You never touch the engine.</p><pre># Plugin registry — that&#39;s it<br>_REGISTRY = {<br>    &quot;kotlin17&quot;: Kotlin17Plugin,<br>    &quot;kotlin2&quot;:  Kotlin2Plugin,<br>    &quot;java21&quot;:   Java21Plugin,<br>    &quot;spring3&quot;:  Spring3Plugin,<br>    &quot;jakarta&quot;:  JakartaPlugin,<br>}</pre><p>This pattern is transferable far beyond migrations. Any time you have a <em>process</em> that stays the same but the <em>specifics</em> change — database schema upgrades, API version bumps, infrastructure-as-code migrations — a plugin system lets you scale without duplicating logic.</p><h3>The Pipeline: Step by Step</h3><p>When you run the CLI, the controller executes phases in strict order. Here’s the full flow at a glance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eqOijUK9ANct0A0R1QxR0Q.png" /></figure><h3>Phase 1–2: Setup and Platform Migration</h3><p>The tool clones your repo onto an isolated branch (upgrade/spring3) — nothing is ever pushed to a remote. Then a deterministic ScannerAgent reads every build file to extract the project&#39;s current state (build tool, language versions, all dependencies). The AI rewrites build files with the plugin&#39;s platform changes (e.g., Spring Boot 2.x to 3.3.5, Java to 17).</p><p>The controller also fetches official migration guides from URLs declared by the plugin (e.g., the Spring Boot 3.0 Migration Guide). These are cached to disk and passed to AI agents as context throughout the pipeline. If fetching fails, the plugin’s short fallback_context() is used instead.</p><h3>Phase 3: Dependency Resolution</h3><p>Plugin rules drive explicit changes first (remove javax.servlet-api, replace with jakarta.servlet-api). For dependencies without rules, an AI CompatibilityResolver recommends versions — but every recommendation is validated against Maven Central&#39;s actual published versions ( for cases like Java / Kotlin upgrades ) . If the LLM suggests a version that doesn&#39;t exist, it&#39;s rejected.</p><p><strong>Additional guardrails keep things safe</strong>: Spring Boot starters can’t accidentally get Spring Framework version numbers, related dependency families are aligned to the same version, and BOM-managed deps keep their managed status.</p><p>After rewriting the build file, a <strong>compile-validate-recompile safety loop</strong> runs automatically:</p><pre>def _run_build_file_safety_loop(self, verifier, full_path, dependency_changes, context_label):<br>    &quot;&quot;&quot;Mandatory loop: compile -&gt; validate -&gt; recompile.&quot;&quot;&quot;<br>    compile_result = verifier.compile()<br>    gradle_output = (compile_result.stdout or &quot;&quot;) + &quot;\n&quot; + (compile_result.stderr or &quot;&quot;)<br>    build_content = full_path.read_text()<br>    self._validate_and_fix_build_file(<br>        full_path, build_content, dependency_changes,<br>        gradle_compile_output=gradle_output,<br>    )<br>    return verifier.compile()</pre><blockquote>Every build file mutation goes through this loop. No exceptions.</blockquote><h3>Phase 4: Stabilization and Code Migration</h3><p>This is where the bulk of the work happens, in three sub-steps:</p><ol><li><strong>Deterministic import fixing</strong> — The ImportResolver compiles and, for broken imports, searches class-path JARs to find the correct path (e.g., javax.servlet becomes jakarta.servlet). No AI needed.</li><li><strong>AI code rewriting</strong> — For files affected by changed dependencies, the CodeGeneratorAgent rewrites them using migration instructions, release notes, and compile errors as context. Source files go first, then test files — because tests depend on source signatures that may have just changed.</li><li><strong>Repair loop</strong> — If compilation still fails, the RepairAgent proposes minimal fixes based on the actual compiler output. Up to 3 attempts.</li></ol><h3>Phase 5 (Optional): Private Dependency Resolution</h3><blockquote>Only relevant if your organization has a private artifact store (S3, Artifactory, etc.). Open-source and individual repos skip this automatically.</blockquote><p>Same pattern as public dependency resolution — list versions, pick the highest compatible one, run the safety loop — just against a different registry.</p><h3>Phase 6: Verification and Output</h3><p>The full build runs: compile, compile tests, run tests. If anything fails, the RepairAgent gets the compiler output, affected files, and context from the migration, then returns structured fixes:</p><pre>{<br>  &quot;fixes&quot;: [<br>    {<br>      &quot;file&quot;: &quot;src/main/kotlin/com/example/Service.kt&quot;,<br>      &quot;original&quot;: &quot;import javax.persistence.Entity&quot;,<br>      &quot;replacement&quot;: &quot;import jakarta.persistence.Entity&quot;,<br>      &quot;reason&quot;: &quot;javax.persistence moved to jakarta.persistence&quot;<br>    }<br>  ]<br>}</pre><p>The retry loop is bounded to 3 attempts — enough for straightforward issues; anything harder needs a human. Once the build passes (or retries are exhausted), all changes are committed locally and a unified diff is saved to .agent/patches/migration.diff. The output is a reviewable patch, not a black-box transformation.</p><h3>How the AI Agents Actually Work</h3><p>The AI agents in this system are not chatbots. They’re <strong>constrained decision engines</strong>. Three design pillars make them reliable:</p><h3>1. Runtime Context from Official Sources</h3><p>Instead of hardcoding migration knowledge into prompts (which goes stale), the tool fetches official release notes and migration guides at runtime:</p><pre>def release_notes_sources(self) -&gt; list[ReleaseNoteSource]:<br>    return [<br>        ReleaseNoteSource(<br>            url=&quot;https://github.com/spring-projects/spring-boot/wiki/&quot;<br>                &quot;Spring-Boot-3.0-Migration-Guide&quot;,<br>            label=&quot;Spring Boot 3.0 Migration Guide&quot;,<br>        ),<br>    ]</pre><p>These docs are fetched once, cached to disk, and passed to every AI agent as context. This means the agent always reasons over up-to-date documentation without needing prompt changes or retraining.</p><h3>2. Hard Constraints in Prompts</h3><p>The system prompts are long and specific. They don’t say “rewrite this file.” They say “rewrite this file, and here are 15 rules you must follow.” Here’s a representative excerpt from the code generator’s system prompt:</p><pre>You are a Kotlin/Java migration assistant. Rewrite the given file<br>to apply the requested changes.<br>Return ONLY the complete file contents — no explanations, no markdown fences.<br><br>CRITICAL: Never change the language of a file. A .java file must<br>remain valid Java. A .kt file must remain valid Kotlin.<br><br>METHOD/SIGNATURE STABILITY (CRITICAL):<br>- Do NOT rename existing methods, constructors, classes, or fields<br>  unless the instructions explicitly require it.<br>- Preserve public API and cross-file call contracts.<br><br>IMPORT ACCURACY (CRITICAL):<br>- Do NOT replace an existing import with a &quot;new-looking&quot; variant<br>  unless that exact symbol is confirmed by context or compile errors.<br>- Never guess import symbol names. If unsure, keep the existing import.</pre><p>These constraints emerged from real failures. Without the “never change language” rule, the LLM would sometimes convert a .java file to Kotlin file. Without the &quot;never rename methods&quot; rule, it would &quot;improve&quot; method names and break every call site in other files.</p><h3>3. Post-LLM Validation and Sanitization</h3><p>Even with the best prompts, LLMs make mistakes. So every AI output goes through deterministic post-processing.</p><p><strong>For source files</strong>, the system removes known-invalid imports that LLMs commonly hallucinate.</p><p><strong>For build files</strong>, the system reverts unsolicited Spring Boot starter version changes and deduplicates dependency entries.</p><p><strong>For dependency versions</strong>, every LLM recommendation is checked against the list of actually-published versions from Maven Central.</p><p>This three-layer approach — runtime context, hard prompt constraints, and post-LLM validation — is what makes the AI reliable enough for production use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ts5bhU0ob31o6JT6Ot5vMw.png" /></figure><h3>Conclusion</h3><p>The core idea behind this entire system is simple: let deterministic tools collect facts, let AI reason over those facts, and always verify what the AI produces. That principle — combined with a plugin system that separates <em>what</em> to migrate from <em>how</em> to migrate, and an orchestrator that enforces phase boundaries, failure classification, and bounded retries — is what turns a fragile LLM experiment into a reliable automation tool.</p><p><em>This pattern isn’t limited to code migrations. The same architecture — scan, plan, transform, validate — applies equally well to database schema upgrades, API version bumps, infrastructure-as-code updates, or any large-scale codebase transformation where you need AI’s flexibility but can’t afford its unpredictability.</em></p><blockquote>The best AI agents aren’t the ones that do everything autonomously. They’re the ones with the right guardrails to be trusted.</blockquote><p><em>If you found this useful, feel free to share it with your friends or drop a comment. I’d love to hear what you’d build an agent for.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95260842c05f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>