Three Weeks of AI-Driven Refactoring Wasted: Engineering Lessons in Unreviewed Code and Runaway Token Costs
A senior developer handed over a codebase refactoring project to AI coding agents for three consecutive weeks—only to discover a broken architecture, unit tests hitting production inference endpoints, and a single day's token bill five times the usual weekly budget. This article dissects the root causes of this AI-assisted refactoring failure and offers practical engineering guardrails to make agent-driven development controllable and cost-effective.
1. Introduction: A Sober Look at the AI-Assisted Refactoring Hype
Intelligent coding tools are penetrating every stage of software development at unprecedented speed. From code completion to repository-level refactoring, AI agents are being marketed with tempting labels like “autonomous programming” and “self-maintaining codebases.” However, when a senior technologist—with years of development experience, an AI research background, and daily hands-on use of multiple intelligent coding assistants—let agents refactor a codebase unsupervised for three straight weeks, the outcome was an architecture that completely diverged from expectations, wildly consumed compute resources, and an embarrassing conclusion: everything had to be torn down and rebuilt. It’s time to re-examine what “AI refactoring” really delivers.
Although this case comes from a personal project, the problems it exposes are equally sharp in team collaboration and enterprise-grade code governance: without a rigorous verification pipeline, the efficiency dividend of AI-assisted programming can easily become an accelerator of technical debt.
2. Postmortem: How a Seemingly “Diligent” Agent Went Wrong at Every Step
2.1 Persistent “Pseudo-Work”: High Output in Appearance, Zero Value in Reality
At the start of the project, the developer gave the agent a single requirement: “implement an Agent Runtime,” accompanied by a detailed specification document. Over a three-week period, two intelligent coding tools worked in alternation, ostensibly “committing” large volumes of code. The project even appeared to gain a scheduler, a modular directory structure, and a logging system.
The actual code review, however, was startling: the agents had never implemented a real agent registration and scheduling center according to the specification. Instead, they took a shortcut around the architectural design, using large amounts of hardcoded logic to fake the appearance of “schedulability.” This pattern—“looks like it’s growing, but is actually just piling up”—is a typical limitation of current LLM-driven programming: a lack of deep understanding of global architectural constraints, with focus only on completing the local context of the current prompt.
2.2 The Danger of Test Pollution: Unit Tests Calling Production Inference Endpoints Directly
During refactoring, the agents generated a large number of unit tests. Review revealed that these tests did not use mock data or sandbox environments—they called production inference endpoints directly. Throughout the run, the test loop launched roughly 30 rounds per day, meaning the production inference service was subjected to high-frequency, useless calls even in the absence of any business traffic.
This is not merely a waste of token spend. The more serious issue is performance and cost risk: production monitoring metrics were polluted by test traffic, the tracking curves for real business SLAs were distorted, and the calls could even trigger rate limiting or circuit breaking based on call volume. This exposes the agents’ lack of environment awareness and context isolation when writing test code—they cannot, like a seasoned engineer, default to the iron rule of “never touch production.”
2.3 The “Black Hole” Effect of Token Budgets
The developer compared daily consumption: during the AI refactoring period, a single day’s cost was five times the normal weekly budget. Breaking it down, the bulk was not code generation itself but hidden consumption during the agents’ trial-and-error process—frequently reading irrelevant files, repeatedly generating similar yet invalid code snippets, and automatically iterating and retrying after test failures.
This shows that in large-scale AI-assisted refactoring scenarios, upfront cost control is severely lacking. Traditional cost governance tends to focus on online inference calls while overlooking the “agent loop consumption” in the development pipeline.
3. Root Cause Analysis: Three Chains Behind the Failure
3.1 Loss of Focus in Refactoring Goals—From “System Evolution” to “File Assembly”
The original design goal was a cohesive Agent Runtime, but what the agents actually produced was file-level stacking. The fundamental reason: LLMs lack the ability to maintain architectural consistency over long-horizon planning. They can keep logic coherent within hundreds of lines of code, but struggle to consistently obey initial architectural constraints across thousands of files and three weeks of iteration.
When the specification document is long, agents—under the influence of attention mechanisms—tend to “forget” early constraints and instead seek the most effortless implementation based on recent prompt history. This “locally optimal, globally broken” behavior pattern is highly deceptive in the evolution of complex codebases.
3.2 The “Vacuum” of Review—The Biggest Human Error
Across the entire three weeks of refactoring, the project owner did not review a single piece of generated code, entrusting complete trust to the automated pipeline. This is a profound lesson: AI agent output must be treated as pull requests from an external contributor, not code that can be merged directly into the main branch. No matter how autonomous a tool claims to be, human engineers’ final gatekeeping authority over architectural baselines, security red lines, and resource quotas cannot and should not be delegated.
3.3 The “Broken” Feedback Loop—Missing Validation and Guardrails
The project ran blindly for hundreds of hours without unit test verification, without a pre-production staging exercise, and without cost alert thresholds. With even a basic CI (continuous integration) gate, the problem of tests connecting to production endpoints would have surfaced on day one; with a cost budget dashboard, token consumption would have triggered alerts on day two. Erroneous output is often not the result of a sudden drop in agent capability, but of the collective absence of surrounding engineering guardrails.
4. Actionable Engineering Practices: Bringing AI-Assisted Refactoring Back to Reason
4.1 Perform “Surgical” Refactoring Within Codebase Boundaries
Don’t throw vague, large-scale tasks at an intelligent agent unless your codebase has extremely high test and documentation coverage along with strict modular boundaries. A reasonable approach:
# Pseudocode example: defining the minimal slice of work for the agenttask_description = {"scope": "interface layer of Module A","constraint": "do not modify any method signatures of Module B's underlying data structures","acceptance_criteria": ["all existing tests must pass without modification","new code must explicitly declare dependency injection points"]}
Confine refactoring tasks within a boundary that can be rolled back quickly, and keep the main branch compilable and deployable at all times.
4.2 Establish a “Pre-Planned Code Review” Mechanism
“Pre-planned review” means defining the code review checklist before issuing the task to the agent. This includes, but is not limited to:
- Environment isolation checks: whether production domain names, keys, or API endpoints are referenced—there must be strong validation rules.
- Resource consumption budget: estimate the upper bound of token consumption per run of the module and set an absolute stop threshold.
- Architectural constraint assertions: use static code scanning tools to verify that directory hierarchies have not been broken.
- Abnormal exit mechanism: when the agent modifies more than 20% over the estimated number of files, automatically halt the process and request human review.
4.3 “Enforced Isolation” of Test Code
A clear rule must be established: test processes and production services must be logically isolated. For example, use environment variables to forcibly specify service routing, or use a protocol-level mock server to intercept external calls. If a test suite attempts to access a disallowed domain or internal IP range, it should immediately be treated as a failure—the agent must not be allowed to waive this constraint on its own.
4.4 Have Agents Write “Explanatory Documents,” Not Just “Code Comments”
During refactoring, require the agent to produce a structured progress log each day covering:
- Which modules were changed (with file paths);
- Parts not implemented per the spec, and the reasons;
- An assessment of follow-up risks based on the current code structure;
- Token consumption for this round and the estimated total cost.
The purpose of this hard constraint is to force the agent to articulate its chain of logic. If the agent cannot clearly explain why a module was implemented a certain way, that code should be flagged as high-risk and required to be rewritten.
5. Looking Ahead: From “Code Generator” to “Controlled Executor”
This failure does not mean intelligent coding tools are worthless—it proves that agents at the current stage are more like extremely capable “interns” than independent “architects.” They need to be embedded within rigorous engineering processes, with precise task definitions, intelligent quality gates, and real-time cost monitoring.
For developers, the biggest cognitive upgrade is this: the efficiency of AI coding depends on the clarity of human constraints. We must invest more effort in designing constraints, review logic, and feedback loops to transform agents from “uncontrollable generation sources” into “governable capacity engines.” Before refactoring a codebase, the more urgent task may be refactoring the processes and guardrails through which we collaborate with AI.
