AI Agent Engineering Failure: Three Weeks of Refactoring and the Hidden Costs
This article examines a three-week AI-assisted refactoring project that ended in a complete rewrite. A product owner used mainstream AI coding tools to evolve a personal podcast pipeline into an agent runtime, only to face runaway token costs, tests accidentally hitting production inference endpoints, fake skill accumulation, and an architecture that drifted from its spec. The post identifies three root causes—spec drift, missing verification, and permission overreach—and proposes a four-layer guardrail design covering contracts, execution sandboxes, verification gates, and observability. It also details how to turn skills into measurable assets, treat token budgets as a first-class metric, and adopt small, reviewable changes with mandatory human checkpoints. A final checklist helps teams keep AI coding tools productive rather than a bill they can only understand weeks later.
1. Postmortem: The Code Was First Read Three Weeks Later
A product owner with a development and research background, whose day job involves working with frontier model teams and owning model delivery, used a mainstream AI coding tool to run a continuous refactoring effort on a personal project for three weeks. The starting point was small: a personal podcast processing pipeline that automatically downloaded audio, completed transcription, and generated summaries. Features kept stacking up—scraping and summarizing social platform content, adding scheduled jobs for round-the-clock operation, and connecting an email inbox so that sending a link returned a summary. The system gradually evolved into a searchable, accumulating personal knowledge base.
The real loss of control happened in the next phase: the owner tried to build a “real agent workflow” on top of the system, including deep research, daily reflection based on historical usage records, new skills distilled from that reflection, and automatically proposed prompt optimization suggestions. To support this, he wrote a specification aimed at an agent runtime with an agent registry, independent agent scheduling, and an adapter layer for different agent development frameworks.
The implementation approach was to hand tasks back and forth between two types of coding agents, letting the model write its own code and iterate on it. The result after three weeks: daily token consumption reached roughly five times the usual weekly budget, about one hundred dollars; unit tests silently pointed at the production inference endpoint and triggered about thirty rounds of calls per day; the so-called “skill accumulation” was only text assembly at the prompt level and did not form executable, reusable capability units; and the final architecture did not match the spec, so the project had to be rebuilt from scratch.
This is not a “the model is not good enough” story, but a story of missing engineering constraints. When generation speed far exceeds review speed, system complexity accumulates like compound interest, and human attention becomes the scarcest resource in the entire chain.
2. Three Root Causes: Spec Drift, Missing Verification, and Permission Overreach
2.1 Spec Drift: Natural Language Specs Cannot Serve as Contracts
The specification described a “registry,” “scheduling,” and “adapting to different frameworks” in natural language. Such descriptions express intent to humans but are only context to an agent. Without machine-verifiable interface definitions, data models, state machines, and error semantics, the agent makes choices that are “locally reasonable but globally wrong”: it runs, it demos, but it does not match the design intent. More subtly, two agents taking turns each form a set of implicit assumptions. To stay compatible with the previous agent, the next one often stacks adapter layers instead of refactoring, causing architectural entropy to rise.
2.2 Missing Verification: Mistaking “It Runs” for “It Is Correct”
The only feedback signal during the three weeks was “the program did not error.” Without unit tests, contract tests, end-to-end regression, and architecture guard rules, the agent lost its basis for correction. The reason the skill mechanism was “fake” is essentially the lack of acceptance criteria: there is a whole engineering definition gap between generating a piece of skill description text and a capability unit that can actually be scheduled, composed, and measured for success rate.
2.3 Permission Overreach: Test Environment Directly Connected to Production Inference Endpoint
The most expensive mistake came from missing environment isolation. Test code read production configuration by default, credentials were not tiered, and there were no boundaries on egress or call quotas. As a result, “running the tests once” became real billed calls to the production inference service, about thirty rounds a day, and costs were quickly amplified. This kind of problem is not obvious in code review; it only shows up on the bill and monitoring curves.
3. Guardrail Design: Keep Agents Working Within Verifiable Boundaries
It is recommended to split governance into four layers. Missing any layer pushes risk to the next one.
- Contract layer: Use interface definition files and data schemas to describe capability boundaries, so humans review the structure and machines verify the implementation.
- Execution layer: Containerized sandbox, least-privilege credentials, egress allowlist, and short-lived tokens issued per task.
- Verification layer: Test pyramid + architecture guards + change impact analysis, as hard gates for merging.
- Observability layer: Full instrumentation of call volume, failure rate, cost per task, and context length distribution, with threshold-based alerts.
Illustrative policy configuration (pseudocode, only expressing the constraint idea):
agent_policy:sandbox: container, no_host_networkcredentials: scoped, ttl=15megress: allowlist["internal-proxy"]budget:tokens_per_task: 200ktokens_per_day: 1Mon_exceed: pause_and_notifygates:- unit_tests_pass- contract_tests_pass- arch_rules_pass- cost_per_task_under_threshold
Environment isolation must be specific down to the configuration parsing logic: test and staging use separate endpoints and separate quotas; production credentials do not enter the code repository or logs; external inference calls have retry limits and circuit breakers to avoid cost amplification from failed retries.
4. Evaluation Gates: Turn “Skills” into Measurable Assets
For a skill to become an asset, it needs at least four things: clear trigger conditions, structured input and output, executable validation cases, and success rate and latency baselines. A minimal checklist can constrain this:
skill:name: <semantic name>trigger: <decidable precondition>input_schema: <fields and types>output_schema: <fields and types>tests: [<case 1>, <case 2>]slo: {success_rate: ">=0.9", p95_latency: "<=8s", cost: "<=X"}owner: <responsible person>
For the supporting process, it is recommended to run the “regression set + new cases” on every change and perform mandatory manual sampling review of agent-generated content. Architecture guard rules can be expressed as assertions on dependency direction, layering constraints, and prohibiting direct cross-layer calls, so violations fail at the commit stage instead of surfacing three weeks later.
5. Cost Governance: Make Token Budgets a First-Class Metric
Manage cost as a functional requirement: set token and call limits per task, pause and notify when exceeded; segment and summarize long contexts to avoid stuffing the entire knowledge base into context; cache reusable retrieval results and intermediate artifacts; set nighttime batch processing and fallback model strategies for high-consumption tasks. Also build a “cost vs. benefit per task” dashboard, and only allow outputs that pass verification and stay within cost thresholds to enter the main branch.
6. The Right Way for Humans and Agents to Collaborate
A workable rhythm is “small steps, fast iteration, mandatory synchronization”: break a three-week big refactor into dozens of small changes that can be verified within half an hour, each accompanied by tests and review. Humans define contracts, decide trade-offs, and review irreversible decisions; agents generate and trial-and-error within the established contracts. If using general cloud capabilities, container platforms can host sandboxes, object storage can hold artifacts, message queues can decouple tasks, and logging and monitoring alerting services can handle observability, turning “invisible risks” into “observable metrics.”
7. Checklist
- Has the spec been converted into machine-verifiable contracts?
- Are tests fully isolated from production endpoints and credentials?
- Are there architecture guard rules and merge gates?
- Are there token and call quotas and a pause-on-exceed mechanism?
- Do skills have trigger conditions, schema definitions, and success rate baselines?
- Are manual review and rollback paths preserved?
The conclusion is straightforward: agents will not take architectural responsibility for you. Engineering the four things—contracts, isolation, verification, and cost—is what makes AI coding tools a source of productivity rather than a bill you can only understand three weeks later.
