AI Agent Refactoring Failure: Token Cost Overruns and Test Pollution
A practical post-mortem of a three-week AI-assisted refactoring effort that ended in a full rewrite. It examines three root causes—specification drift, missing test isolation, and uncontrolled token spending—and shows how executable contracts, layered test isolation, budget circuit breakers, real skill definitions, and human review turn agentic coding from something that appears to run into something that can be delivered.
1. Case Review: Reading the Code Only After Three Weeks
A practitioner with development experience, whose day job involves working with frontier model teams, ran an experiment on a personal project. What started as a simple podcast processing tool was gradually expanded into a “personal knowledge base” that could scrape content from multiple platforms, run on a schedule, and trigger summaries by email. On top of that, agent workflows were layered in: deep research, usage reflection, skill accumulation, and instruction optimization suggestions. A specification was written, with the goal of producing a runtime that included an agent registry, independently schedulable agents, and the ability to integrate with different agent SDKs.
The implementation approach was very “modern”: instead of writing code himself, he had two AI coding tools take turns. Three weeks later, when he finally read the output line by line, the problems erupted all at once:
- The so-called “skills” were only directories and documentation files, with no executable registration, discovery, or invocation path.
- Unit tests connected directly to the production inference API at runtime, polluting production and making test results untrustworthy.
- Roughly thirty automated iterations per day consumed about five times the token budget.
- The architecture deviated severely from the specification, leaving no option but to start over.
This was not a case of “the model isn’t good enough,” but of missing collaboration mechanisms and engineering guardrails. The rest of this article breaks the problem down into a reusable analysis framework.
2. Root Cause One: Specification Drift and Context Decay
When multiple rounds and multiple tools hand off work, the original constraints are gradually diluted. Each new tool sees only part of the context and tends to “fill the gap in front of it” rather than “maintain overall consistency.” The result is inconsistent interface naming, blurry responsibility boundaries, and multiple implementations of the same functionality.
Actionable mitigations:
- Turn the specification into an executable contract. Use interface definition files, schema validation, and sample data to pin down inputs and outputs, instead of relying only on natural language descriptions.
registry.contract.yaml- name: agent_registryoperations: [register, discover, invoke, health_check]invariants:- invoke.must_be_idempotent_by_request_id- discover.must_not_expose_disabled_agents
- Single source of truth. Keep the specification, interface definitions, and task list in the same repository directory. Any change must update the contract before the implementation, and reviews should treat the contract as authoritative.
- Small commits that can be rolled back. Allow only one verifiable goal per round, bind commit messages to task IDs, and make it easy to revert when something goes wrong.
3. Root Cause Two: Missing Verification, Tests Connected to Production
Connecting tests to the production inference API is the most typical and most dangerous kind of mistake. It damages cost, data, and result trustworthiness at the same time. The correct approach is layered isolation:
- Deterministic stand-ins: use local stubs or recorded replay data in unit tests, asserting on logic rather than model output.
- Contract tests: verify request and response structures, error codes, and timeout and retry semantics.
- Small-scale integration tests: use low quotas, rate limiting, and synthetic data in an isolated environment.
- Manual spot checks: keep human review and sampling for critical paths.
# Pseudocode: enforce isolation via environment variables, fail if missingif env == "prod" and not request.is_synthetic:raise RuntimeError("prod inference is forbidden in tests")
The principle of least privilege is equally important: write access to the code repository, permission to call the production inference API, and permission to read secrets should be separated. Agents should by default receive only the minimal set required for the current task, with short-lived, auditable credentials.
4. Root Cause Three: Runaway Costs and Budget Guardrails
Thirty automated iterations a day and token consumption five times the budget indicate a design where “budget is not a first-class citizen.” Cost governance should be built in up front:
- Budgets and circuit breakers: set limits per task round, per day, and per feature module; pause and wait for human confirmation once a threshold is reached.
- Tiered model strategy: use more capable models for planning and review, and more economical models for bulk mechanical changes.
- Context trimming: inject only relevant files and interface definitions instead of stuffing the entire repository into context.
- Observability: bring call counts, input and output sizes, failed retries, and per-task cost into logging and monitoring with alerts, and produce a daily report.
- Caching and reuse: cache stable prompts, retrieval results, and build artifacts to reduce repeated consumption.
When deploying on the cloud, object storage can hold artifacts and replay data, a message queue can smooth out task spikes and handle retries, a container platform can host isolated execution environments, and logging and monitoring services can provide cost visibility, forming a closed loop.
5. Turning “Fake Skills” into Real Capabilities
If a “skill” is only a documentation file, it cannot be scheduled. A usable skill contains at least four elements: metadata (name, version, applicable scenarios), permission declarations, input and output contracts, and executable validation cases. The registry performs static validation at load time, a health check before execution, and records results after execution. Skills that fail validation must not enter the scheduling queue.
skill/meta.yaml # name/version/applicable scenarios/required permissionscontract.yaml # inputs, outputs, and invariantshandler/ # executable implementationtests/ # deterministic cases + contract cases
6. The Right Way for Humans and Agents to Collaborate
AI coding tools are suited to “verifiable repetitive work,” not to making architecture decisions alone. A workable process: the human owns goals, boundaries, and acceptance criteria; the agent owns implementation and self-testing; the human owns review and merging. Every round’s output must include a change description, an impact analysis, and test results. If review fails, no progress is counted.
Also keep a “circuit-breaker retrospective”: once specification deviation or test failures occur in two consecutive rounds, pause automated iteration immediately and go back to the contract layer to fix things, rather than adding more rounds.
7. Checklist
- Does the specification have an executable contract and a single source of truth?
- Are tests fully isolated from production, with least-privilege, short-lived credentials?
- Are there budget limits, circuit breakers, and a daily cost report?
- Do skills have all four elements: metadata, permissions, contracts, and test cases?
- Does every round have small commits, rollback capability, and human review?
- Is there a retrospective mechanism that pauses work after consecutive failures?
Conclusion
Three weeks bought one rewrite—a steep price, but the conclusion is clear: the bottleneck in agentic coding is not generation capability, but the four guardrails of contracts, isolation, budgets, and review. Build those first, then let the tools take turns, and only then can “looks like it runs” become “ready to deliver.”
