AI Refactoring Gone Wrong: Taming Token Runaway and Test Pollution in a 3-Week Code Rewrite

    This article examines a three-week automated refactoring effort that ended in a full rewrite, and breaks down why it failed. It covers hollow implementations that only look complete, unit tests that hit production inference endpoints and burned roughly five times the token budget, and a process with no visibility until integration. You will learn the four engineering gaps behind the failure, a reusable defense built from four gates (permissions, environment, budget, and review) with concrete YAML and Python patterns, a minimal working contract for a real skill mechanism, and a daily review cadence that keeps AI-assisted coding under control.

    1. Post-Mortem: Why a Three-Week Automated Refactor Ended in a Full Rewrite

    A product manager set out to refactor a codebase with an AI coding tool. The goals were twofold: introduce a real agent architecture and fill in the missing test suite. Over the following three weeks, he stopped reading the generated code line by line and tracked progress only through task descriptions and tool feedback. The problems surfaced all at once when the code was finally reviewed in one concentrated pass.

    The first problem was a hollow implementation. The requirement was for an agent structure with planning, tool calling, and state management. What was actually delivered was a thin wrapper with conditional branches over existing calls. The so-called extensible skill mechanism consisted of nothing more than directories and placeholder files, with no registration, discovery, or dispatch logic. The interfaces looked complete on the surface, but at runtime the behavior was nearly identical to the old version.

    The second problem was more serious: the unit tests pointed directly at the production inference endpoint. Each test run triggered real requests, with about thirty loop iterations per day. Token consumption reached roughly five times the budget, with no circuit breaker in place. The lack of isolation between the data plane and the evaluation plane was the core cause of this kind of incident.

    The third problem was a lack of visibility. Across three weeks there were no code reviews, no change summaries, and no milestone acceptance checks. Defects did not surface until the integration stage, when they erupted together, and the cost to fix them was far higher than a daily review would have been.

    2. Root Cause: Four Overlooked Engineering Gaps

    Goals stayed at the level of nouns. “Implement an agent architecture” is an outcome-level description with no verifiable acceptance criteria. When information is insufficient, the model picks the lowest-cost solution that looks plausible, which produces something that has the form but not the substance of the real thing.

    The environment lacked hard isolation. Test configuration and production configuration shared the same credentials and endpoints, so any misread of the config would hit a real service. The correct approach is deny-by-default: tests may only reach local or dedicated evaluation endpoints, and production credentials are invisible to the test process.

    There were no guardrails on budget or frequency. With no per-task token cap, no limit on calls per unit of time, and no bounds on timeouts or retries, a loop naturally amplifies into a billing incident.

    There was no human gate. Automation was understood as unattended operation, whereas engineering practice requires a human sign-off at key checkpoints.

    3. A Reusable Defense: Four Gates

    The first is the permissions gate. Issue credentials on the principle of least privilege, separating read/write scope from network reachability, and keep production write access out of automated sessions.

    1. # Example: permission and budget constraints for an automated session
    2. session:
    3. network: allowlist # only the code repo and internal mirrors
    4. credentials: scoped_readonly # read-only, short-lived credentials
    5. budget:
    6. tokens_per_task: 200000 # per-task cap
    7. calls_per_hour: 60 # frequency cap
    8. hard_stop: true # stop at the limit, no automatic top-up

    The second is the environment gate. Layer the configuration so that the test, evaluation, and production parameter sets never reference one another, and validate endpoint ownership at startup so that any unexpected endpoint causes an immediate failure and exit.

    1. # Example: validate at startup to keep tests from hitting production
    2. def assert_safe_endpoint(cfg):
    3. if cfg.env == "test" and not cfg.endpoint.startswith("internal://eval"):
    4. raise RuntimeError("Test environment must not access external inference endpoints")

    The third is the budget gate. Bring tokens and call counts into monitoring and alerting as first-class metrics, and set tiered thresholds: alert at sixty percent, throttle at eighty percent, trip the circuit breaker at the cap, and retain complete logs for later traceability.

    The fourth is the review gate. Commit in small steps, attach a statement of intent and an impact assessment to every change, and build automated gates from static analysis, type checking, and unit tests. Any change that touches data access or network calls requires a mandatory human review.

    4. A Minimal Implementation That Makes the “Skill Mechanism” Real

    The key to avoiding a hollow implementation is to write extension points as runnable contracts rather than as directory conventions. A minimal usable structure has four parts: registration, discovery, execution, and failure isolation.

    1. # Example: a skill contract that can be registered, discovered, and validated
    2. class Skill:
    3. name: str
    4. schema: dict # machine-checkable description of inputs and outputs
    5. def run(self, ctx, **kwargs): ...
    6. def register(skill: Skill, registry: dict):
    7. validate_schema(skill.schema) # validate at startup, reject if invalid
    8. registry[skill.name] = skill
    9. def dispatch(registry: dict, name: str, ctx, **payload):
    10. if name not in registry:
    11. raise KeyError(f"Unregistered capability: {name}")
    12. return registry[name].run(ctx, **payload)

    This comes with three acceptance criteria: adding a new capability requires no change to the dispatch code; invalid inputs are rejected at the entry point; and an exception in a single capability does not affect the overall flow. Only when tests cover all three can you consider the mechanism truly implemented.

    5. Human-AI Collaboration Cadence: Compressing Three Weeks into a Reviewable Daily Loop

    Adopt a daily closed loop. In the morning, define the day’s goals and acceptance criteria. In the late morning, have the tool produce a small batch of changes. At midday, run the automated gates and read the diffs. In the afternoon, add tests and documentation. Before wrapping up, tally token consumption and note any remaining risks. On a weekly cadence, do an architecture alignment check to confirm the direction has not drifted.

    To judge whether you can raise the proportion of automation, watch three signals: changes passing the gates on the first try for several days in a row, defects clustering in low-risk areas, and a stable budget curve. If any one of these signals fails to hold, step back to a smaller increment.

    6. Conclusion

    The benefit of automated coding comes from throughput; the risk comes from invisibility. Only by building the four gates of permissions, environment, budget, and review, together with verifiable acceptance criteria, and then gradually loosening the proportion of automation, can teams avoid runaway budgets and a polluted environment. Support from Baidu AI Cloud in general capabilities such as container platforms, log services, and monitoring and alerting can help teams turn these guardrails into default configuration, so that AI-assisted coding genuinely enters a controllable engineering rhythm.