AI-Assisted Legacy Code Refactoring: How One Engineer Turned 100K Lines into 300K+ Over Six Months
This article walks through a real-world, six-month legacy refactoring in which a single experienced engineer transformed roughly 100,000 lines of legacy code into a new system of 300,000–400,000 lines while using an AI coding assistant as a productivity lever. It reconstructs the project timeline month by month and breaks down the practices that made the effort sustainable: context engineering, quality gates, task orchestration, code-growth review, and a cost-benefit analysis of the roughly $200/month subscription. Readers will find reusable guidance for running large-scale, AI-assisted refactoring of both monoliths and multi-service distributed systems—without turning AI-generated speed into unsustainable technical debt.
Introduction: What surfaces when you push AI to its limit
A software engineer with seven years of production-grade web development experience completed a large-scale refactoring solo over six months. He reshaped roughly 100,000 lines of legacy code into a new system on the order of 300,000–400,000 lines. The AI coding assistant he relied on cost about $200 per month (around 1,400 RMB). Looking back, he admitted his initial timeline was too aggressive, joking that he “may have shaved five years off my life.”
Stories like this resonate. They carry the drama of “one person carrying an entire project” and the quiet warning that “the stronger the tool, the easier it is to overdraw yourself.” If we stop at amazement, we miss the most valuable part: once code output is dramatically amplified, which engineering steps need to be redesigned, and which risks must be defended against in advance.
So this article does not debate which tool is better. Instead, it abstracts the experience into a more general question: with AI deeply involved, how do you complete a large-scale legacy refactoring and convert raw speed into something sustainable, deliverable, and maintainable? The lessons apply equally to a monolith running in the cloud or on-premises and to a distributed system split into multiple microservices.
1. Project background: a “legacy” revived by AI
1. A senior engineer who embraced AI
The engineer had long been responsible for production web applications. When the AI wave arrived, he proactively brought intelligent coding assistants and reasoning models into daily development—accelerating new feature work, quickly producing demos, and even integrating related capabilities into the company’s product. That advantage also landed him the role of an “AI advisor” within the team.
His starting point, he stressed, was not fear of being replaced but a view of AI as a capability amplifier. That judgment shaped how he used it: treating AI as a team member that needs to be onboarded and coached, rather than a black box that generates everything from a single sentence.
2. A legacy system with tangled origins
The target had originally been written by an intern, and the code itself was derived from another project this engineer had built while interning seven years earlier. Two generations of “beginner code” stacked together, plus a steady pile of ad hoc requirements layered on top ever since—the system’s quality was, predictably, poor. Such projects are common in practice, with recurring traits like:
- Missing architectural intent: module boundaries drift with business needs, and the same concept may carry several names across different files.
- Types reduced to decoration: loose types “bypass” the compiler, so errors only surface at runtime.
- Duplication and copy-paste: similar logic is pasted repeatedly, forcing the same change to be made in many places.
- Implicit coupling: heavy reliance on global state, string-based conventions, or execution order, with no explicit contracts.
- Docs and tests lagging: understanding the system means “reading code plus asking the author,” and regression checks are almost entirely manual clicks.
3. Making a promise
To get the project approved, he promised management that he would single-handedly complete the entire redesign and refactoring within a few months. He knew it meant intense overtime, and he knew that once the goal was set, there was no easy turning back.
Comparing the promise to the outcome, the experience illustrates at least two points:
- Estimates must be measured in “refactoring,” not “rewriting.” Refactoring has to preserve external behavior, and its hidden cost is often several times that of building from scratch.
- AI can sharply cut the cost of “implementation,” but it cannot replace requirement clarification, architectural decisions, or acceptance judgment. Whether it takes weeks or months depends on whether those steps are handled up front—not on how fast the tool runs.
2. Reconstructing the timeline: what six months of refactoring involved
Following a typical practice arc, the process breaks into six stages. Stages can overlap; focus on each stage’s goal, key actions, and the way work was gated.
| Stage | Core goal | Key actions | AI’s role | Human gatekeeping |
|---|---|---|---|---|
| Month 1 | Understand the current state | Freeze the run/build environment, map dependencies, analyze hotspots, capture a behavior baseline | Generate module maps and code summaries | Confirm the baseline truly reflects production behavior |
| Month 2 | Build the guardrails | Add tests for critical paths, tighten types, set collaboration conventions and code gates | Bulk-generate tests and type definitions | Verify test assertions reflect intended behavior |
| Month 3 | Establish the architecture | Domain partitioning, boundary definition, consolidating shared capabilities | Produce design drafts and alternatives | Make architecture decisions, assess migration cost |
| Months 4–5 | Bulk migration | Migrate in vertical slices, fill in tests and docs, merge continuously in small steps | Primary code generation and rewriting | Review block by block, run full regression |
| Month 6 | Finalize and harden | Remove old code, run performance and security checks, wire up monitoring, document lessons | Generate cleanup lists and docs | Release decision and risk confirmation |
1. Month 1: understand the current state, establish a “behavior baseline”
The first step of refactoring is not writing code, but making the system “understandable, runnable, and verifiable.” The core deliverables are three lists:
- Dependency list: runtime and build tool versions, dependencies and their licenses, and whether any are unmaintained or have known vulnerabilities.
- Hotspot list: the modules that change most often, have the highest cyclomatic complexity, and are most deeply coupled to core business flows.
- Interface list: externally exposed interfaces, their callers, and contracts that must not change casually.
At the same time, capture a “behavior baseline”: the inputs, outputs, and side effects (which data was written, which external calls were triggered) of key business flows—ideally drawn from a desensitized sample of real production traffic.
At this stage, AI is best cast as a “reader”: traversing directory structures, summarizing module responsibilities, explaining unfamiliar code, and producing an initial module map. One lesson is worth keeping in mind: every conclusion AI offers should be traceable to a location in the code; any description that cannot be located should be treated as information still to be verified.
2. Month 2: build the guardrails before touching existing code
Letting AI modify a legacy system with no tests is like building on quicksand. This stage focuses on putting “guardrails” in place:
- Critical-path tests: prioritize core flows like ordering, payment, and login, plus branches that historically caused incidents.
- Type tightening: eliminate loose types and type suppressions in batches so errors surface at compile time.
- Collaboration conventions: pin down the tech stack, directory structure, coding style, and prohibitions for both AI and humans to follow.
- Automated gates: integrate type checks, static analysis, unit tests, and the build into the CI pipeline.
This stage may look like “no feature output,” but it actually determines whether AI can run at high speed afterward. The faster AI generates code, the more valuable automated verification becomes: the more reliable the checks, the more work people dare to hand to AI.
3. Month 3: use AI to help establish the architecture
Before bulk migration, you must define the system’s “skeleton.” First have AI generate a module dependency graph from the existing code, then set boundaries around domain partitioning. Three common splitting strategies:
- By business capability, such as users, orders, inventory, and settlement;
- By change frequency, isolating the parts that change often from the stable core;
- By data ownership, giving each module a clear data boundary.
For each option, AI should list pros and cons, migration cost, and risk, with a human making the final call. Architecture decisions can draw on AI to widen the range of ideas, but their consequences cannot be outsourced to AI. This stage’s output becomes the “architecture contract” that every subsequent conversation references.
4. Months 4–5: the main phase of bulk migration
This is where code volume grows most, and where AI’s value is most visible. Three principles apply:
- Advance in vertical slices: convert one end-to-end loop at a time—for example, “switch a given page from the old service to the new one while keeping a rollback switch”—so each step can be verified and rolled back independently.
- Run old and new in parallel during the transition: use an adapter layer or feature flags so both implementations coexist for a while, ramp up traffic gradually, then retire the old code.
- Small, frequent merges: keep each change within roughly a hundred or two hundred lines to lower review and debugging cost.
5. Month 6: finalize and harden
The final stage often decides success or failure and needs four priorities:
- Remove old code: delete once it’s confirmed there are no callers, avoiding two sets of logic coexisting long-term.
- Security hardening: check input validation, access control, key management, and sensitive data—especially edge-case handling that AI-generated code may have missed.
- Observability: add logs, metrics, and alerts for core paths so the new system is “visible and traceable” after launch.
- Documentation: capture the architecture decisions, conventions, and pitfalls from this refactoring for the team to reuse.
3. Context engineering: it sets the ceiling on AI output quality
If the six months yield only one core lesson, it is this: the quality of AI output depends heavily on the quality of the context you provide. The same model can produce wildly different results for “refactor this file for me” versus a structured task specification.
1. Give AI a “project collaboration agreement”
Keep a collaboration-agreement file in the repository root and make it the “default common sense” for every AI session. The example below can be tuned to your project:
# AI Collaboration Agreement (excerpt)## Tech Stack- Backend: Node.js + TypeScript (strict mode)- No new `any` or type-suppression comments; if unavoidable, document the reason## Directory & Layering- Business logic lives in src/modules/<domain>/; each module must include: interface definitions, implementation, tests- Cross-module access to another module's internal implementation is forbidden; call only through module entry points## Coding Style- Public functions must have JSDoc stating purpose, parameters, and exceptions- No copy-paste duplication; abstract when the same logic appears a third time## Workflow- Read the relevant module and its tests before making changes- Commit message format: <type>(<scope>): <subject>- Keep each change under 300 lines by default; explain if it must exceed that## Self-Check List- [ ] New or changed code has corresponding tests- [ ] No new external dependencies introduced (request approval first if needed)- [ ] Logs do not print sensitive information
The agreement file should be version-controlled and revised as the project evolves. It is both AI’s “onboarding handbook” and the team’s single source of truth for engineering standards.
2. Assemble context dynamically per task
Project-level conventions handle “general rules,” but each specific task still needs precise additions:
- Relevant code: the directly involved files and shared modules they call;
- Interface contracts: request and response data structures and error-code conventions;
- Data models: the database table structures and indexes involved;
- Constraints: performance requirements, compatibility requirements, and parts that must not change;
- Reference examples: existing implementations of similar features so AI “writes in the house style.”
A useful order is “outside-in, converging layer by layer”: state background and goals first, then constraints and references, and finally the specific task and acceptance criteria.
3. Replace vague instructions with structured templates
Rewriting a vague instruction into a structured prompt delivers immediate results. For example, replace “make this interface a bit better” with:
[Background]This is a legacy interface in the order module, missing input validation and unified error handling.[Task]Enhance the createOrder method in orderController.ts:1. Input parameter validation (use the project's existing validation library);2. Unified business exception handling (follow the style in src/modules/user/errors.ts);3. Unit tests covering three scenarios: success, missing parameters, insufficient stock.[Constraints]- Do not change the route registration; do not add dependencies;- Keep the return structure unchanged; reuse existing error codes;- Use the Given-When-Then structure for tests.[Acceptance Criteria]- Type checks and unit tests all pass;- Test coverage for all three scenarios reaches 100%.
A structured prompt has three ingredients:
- Clear task boundaries: AI needs to know what to do—and, just as important, what not to do;
- Executable acceptance criteria: humans and AI share the same understanding of “done”;
- Traceable references: AI learns style from the project’s existing code instead of inventing on its own.
4. Manage the “context budget”
A model can only process so much at once, and piling in irrelevant information dilutes what matters. Common context problems and responses:
| Problem | Symptom | Response |
|---|---|---|
| Context overload | Many unrelated files are fed in and AI loses the point | Provide only directly relevant files; split sessions per task |
| Context gap | AI guesses interfaces or fields and hallucinates | Add interface definitions and data models; require it to search before answering |
| Stale context | Files have changed but AI still reasons from an old version | Re-sync relevant files after each change |
| Context pollution | Wrong intermediate conclusions leak into the conversation | Once confirmed, capture conclusions into the agreement or design docs promptly |
4. Quality gates: a mechanism for building trust under high AI throughput
There is often a hidden gap between “looks correct” and “is actually correct” in AI-generated code. Building layered gates is essentially using automation to lower the human cost of trust.
1. Static checks: the first line of defense
Type checking and static analysis catch many problems without running the code—type mismatches, unused variables, unhandled nulls, potential resource leaks. More importantly, they are the most reliable feedback signal for AI self-checking: if the build fails, the change is not yet complete.
In practice, the collaboration agreement can require AI to “make type checks and static analysis report zero errors before submitting,” along with the commands to run, so it can repeatedly correct itself during self-verification.
2. Testing: telling “looks right” from “is right”
Testing AI-generated code needs extra care:
- Tests must be independent of implementation: define the expected behavior first, then have AI write the implementation, so tests don’t become a “freeze-frame” of wrong behavior.
- Cover edge cases: nulls, overlong inputs, concurrency, and duplicate submissions are the parts AI most easily overlooks.
- Change coverage: look not only at overall coverage but at whether line coverage of this specific change meets the bar.
A practical approach is “tests first, implementation second”: a human writes failing test cases that describe the expected behavior, then AI completes the implementation until all tests pass.
3. Runtime verification and gradual rollout
Integration problems that unit tests can’t cover must be verified in a more realistic environment—containerized integration tests, API contract tests, and end-to-end smoke tests. For a web application, page rendering, interaction flows, and access control should all be within the regression scope.
Releases then follow a progressive strategy:
- First deploy to a staging environment and watch core metrics;
- Then roll out to a small share of users, with feature flags for instant rollback;
- Finally, ramp to full volume.
Logs, metrics, and distributed tracing should run throughout. If the new system misbehaves, you can pinpoint the specific module quickly instead of searching for a needle across “two sets of code.”
4. Diff review: focus on the “unexpected” in AI changes
When humans review AI-generated diffs, it helps to watch for four kinds of issues:
- Over-modification: editing unrelated files or reformatting large blocks while completing the task;
- Defensive bloat: layer upon layer of fallbacks, pointless exception catching, and repeated validation that make the code heavier;
- Reinventing the wheel: reimplementing something a project utility already provides;
- Security risks: string-concatenated SQL, sensitive data in logs, missing permission checks.
This checklist can be embedded in your code host’s merge-request template to steer reviewers:
## AI Change Review Checklist- [ ] Change scope matches the task description, no unrelated edits- [ ] No redundant defensive code or empty exception handling- [ ] Existing project utilities and components are reused where possible- [ ] Input validation, access control, and sensitive data handling comply with standards- [ ] New dependencies are approved and license-compatible
5. Task orchestration: splitting a big project into tasks AI can “digest”
Refactoring projects often fail not because AI lacks capability but because task granularity doesn’t match. A single instruction spanning tens of thousands of lines exceeds both the context window and the scope verifiable in one delivery.
1. Break tasks into layers
A three-level breakdown works well in practice:
- Epic: for example, “migrate the order module from the old architecture to the new one”;
- Task: for example, “add validation and exception handling to the create-order interface”;
- Subtask: for example, “define the request parameter structure, write the validation function, add unit tests.”
Only a description that reaches subtask level works as effective AI input. A good task description should let a colleague unfamiliar with the project complete and verify the work independently.
2. Balancing batch processing with human involvement
Some work suits batch processing by AI because the pattern is fixed and verification is cheap:
- Completing and narrowing type definitions;
- Generating interface docs and comments;
- Drafting unit-test skeletons;
- Identifying and merging duplicate logic;
- Checking references before deleting old code.
Other work must be human-led, with AI only assisting:
- Domain modeling and data structure design;
- Cross-module interface-contract changes;
- Performance-critical-path optimization;
- Security and permission logic;
- Production changes and rollback decisions.
3. Iteration cadence: closing the loop between AI and automated tests
An efficient rhythm is a “generate, verify, correct” loop:
- Describe the task and bound its scope;
- AI generates the change;
- Automatically run type checks, static analysis, and tests;
- Feed failure information back to AI and ask it to locate and fix the problem;
- A human reviews the diff and merges.
The key: feed the verification failure back to AI completely and verbatim, without “translating” or summarizing it yourself. Error stacks, failed assertions, and actual output are the most direct clues for AI to fix issues.
6. Code growth: a rational look behind the rising line count
From about 100,000 lines to 300,000–400,000, code volume grew two- to threefold. That doesn’t necessarily mean quality dropped. Legacy systems often sacrifice readability to “save characters,” and the type definitions, test code, interface docs, and error handling added during refactoring are themselves a sign of engineering quality. Still, it’s worth watching for increments that aren’t real value:
- Defensive redundancy: fallbacks for cases that can’t happen, and repeated validation of normal flows.
- Duplicate implementations: the same feature “reinvented” multiple times, forcing synchronized edits during maintenance.
- Over-abstraction: designing many extension points up front for “requirements that may come someday,” which only raises the cost of understanding.
- Comments drifting from code: the code changes but the comments don’t, misleading whoever comes next.
For engineering teams, code volume directly affects reading and review cost, and thus long-term maintainability. A few constraints help in practice:
- Set a cap on lines changed per commit, requiring justification to exceed it;
- Run duplicate-code detection tools on a regular scan;
- Make “deletability” a review dimension: can newly added code be cleanly removed in the future?
Code is both a liability and an asset; the difference is whether anyone is willing to maintain it. This is exactly the perspective AI-era refactoring needs to stress.
7. Risk checklist: traps easy to overlook in AI-assisted refactoring
| Risk | Typical symptom | Mitigation |
|---|---|---|
| Hallucination | Calling nonexistent APIs, inventing config options | Require citations to real files and line numbers; validate with build and tests |
| Dependency sprawl | Frequently pulling in unfamiliar small packages | Require approval for new dependencies; assess maintenance status and vulnerabilities |
| Security holes | SQL concatenation, missing permissions, hardcoded keys | Put security scanning in the pipeline; manage sensitive data through a dedicated secrets service |
| Data leakage | Pasting production data or keys into the chat | Define data classification and desensitization rules; never send sensitive content out |
| License compliance | Generated code includes snippets under restrictive licenses | Run similarity checks on key modules; keep generation records |
| Single point of dependency | Only one person knows the AI workflow | Persist conventions, templates, and scripts in the repository |
| Team pacing imbalance | Output speeds up but review becomes the bottleneck | Control merge granularity; allocate review capacity sensibly |
The most underrated is “team pacing imbalance.” When code output multiplies while review and verification still depend on serial human work, pending changes pile up fast and delivery cycles actually lengthen. The fix isn’t reviewing faster—it’s moving as much verification as possible into automation, so human review focuses only on design and logic.
8. Cost and benefit: is a ~$200/month subscription worth it?
The roughly $200 per month in subscription fees looks like an extra expense, but it needs to be weighed against the whole ledger. Break the cost of AI-assisted refactoring into four parts:
- Direct cost: subscription and inference-call fees;
- Verification cost: infrastructure like automated testing, code-host pipelines, and integration-test environments;
- Human cost: requirement clarification, architecture design, and code review;
- Trial-and-error cost: rework, rollbacks, and incident handling.
A quick way to judge: if code output scales to roughly three or four times the original while total hours don’t grow proportionally, AI is acting as a lever; if total hours balloon too, a bottleneck exists in the process, and verification and review should be optimized first.
Over a longer horizon, the refactoring’s benefits are also substantial:
- Manual processes automated: many steps that once depended on manual work now run automatically, directly saving business time;
- Long-deferred optimizations delivered: typing, test coverage, and documentation—“things we always wanted to do but never had time for”—finally got done;
- Team capability upgraded: a reusable AI collaboration method emerged, so knowledge no longer lives only in one person’s head.
9. Human–AI boundary: turning “five years off my life” into “five more years of work”
The developer’s joke about shaving five years off his life points to a serious question: once AI drives down the cost of implementation, the real constraint shifts from “can it be written” to “how long can human energy, attention, and judgment hold up.” That yields a division of labor:
| AI is better suited to | Humans must lead |
|---|---|
| Pattern-based code generation and rewriting | Requirement prioritization and scope definition |
| Writing tests, docs, and comments | Domain modeling and architecture decisions |
| Explaining code and analyzing impact | Cross-team coordination and risk calls |
| Repetitive refactoring and bulk cleanup | Release and rollback decisions |
| Providing options and comparative analysis | Final acceptance and ownership |
Three practical principles follow:
- Let AI handle high-volume, pattern-based work; let humans handle low-volume, high-stakes judgment;
- Give control of pace back to humans: use iteration rhythm, merge frequency, and rest mechanisms to push back on the “the faster the tool, the more exhausted the human” dynamic;
- Stay honest about commitments: include verification, review, and rework time in estimates, not just the time to generate code.
10. Recommendations for teams
For teams that want to reproduce this kind of practice, a roadmap looks like this:
- Build the guardrails first: before bringing AI in deeply, complete type checks, static analysis, and critical-path tests.
- Then set the standards: form a project collaboration agreement and task templates so everyone works with AI the same way.
- Then control the pace: cap the size of a single change and center review on design and logic.
- Keep optimizing: regularly review prompt templates, task decomposition, and gate rules, and turn what works into institutional practice.
- Make good use of cloud infrastructure: general capabilities like cloud development environments, code-hosting and pipeline services, container platforms, and logging and alerting can be combined. On a cloud platform such as Baidu AI Cloud, for instance, code hosting, continuous integration, containerized deployment, and observability are typically available together, giving AI-generated code an integrated verification path from commit to release.
Conclusion
Six months, 300,000–400,000 lines, a ~$200/month subscription—the numbers themselves aren’t the point. The takeaways worth keeping are:
- AI is a productivity lever, not a replacement: what it amplifies is human judgment and engineering discipline;
- Context quality determines output quality: structured collaboration agreements and task descriptions are more reliable than any “magic prompt”;
- Automated verification is the precondition for fast iteration: AI-assisted coding without gates just accumulates technical debt faster;
- Refactoring must hold behavior unchanged as the baseline: small steps, gradual rollout, and always-reversible changes;
- A sustainable pace is the real long-term play: freeing people from repetitive labor, not turning them into “meat-based review machines” for AI.
Tools will keep getting stronger, but what decides a project’s fate is always how people organize work, set boundaries, and take responsibility. Using AI well isn’t about shaving five years off your life—it’s about doing more genuinely valuable work in the same amount of time.
