The Cost of Rewriting 300,000 Lines of Code in Six Months With AI

    This article examines a real-world case in which an engineer attempted to rewrite a legacy application of roughly 100,000 lines in six months using AI coding tools, only to see the codebase grow to 300,000–400,000 lines. It explains why AI-assisted refactoring tends to inflate code volume, how context engineering and explicit repository constraints improve output quality, how to break large refactors into small verifiable tasks, and which automated quality gates and cost controls keep AI-generated code maintainable. Readers will learn how to capture the productivity gains of generative coding without trading away engineering quality or personal health.

    1. Background: A Technical Debt Specimen and an Aggressive Promise

    An engineer with seven years of production web development experience took over an internal application with an extremely heavy legacy burden. The code had originally been written by an intern and was later derived from an even earlier intern project. Layer upon layer had been added on top of it, leaving the structure chaotic, the boundaries blurred, and duplicate implementations everywhere. The original codebase was about 100,000 lines.

    He saw this as a refactoring opportunity worth investing in: once finished, a large number of manual hand-off steps could be automated, and the team could save a considerable amount of time. To secure resources and approval, he made a very aggressive promise — he would complete the redesign and the full refactor alone within six months.

    Six months later, the codebase had grown from about 100,000 lines to somewhere between 300,000 and 400,000 lines. His own conclusion was that the schedule had been overly optimistic, that the process had pushed the tools’ capabilities to their limit, and that it had pushed his own energy to the edge of collapse. Using this kind of AI coding capability cost him about $200 per month in subscription fees.

    The value of this case is not the show of skill. It exposes two things at the same time: large-scale AI-assisted refactoring really can raise the output ceiling of a single developer significantly; but without engineering constraints, that output quickly turns into a new maintenance burden.

    2. Why Code Volume Balloons: The Entropy Trap in Refactoring

    Going from 100,000 lines to 300,000 lines usually does not mean requirements tripled. It is a typical side effect of generative tools operating without constraints:

    • Duplicate implementations: the same logic is generated repeatedly in different sessions, with slight variations, and nobody dares to delete any of it.
    • Over-abstraction: models tend to reserve extension points “for possible future needs,” producing large numbers of empty shells and pass-through layers.
    • Defensive redundancy: try/catch blocks, parameter fallbacks, and type assertions pile up just to pass validation.
    • Style drift: naming, directory organization, and error handling are inconsistent across different batches of generated code.
    • Comment and test inflation: documentation and test cases are code assets too, so they inflate the volume in step with everything else.

    The standard for judging whether a refactor succeeded has never been line count; it is whether the cost of change went down. So any AI-assisted refactor must first define a “measurable convergence target,” for example build time, average API response time, defect density, duplicate code rate, or the average number of files changed per requirement.

    3. The Core of Using AI Coding Tools Well: Context Engineering

    What really determines output quality is not the model itself but the context you feed it. What works in practice is turning “implicit knowledge” into explicit assets inside the repository:

    1. Project contract document: stack versions, directory responsibilities, naming conventions, error code conventions, commit conventions.
    2. Architecture decision records: why this layering was chosen, which patterns are forbidden.
    3. An executable constraint checklist: no new dependencies, no cross-layer direct calls, all logging and configuration must go through the shared entry points.
    4. Task context packages: feed only the files and interface definitions relevant to the current task, instead of stuffing in the whole repository.

    A sample project constraint file can look like this:

    1. # Engineering constraints (read before every task)
    2. - Layering: handler -> service -> repository; cross-layer calls are forbidden
    3. - Dependencies: no new third-party libraries; prefer the standard library
    4. - Errors: use AppError consistently; never throw bare strings
    5. - Logging: structured logging; no console output
    6. - Tests: every service method needs at least one happy-path and one error-path case
    7. - Change scope: no more than 8 files changed per task

    Combined with automated checks in the repository, the model’s output can be held on the right track:

    1. # Pre-commit gate example
    2. npm run lint
    3. npm run typecheck
    4. npm run test -- --coverage
    5. npm run build

    4. Task Breakdown: Make AI Do Small, Verifiable Work

    The most common reason large refactors fail is describing the task in overly grand terms. A reusable breakdown order is:

    • Establish a baseline: first fill in the build, static checks, tests, and monitoring alerts, so any regression is detected immediately.
    • Advance by vertical slices: refactor one complete business flow at a time (entry point, service, storage, tests) instead of horizontally replacing all files of the same kind.
    • Add tests before changing the implementation: use characterization tests to lock in existing behavior, then let the tool replace the implementation inside that safety net.
    • Small parallel batches: hand independent slices to parallel sessions, but enforce a shared constraint file and shared type definitions.
    • Converge daily: code generated that day must pass the gates and be merged that day, to avoid a pile-up of “generated debt.”

    A typical task instruction should be verifiable, for example: “Without changing existing interface signatures, consolidate storage access in the order query flow into the repository layer, add three error-path test cases, change no more than six files, and make all checks pass.”

    5. Quality Gates: AI Output Must Be Held to a Stricter Standard Than Human Code

    Once generation speed increases, review becomes the new bottleneck. A workable strategy is to shift review earlier by automating it:

    • The type system as the first line of defense: enable strict mode, forbid implicit any and overuse of type assertions.
    • Static analysis and complexity thresholds: cap function length and cyclomatic complexity to suppress redundant branches directly.
    • Duplication detection: run similarity scans on new code to block “copy-style generation.”
    • Change size limits: set an upper bound on lines changed per merge, and force a split when exceeded.
    • Observability built in: logging, metrics, and monitoring alerts cover critical paths so anomalies can be located quickly.
    • Dependency and artifact governance: build outputs go into a single artifact repository, and configuration and secrets are delivered through a secret management service rather than committed to the codebase.

    It is worth stressing that the focus of human review should shift from “reading every line” to “reviewing design, boundaries, and data consistency” — the part models find hardest to replace.

    6. Cost and Pace: Do the Math on $200 a Month

    With a subscription used at high intensity, the cost is not just the monthly fee; it also includes rework, context preparation, and review time. Ways to control cost include:

    • Use high-tier quota only for high-value tasks, and leave boilerplate code and formatting to the automated toolchain.
    • Reuse the accumulated constraint files and prompt templates to reduce the cost of repeated explanation.
    • Set a daily usage cap and mandatory offline periods to avoid “the more you use it, the messier it gets.”
    • Shorten the feedback loop with caching and incremental builds; the faster the feedback, the less rework.

    7. The Price and the Limits: Don’t Copy the “Five Years Off My Life” Pace

    In the case, the author joked that he might have shortened his life by five years. That deserves to be taken seriously. Months of continuous high-intensity delivery bring sleep deprivation, scattered attention, and degraded judgment — and judgment is exactly the capability that matters most when driving generative tools. A sustainable approach is to change the commitment from “a few months” to “deliverable milestones,” with something demonstrable every two weeks; to cut the refactor scope into stages and automate the highest-return flows first; and to keep fixed windows for retrospectives and rest.

    If an organization needs elastic compute and complete engineering support, this can usually be carried by the general capabilities of a cloud platform — for example, a container platform for builds and runtime, object storage for artifacts, a message queue to decouple asynchronous tasks, logging and monitoring services for observability, plus unified identity and secret management for access control. That lets the team focus on business and architecture rather than environment maintenance.

    8. Conclusion: Replace the Grind With Engineering

    The real lesson of this case is that AI coding tools raised the ceiling of individual output but did not automatically raise the floor of engineering quality. To capture the gains while avoiding the costs, three things must be in place at once — explicit context and constraints, small verifiable task breakdown, and automated quality gates that cannot be bypassed. With those three, a 100,000-line refactor does not have to balloon into 300,000 lines, and six months does not have to be mortgaged against your health.