When AI Coding Refactoring Goes Wrong: A Guide to Architecture Acceptance and Budget Governance

    A product manager let two AI coding tools refactor a personal project for three weeks without reviewing the output — and discovered a missing agent runtime, unit tests calling production inference APIs, and roughly $100 in costs. This guide explains how to turn vague specifications into verifiable architecture acceptance criteria, establish safe environment boundaries for testing, and govern LLM budgets before AI-generated code spirals out of control.

    1. Three Weeks of Automated Refactoring: Why You Might Still Need to Start Over

    In the original case, a product manager with a background in development and AI research handed a personal project to two AI coding tools, letting them take turns refactoring it for about three weeks before carefully inspecting the generated code. The inspection revealed two critical problems: the system had never actually implemented the agent runtime required by the specification, and some unit tests were calling the production model inference API directly.

    According to the case description, those tests ran roughly 30 rounds per day, consuming about $100 — five times the author’s normal weekly budget. These figures only describe the outcome of that specific case; they cannot be used to draw general conclusions about the cost or reliability of AI coding tools.

    What truly deserves attention is not that a tool “wrote wrong code,” but that the entire delivery process lacked an effective feedback loop: the specification never became verifiable architectural constraints, the tests had no trustworthy environment boundaries, and continuously generated code received no timely human review.

    For developers and engineering teams, this class of problem is common. Code can compile, pipelines can return results, and tests can show green — yet none of these signals necessarily prove the system implements the intended architecture, let alone that it is fit to run long-term.

    2. From a Content Processing Script to an Agent System: How Complexity Changes

    The project originally handled a relatively well-defined content processing task: download audio, transcribe it, and generate summaries. Social content scraping, scheduled jobs, email triggers, and continuous operation were later added, gradually turning it into a personal knowledge processing system.

    At this stage, most requirements can still be implemented as deterministic workflows. For example:

    Input link → fetch content → extract text → generate summary → save result → send notification.

    Each step has clear inputs and outputs, and failures can be retried according to preset rules. Even if one step calls a large language model, the whole system does not necessarily require an agent architecture.

    Once deep research, usage-log reflection, skill accumulation, and instruction optimization are added, the nature of the system begins to change. Tasks may need dynamic decomposition, tool selection based on intermediate results, decisions about whether to keep exploring within a budget, and state maintained across steps.

    The questions to answer are no longer just “how do I call the model,” but:

    • Who decides what to execute next?
    • Which tools may be invoked, and how is their scope restricted?
    • Where is execution state stored, and how is recovery handled after failure?
    • How are skills discovered, selected, and used?
    • How are permissions, resources, and context isolated between tasks?
    • How do you determine a task is complete, rather than reasoning indefinitely?

    If these questions have no clear answers, the system can easily become an ordinary script dressed up in agent terminology.

    3. “The Skills Are Fake”: The Problem Is Missing, Verifiable Runtime Semantics

    The original title summarized the skill problem as “fake,” but the provided text did not show the relevant implementation code, so no further claims can be made about how it was implemented. A more rigorous technical discussion should focus on a common deviation: a system has skill files, registration entry points, or related naming — but no evidence that any of this actually participates in execution.

    A skill should not be recognized merely by a directory name or class name. It can be a set of reusable instructions, task steps, and supporting resources, or it can combine controlled tools to accomplish specific work. Implementations need not be identical across systems, but at minimum the following must be explicit.

    3.1 Trigger Conditions

    Under what circumstances does the system select this skill? Is it explicitly specified by the user, matched by task type, or chosen by a planning process? If every task loads every skill, context bloat and behavioral conflicts follow.

    3.2 Input/Output Contracts

    What information does the skill require, what results may it return, and how are failures expressed? Without a contract, callers can only guess at output meaning, and downstream steps cannot connect reliably.

    3.3 Permission and Resource Boundaries

    Can the skill access the network, read files, call external APIs, or modify persistent state? These capabilities should be granted by the runtime environment, not expanded unilaterally by generated code.

    3.4 Versioning and Traceability

    Each execution should record which skill version was used, which tool calls were made, and how the final result was verified. Otherwise, when behavior changes after an instruction update, the cause is hard to locate.

    To verify a skill is genuinely wired into the system, design a set of controlled tasks: with a skill enabled versus disabled, observe whether skill-loading logs, tool-call traces, and task outcomes differ as expected. Because model behavior is stochastic, do not conclude from a single run; combine multiple evaluations with execution evidence.

    4. Turning “Implement an Agent Runtime” into Architecture Acceptance Criteria

    Statements like “implement a registry,” “support independent agents,” and “integrate different execution components” express direction but are not directly testable.

    A more effective approach is to decompose the specification into observable behaviors and boundaries that must not be violated.

    Architecture Goal Verifiable Acceptance Criterion
    Agent registration Unregistered identifiers are rejected; duplicate registration has explicit handling rules
    Independent execution Contexts and mutable state of concurrent tasks do not contaminate each other
    Execution component adaptation The business layer does not depend on specific components; contract tests still pass when a component is replaced
    Permission control Unauthorized tool calls are rejected before execution
    State management Task progress is queryable; the recovery scope after restart is explicitly defined
    Budget constraints New calls stop once call-count or cost limits are reached
    Execution tracing The relationships among tasks, steps, skills, and tool calls can be reconstructed

    A recommended division of responsibilities includes modules for task intake, scheduling, agent registration, execution adaptation, skill resolution, tool authorization, state storage, and observability. These modules do not need to be deployed independently, and there is no need to introduce complex infrastructure prematurely just for “architectural completeness” — but responsibilities should remain clear.

    In particular, distinguish three different concepts: a registry provides definitions, a scheduler arranges tasks, and a runtime manages the execution lifecycle. A map storing names and functions can be part of a registration mechanism, but by itself it does not prove a complete runtime exists.

    5. Why Tests Connected to Production

    Unit tests mistakenly hitting production endpoints is usually not a single mistake but the result of several missing boundaries stacking together.

    Common paths include: importing a business module in a test automatically reads production configuration; the model client is initialized at module load time; a test environment lacking configuration falls back to default endpoints; or tests stub only some calls while other branches still reach real services.

    Environment safety therefore cannot rely on “developers remembering not to call.” It must rely on default-deny and explicit authorization.

    5.1 Unit Tests Must Not Access External Networks by Default

    Unit tests should verify local logic — task routing, budget calculation, failure handling, result parsing. Model responses, network access, and storage operations should be provided by test doubles.

    A test double here is a controlled simulated implementation, not a different real model endpoint. It should cover success, timeouts, malformed output, and insufficient-quota scenarios, keeping tests stable and repeatable.

    5.2 Integration Tests Use Isolated Resources

    Tests that genuinely need real calls should use separate identities, isolated data, and dedicated budgets, enabled by an explicit switch. When required configuration is missing, they should refuse to run rather than automatically using production credentials.

    Different test layers should also run at different frequencies. Fast-feedback tests suit every commit; real-model evaluations should be scheduled based on risk and cost, not embedded indiscriminately into every test pipeline.

    5.3 Build a Second Line of Defense in the Runtime Environment

    Beyond code-level checks, restrict the network egress of test environments, do not inject production credentials, and apply least privilege. Even if generated code bypasses a configuration check, it should not thereby gain access to production resources.

    6. Budget Runaway Is Not About Expensive Single Calls — It’s About Amplified Call Volume

    Model cost can be abstracted as:

    Total cost ≈ input metered usage × input unit price + output metered usage × output unit price + other billable items.

    Actual billing units and items depend on the service’s rules. Governance should focus not only on the cost of a single request but on how request counts grow.

    For example, one test round contains multiple model calls, each with automatic retries; when multiple tasks run concurrently, retries and loops amplify consumption further. Continuously appended context can also make each later step more expensive than the one before.

    Budget governance requires at least three levels:

    • Per-task limits: cap step counts, call counts, cumulative usage, and maximum execution time.
    • Environment limits: set separate quotas and call permissions for development, testing, and production.
    • Account limits: configure total-budget alerts and prepare necessary kill switches.

    Budget checks must also account for concurrency. If several tasks check the balance simultaneously and all conclude funds are sufficient, overspending can still result. Budget reservation, atomic counters, or concurrency quotas can reduce this risk; settle against actual usage after calls complete.

    Note that a budget cap is usually not a perfectly precise hard boundary. In-flight requests may still incur charges, and estimates may differ from actual metering. Keep a safety margin and limit maximum concurrency.

    7. Two AI Coding Tools Taking Turns Is Not the Same as Reviewing Each Other

    Multiple tools can bring different analytical perspectives, but effective cross-checking only forms when review standards are independent and results are verifiable.

    If the second tool simply accepts the first tool’s explanations and continues filling in code, wrong assumptions get passed along. Both tools may generate more implementation around the same flawed abstraction, making the problem harder to untangle.

    A more sensible collaboration model assigns clear roles:

    • The implementation step submits code around a single, verifiable change.
    • The review step independently reads the specification, code diffs, and test evidence.
    • Security review focuses on network access, credentials, file access, and execution permissions.
    • Cost review analyzes real call counts, loop conditions, and retry strategies.
    • Final architecture decisions remain with the developer or technical lead.

    Reviewers should not merely judge whether code “looks reasonable” — they should actively hunt for paths that violate constraints. For example: could a test create a real client? After a task is cancelled, do requests still go out? Does a new skill actually enter the execution chain?

    8. Replace Long Unreviewed Refactoring with a Progressive Process

    A more reliable refactoring process has six stages.

    Stage 1: Establish a baseline of the current state.
    List current business capabilities, data flows, external dependencies, and high-risk call sites. Add behavioral tests for key functionality, first clarifying which behaviors must remain unchanged.

    Stage 2: Define architecture boundaries.
    Document module responsibilities, allowed dependency directions, state ownership, and permission policies. Clarify ambiguous specifications before coding.

    Stage 3: Implement a minimal vertical slice.
    First complete one task’s closed loop — submission, execution, result persistence — including budget checks, execution records, and failure handling. Do not generate many hollow modules first and hope a complete architecture naturally emerges later.

    Stage 4: Accept both behavior and structure.
    Behavioral acceptance checks whether results are correct; structural acceptance checks whether calls go through prescribed entry points, permissions are controlled, and state is isolated. Neither alone is sufficient.

    Stage 5: Low-risk trial runs.
    Run with controlled data, low quotas, and limited concurrency; observe repeated execution, abnormal exits, cancellation requests, and recovery behavior. Confirm the rollback plan before real adoption.

    Stage 6: Migrate incrementally and clean up.
    Migrate legacy flows feature by feature, keeping every change understandable, reviewable, and revertible. Remove old implementations only after new paths are stable, avoiding multiple conflicting execution logics coexisting.

    9. When You Find Risk: Stop the Bleeding First, Then Decide Whether to Rebuild

    If tests have already been found calling production endpoints, the first step is to stop the relevant automated tasks, remove production credentials from the test environment, and review call records, data access scope, and billing details. If credentials were exposed to an untrusted execution environment, revoke or rotate them according to your organization’s security process.

    Then evaluate the codebase. Not every architectural deviation requires starting over: if business logic is reusable and dependencies can be severed, keep the effective parts and replace the execution and test layers; if global state, implicit calls, and permission sprawl have spread throughout the system, rebuilding a minimal core may be the more controllable path.

    AI coding increases the speed of code generation — and equally amplifies the speed at which errors spread. Truly reliable delivery is not measured by how many files were continuously generated, but by whether every change can prove: the architecture meets its constraints, tests cannot cross boundaries, costs are controllable, anomalies are traceable, and the system can be rolled back.