When AI Coding Refactors Spiral Out of Control: Architecture Verification and Test Cost Governance
AI coding tools can produce large volumes of plausible code, but plausibility is not proof. Drawing on a real-world case where two AI coding tools refactored a codebase for three weeks without verification—resulting in a fake agent architecture, non-executable "skills," and unit tests that silently called production model inference APIs at five times the normal weekly budget—this article examines three engineering questions: how to verify that generated code implements the intended architecture, how to ensure tests validate local logic instead of triggering real external services, and how to keep automation permissions, change scope, and costs under control. It covers skill verifiability criteria, acceptance conditions for specifications, layered testing strategies, environment isolation mechanisms, runtime budget governance, and a practical seven-step refactoring workflow.
1. The Danger of Refactoring Often Hides Behind “It Looks Done”
The original case describes a typical loss of control with AI coding tools: a product lead with a background in both development and AI research let two AI coding tools take turns refactoring his personal codebase for about three weeks, without reviewing the implementation in depth. When he finally re-read the code, he discovered that the system had not implemented the intended agent architecture, and that the so-called “skills” had never become truly executable, reusable capabilities. Worse, the unit tests that were supposed to verify code correctness were actually calling the production model inference API.
According to the original account, these tests ran about thirty rounds in a single day, consuming roughly one hundred dollars—about five times the author’s normal weekly budget. Note that this amount is specific to that case: it cannot be generalized into a universal price for any model service, nor can per-call cost be inferred from the number of runs alone.
The questions worth discussing are not “are AI coding tools reliable,” but three engineering problems:
- How do you prove that generated code implements the specified architecture, rather than merely appearing to work?
- How do you ensure tests verify local logic instead of silently triggering real external services?
- How do you keep the permissions, change scope, and costs of automated development within acceptable limits?
Until these three questions are answered, code that runs and tests that pass still do not prove the refactor succeeded.
2. From Content Processing Tool to Agent System: How Complexity Changes
The project in the case started as a personal content processing tool: download audio, transcribe it, and generate a summary. It later added social content scraping, scheduled jobs, an email entry point, and knowledge organization, and eventually expanded into deep research, usage-log reflection, skill accumulation, and instruction optimization.
These requirements all seem to revolve around “processing information,” but the underlying system shapes are quite different.
2.1 Fixed Pipelines Mainly Solve Step Orchestration
For a workflow like “take a link, fetch the content, extract the text, generate a summary,” a fixed workflow is usually sufficient. The inputs and outputs of each step are relatively stable, and the system’s focus is on failure retries, duplicate tasks, timeouts, and data persistence.
Such systems do not necessarily need agents. Implementing them with an explicit state machine or task pipeline makes behavior more predictable and costs easier to control.
2.2 Agent Systems Need Explicit Decision and Execution Boundaries
Agent behavior becomes relevant when the system must choose its next action based on task state, invoke different tools, and decide whether to continue researching.
At that point, the architecture cannot consist of just a few functions with “agent” in their names. At minimum, it must clarify:
- Who receives goals, makes plans, and terminates tasks;
- Which execution units can be discovered and invoked;
- What permissions each execution unit has;
- How state, context, and intermediate results are passed;
- How failures, cancellation, and timeouts are handled;
- How model calls and tool calls are logged and constrained.
Registries, runtimes, and adapters for different execution backends are common ways to implement these capabilities, but not the only ways. What matters is clear boundaries, observable behavior, and verifiable results—not whether directory names match some architectural terminology.
3. “The Skills Are Fake”: How to Judge This from an Engineering Perspective
“Skill” has no single unified implementation across systems. It can be an instruction template, a program function, or a task package with tool configurations and execution constraints. So one cannot simply declare that “only code counts as a real skill.”
A more accurate criterion is whether it has the execution semantics it claims to have.
Suppose the requirement is for the system to produce new skills from daily reflection. Saving a paragraph of suggestion text does not constitute skill accumulation. To become a capability the runtime can actually use, the following problems usually must be solved.
3.1 Discoverable
The system needs to know where skills are, which tasks they apply to, and how to select them. An explicit registry or a controlled configuration loading mechanism works; relying on a human browsing directories does not.
3.2 Executable
A skill must have a clear entry point. If it is an instruction template, the runtime must be able to load it into task execution; if it is a programmatic capability, it needs a callable entry point and an interpretable result format.
3.3 Contractual
Inputs, outputs, error types, and preconditions must be explicit. Without them, callers can only guess at usage, and compatibility becomes hard to verify during refactoring.
3.4 Bounded
A skill should declare which tool permissions it needs, whether it accesses the network, whether it reads sensitive data, and how many resources it may consume. Being executable does not mean it may execute without limits.
3.5 Verifiable
There must be tests proving the skill is actually discovered, loaded, and invoked. Checking that a file exists, or seeing “skill created” in a model’s reply, does not constitute valid acceptance.
Automatically generated new skills should also enter a pending-review state first, and only be published after testing and authorization. Letting reflection output directly modify runtime behavior is equivalent to pushing unverified suggestions into the production execution path.
4. Why Specifications Can Still Be “Implemented Wrong”
Specifications help AI coding tools understand tasks, but natural-language requirements still admit multiple interpretations.
For example, “add an agent registry” could be implemented as a list of names, or as a complete mechanism with lifecycle management, permission checks, and execution routing. Both superficially match the sentence, but their engineering meaning is entirely different.
Therefore, specifications must be further translated into verifiable acceptance conditions.
| Requirement statement | More effective acceptance condition |
|---|---|
| Support independent execution units | Invocations go through a unified entry point, and each unit’s execution state is observable |
| Support multiple execution backends | Core scheduling does not depend on any specific backend; implementations connect through an adaptation boundary |
| Support skill accumulation | A new capability, once approved, can be discovered, loaded, and actually invoked in tasks |
| Support failure recovery | Timeouts and failures do not corrupt task state; retry behavior has explicit limits |
| Support budget control | When the budget is insufficient, subsequent calls are rejected or paused, with the reason recorded |
| Support task cancellation | Cancellation signals propagate through the execution chain, rather than merely updating display state |
Acceptance should also trace real call paths: does the task entry go through unified scheduling? Does execution bypass permission checks? Is backend adaptation just a superficial wrapper? Are skill files actually never read?
The value of this kind of review lies in identifying implementations where “the nouns are all there, but the mechanisms are missing.”
5. Why Unit Tests Calling Production APIs Is a Serious Defect
The goal of a unit test is to verify logic within a limited scope. It should normally be fast, repeatable, and independent of the production environment.
If tests actually call model APIs, they introduce at least four risks:
- Cost risk: Every local run, automatic retry, or CI execution may incur charges.
- Stability risk: Network conditions, rate limits, and external service status affect test results.
- Data risk: Test content may be sent to environments that should not receive it.
- Side-effect risk: The call chain may further trigger message sending, data writes, or other real operations.
A common cause is unsafe configuration defaults: when tests provide no dedicated configuration, the program falls back to production credentials or production endpoints. This reduces configuration errors, but turns “the tests can run” into a danger signal.
Layered Testing Beats Uniform Real Calls
Unit tests use test doubles to verify parameter construction, state transitions, error handling, and budget logic, without touching real model services.
Contract tests verify the adapter layer’s data formats, error mapping, and calling conventions; most checks can be done with fixed samples and controlled mocks.
Integration tests verify collaboration between modules, using isolated environments, dedicated identities, and limited quotas.
End-to-end tests keep only a few critical paths, must be explicitly enabled, and are subject to strict limits on time, call counts, and spend.
Quality evaluation judges whether summaries or research results meet business goals. It may include real model calls, but should use fixed sample sets and a separate budget, and should not be mixed into unit tests that run on every build.
6. Environment Isolation Must Rely on Mechanisms, Not Reminders
Writing “do not access the production environment” in a prompt is not enough. Test processes may read inherited environment variables, or fall into default branches when configuration is missing.
Reliable isolation requires multiple layers of defense.
First, test identities should not hold production permissions. Even if code mistakenly uses a production endpoint, the permission layer should reject the call.
Second, test processes should not have external network access by default. Tests that genuinely need networking should run through a separate entry point with restricted destinations.
Third, missing critical configuration should fail immediately, rather than falling back to production. Production credentials must never be used as a convenient default for development.
Finally, CI environments should manage secrets independently. Ordinary test jobs should not mount production secrets; release jobs and test jobs should use different identities and authorization scopes.
Together, these measures form a “deny by default” security model: without explicit authorization, no real external call can occur.
7. Cost Governance Belongs in the Runtime, Not Just in the Bill
Repeated tests are only one entry point for cost amplification. Automated systems can also inflate consumption through multi-round reasoning, failure retries, ever-growing context, and execution units delegating to one another.
A simplified relationship helps understand where cost comes from:
Total consumption depends on the number of calls, the input/output size of each call, and the billing model of the corresponding service.
Therefore, budget control cannot limit only output length. Input context, nested tasks, and retries must also be managed.
Four categories of constraints are recommended:
- Task budget: Cap the cumulative call count and cumulative spend of a single task.
- Time budget: Set per-step timeouts and a total execution duration to prevent tasks from hanging indefinitely.
- Delegation budget: Limit the number of subtasks and delegation depth to prevent unbounded expansion.
- Environment budget: Manage development, testing, and production quotas separately, so tests cannot drain a shared budget.
Under concurrency, you must also account for multiple tasks passing budget checks simultaneously. Recording cost only after a call completes allows concurrent calls to blow through the budget. A more robust approach is to reserve quota before issuing a call, settle after completion, and leave a safety margin for estimation error.
Monitoring should be tied to tasks, environments, execution units, and retry reasons. Only then, when an anomaly appears, can you tell whether it was a test misconfiguration, a runaway retry policy, or a business task that genuinely exceeded expectations.
8. Two AI Coding Tools Taking Turns Is Not Cross-Review
Alternating tools to modify code can increase throughput, but it does not inherently create independent verification.
The second tool tends to accept the existing code’s organization, treating the first tool’s design assumptions as facts. When the task is simply “keep improving,” it is more likely to extend the existing path than to question whether the architecture has drifted from the goal.
Implementation and review should be explicitly separated:
- The implementation phase completes only one scoped change;
- The review phase reads the requirements and acceptance conditions first, then examines the code;
- Review tasks must look for evidence of constraint violations, not just code style;
- Permission handling, external calls, state management, and budget logic get human review;
- Merges must not be approved based solely on the implementer’s own summary.
Review findings should cite concrete locations, call paths, and failure conditions. “Test initialization reads production credentials” is far more valuable than “consider improving security.”
9. A Practical AI-Assisted Refactoring Workflow
Step 1: Establish a Baseline
Keep a rollback-ready version, and record existing functionality, task entry points, external dependencies, and known defects. Fill in critical-path tests first, so you can tell whether behavior changed after refactoring.
Step 2: Write Requirements as Boundaries
Clarify which features belong in fixed workflows and which require dynamic decisions. Define the responsibilities of the runtime, execution units, skills, and backend adapters, and forbid concentrating all logic in one omnipotent dispatch function.
Step 3: Build a Minimal Vertical Slice First
Do not rewrite the entire codebase at once. First implement one task invoking one execution unit through the unified entry point, and verify permission checks, state recording, cancellation, and budget limits. Expand to other features only after the core mechanisms hold.
Step 4: Limit Each Batch of Changes
Handle one clear objective per batch. Avoid changing directory structure, configuration, tests, and deployment logic simultaneously. The more concentrated the change, the easier it is to spot unnecessary modifications.
Step 5: Accept Architecture and Functionality Separately
Functional tests prove that “results are produced”; architectural acceptance proves that “results are produced through the specified mechanism.” Neither substitutes for the other.
Step 6: Verify Failure Scenarios
Proactively test missing credentials, exhausted budgets, service timeouts, tool access denials, duplicate task submissions, and cancellation. Failure paths often reveal architectural quality better than success paths.
Step 7: Gradually Open Up Real Calls
Validate offline first, then run small samples in an isolated environment, and only then connect production traffic. Each stage needs explicit exit criteria and a rollback plan.
10. What Truly Needs Automation Is a Verifiable Engineering Loop
The illusion AI coding tools most easily create is combining large volumes of file changes, passing tests, and fluent completion reports into the impression that “the project is now reliable.”
But engineering quality depends on evidence: whether runtime paths match the architecture, whether tests isolate external dependencies, whether skills genuinely participate in execution, whether budgets can stop over-limit calls, and whether failures can be recovered from.
The core lesson of this case is not that developers must hand-write every line of code, but that they cannot long abandon understanding and acceptance of critical mechanisms. Tools can generate implementations, but requirement boundaries, permission grants, architectural confirmation, and production release still need clear ownership.
When refactoring is broken into reviewable small steps, tests produce no external side effects by default, and the runtime enforces cost and permission constraints, automated development shifts from “generating code fast” to “reliably delivering systems.”
