AST + LLM Automate Legacy Refactoring: Strangler Pattern Achieves 72% Decoupling Automation

AsiaInfo's AST-guided LLM agent automates legacy Java refactoring via strangler pattern, identifying leaf modules through static analysis, generating clean architecture code with sandbox-verified unit tests, and routing traffic gradually, achieving 72% decoupling automation and cutting regression faults from 4.8% to 0.3% in a 124k-line BSS module.

AsiaInfo Technology: New Tech Exploration
AsiaInfo Technology: New Tech Exploration
AsiaInfo Technology: New Tech Exploration
AST + LLM Automate Legacy Refactoring: Strangler Pattern Achieves 72% Decoupling Automation

Why Big-Bang Rewrite Fails for Large Legacy Systems

Large enterprise core systems (e.g., telecom BSS) accumulate technical debt over 10+ years of frequent changes. They exhibit three typical traits: highly coupled code logic with tangled cross-module calls and no clear layer boundaries; missing documentation and comments so business logic lives only in running code; and low unit-test coverage making changes like "walking a tightrope in a dark room," historically causing cross-module regressions.

A full rewrite (Big Bang Rewrite) carries even higher risk [1]; any missed implicit logic leads to delays or launch failures. Pure LLM-based large-scale rewriting also fails: LLMs suffer logical decay in ultra-long contexts and cannot perceive implicit global variables, producing hallucinations that break core business logic. Therefore, legacy refactoring must adopt "static analysis for boundaries + LLM local rewrite + strangler pattern gradual evolution."

Automated Closed Loop: Static Parsing → Leaf Identification → Agent Refactor → Sandbox Verification → Strangler Proxy Routing

2.1 AST Static Scan: Foundation for Precise Leaf Module & Dependency Boundary Identification

Refactoring starts not by changing code but by building a full dependency graph. Text search or LLM parsing cannot guarantee 100% dependency accuracy; Abstract Syntax Tree (AST) analysis is required.

For a 100k-line Java legacy codebase, a parsing engine extracts classes, methods, variables, and explicit/implicit interface calls to construct a global call directed graph G = (V, E). Dependency topological sorting and cycle breaking then identify leaf modules — nodes with non-zero in-degree but limited out-degree, or no external reverse calls. This step produces a full in/out-degree matrix for all modules, providing the basis for an inside-out refactoring sequence. Unlike heuristic text-similarity methods, AST parsing distinguishes same-name methods and overloaded calls, avoiding dependency-edge misjudgments.

AST static parsing dependency topology and leaf module identification diagram
AST static parsing dependency topology and leaf module identification diagram

Leaf modules are the innermost logic units. Using them as the refactoring entry point ensures each decoupling change has minimal controlled blast radius, preventing chain reactions.

2.2 Code Agent Local Refactoring + Sandbox Unit-Test Completion for Evolution Stability

After target leaf modules are identified, the code agent takes over refactoring tasks [2]. The process strictly follows Clean Architecture, peeling procedural code into standard Domain Model, Service Layer, and Infrastructure Layer.

To prevent agent-generated hallucinations from breaking existing logic, the AISWare TuringCoder engine implements a three-step closed loop:

Context Extraction & Contract Definition: Extract AST-identified leaf module source code and I/O data structures; the agent auto-extracts business contracts and generates interface definitions.

Code Refactoring & Auto Unit-Test Generation: The agent rewrites business logic per specification and simultaneously generates unit tests covering boundary conditions (nulls, exception branches, edge values).

Sandbox Isolation Run & Assertion Verification: Refactored code and tests are pushed to an isolated sandbox for compilation and execution. If assertions fail, compilation errors and stack traces are fed back to the agent for iterative repair until all tests pass.

Only when core-path coverage reaches 100% and overall unit-test coverage ≥ 85% with all assertions passing is the refactoring result marked ready.

100k-Line Module Real-World Data Validates Engineering Feasibility

The approach was validated on a telecom-grade core BSS order-processing module (~124k lines, Java). A Strangler Facade Router deployed at the front end performs transparent routing, switching traffic between the old monolith and the new microservice using a four-stage ladder strategy: 1% → 10% → 50% → 100% . The proxy layer includes millisecond-level auto-failover: if the new service's abnormal response rate exceeds 0.01%, traffic instantly cuts back to the old monolith, guaranteeing production HA. Before each traffic increase, unit tests and core-path regression suites serve as gate criteria; failure holds the current percentage.

Strangler pattern dynamic routing and gradual module strangulation architecture
Strangler pattern dynamic routing and gradual module strangulation architecture

Figure 4 compares traditional manual refactoring vs. the proposed "AST + Code Agent Automated Refactoring" across key metrics:

Core metrics comparison chart
Core metrics comparison chart

Data shows the automated mode simultaneously improves legacy decoupling and microservice extraction automation rates. High-coverage unit tests suppress regression fault rate to 0.3% (down from 4.8%). The decoupling automation rate reaches 72.0% .

Implicit Globals & Data-Layer Coupling Remain Manual Boundaries

Despite gains, deep coupling still requires human intervention [3]:

Shared Memory & Cross-Thread Implicit Dependencies: Legacy systems often use ThreadLocal, global static variables, or in-memory caches for context passing. AST captures static syntactic calls but cannot fully predict runtime race conditions under high concurrency.

Storage-Layer Strong Coupling & Distributed Transactions: When modules join on physical tables or share transactions, pure code-level strangling cannot resolve data-layer coupling. This demands database splitting plus SAGA distributed transaction patterns.

Future work: combine static AST analysis with runtime dynamic tracing (e.g., Java agents, eBPF) to build a "static syntax tree + dynamic call graph" dual-verification mechanism — the key to lower-risk automated legacy refactoring.

References

[1] Fowler M. Strangler Fig Application [EB/OL]. (2004-06-29) [2026-10-09]. https://martinfowler.com/bliki/StranglerFigApplication.html [2] Fowler M. Refactoring: improving the design of existing code [M/OL]. 2nd ed. Boston: Addison-Wesley Professional, 2018: 45-68. https://martinfowler.com/books/refactoring.html [3] Martinez S, Xu L, Elnaggar M, et al. Software refactoring research with large language models: A systematic literature review [J]. Journal of Systems and Software, 2025, 235: 112762. https://doi.org/10.1016/j.jss.2025.112762
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

ASTLLMgray releasetechnical debtunit test generationstrangler patternlegacy refactoringmicroservices migration
AsiaInfo Technology: New Tech Exploration
Written by

AsiaInfo Technology: New Tech Exploration

AsiaInfo's cutting‑edge ICT viewpoints and industry insights, featuring its latest technology and product case studies.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.