Post-Mortem of an Out-of-Control AI Coding Agent: Why a Three-Week Rewrite Was Scrapped
As AI coding agents transition from simple script generators to autonomous development systems, traditional software engineering controls become more critical than ever. This article explores a real-world case where an AI agent was left unsupervised for three weeks to maintain a personal information system, resulting in architecture deviation, fake capabilities, and severe budget overruns. By analyzing the failure points—from testing in production environments to uncontrolled cost loops—we outline a robust engineering workflow for building controllable, auditable, and sustainable agentic systems.
After the rapid popularization of intelligent coding tools, “letting agents write code” has evolved from an experimental trick into real development workflows. For simple scripts, this approach significantly boosts efficiency. However, when a project involves multi-module collaboration, scheduled tasks, external data scraping, model calls, and long-term execution, developers face system design, runtime security, and engineering governance issues rather than simple code generation.
A product manager with a development background and long-term experience in AI technology products recently attempted to let two types of intelligent coding agents take turns maintaining a personal information processing system. For three consecutive weeks, he did not check the code, driving the project’s evolution solely through task descriptions, specification documents, and agent feedback. When he finally opened the code for review, he discovered that the project had deviated from the original design. Several key capabilities only “appeared to exist,” and the tests directly called the production environment’s inference API, resulting in a single-day consumption several times the normal budget. Ultimately, the system required a massive rework, and some modules even needed to be redesigned.
The value of this experience lies not in evaluating whether a specific tool is good or bad, but in revealing a crucial insight: when intelligent agents possess high autonomy, traditional software engineering control points cannot be omitted.
1. How a Simple Tool Evolves into a Complex System
The initial requirements were not complex: automatically fetch audio content, complete text transcription, and generate a summary. As use cases increased, the system gradually incorporated more data sources, scheduled execution, email triggers, and content archiving capabilities.
From a functional perspective, each addition was reasonable:
- Automatically scrape content after receiving a link;
- Perform structured processing on text or audio;
- Execute scheduled tasks and generate results;
- Return results via email or other notification channels;
- Save historical records for subsequent retrieval and analysis;
- Generate reflection reports based on long-term usage records;
- Extract reusable task specifications from reflection results.
However, as the number of features increased, the nature of the project changed. It was no longer a single script but a comprehensive system comprising a data access layer, a task orchestration layer, a model invocation layer, a storage layer, a notification layer, and an automated execution mechanism.
After further introducing an agent runtime, the system also needed to address the following issues:
- How to register and manage different types of agents;
- How to assign tasks and contexts to agents;
- How to restrict agents’ file, network, and credential permissions;
- How to record the input, output, and cost of each execution;
- How to handle failures, retries, timeouts, and human intervention;
- How to distinguish between development, testing, and production environments;
- How to ensure that newly generated “skills” or configurations are actually loaded by the system.
These issues essentially fall under the category of platform engineering and runtime governance. If development continues using a “write a function, patch a module” approach, the system can easily reach a state of superficial completeness but internal chaos.
2. The Most Dangerous Misconception: Treating Code Generation as Architecture Implementation
Intelligent coding agents are typically good at completing local tasks, such as creating files, adding functions, writing basic tests, or modifying configurations. However, “implementing a real agent runtime” is not just simple code splicing; it requires clear abstraction boundaries.
A complete agent runtime should at least contain the following concepts:
- Agent Definition: Describes the agent’s responsibilities, inputs, outputs, and constraints;
- Task Instance: Records a specific execution and its state;
- Scheduler: Decides when and by whom a task runs;
- Context Manager: Controls historical information, tool results, and intermediate states;
- Tool Adapter Layer: Unifies access to files, networks, databases, or model capabilities;
- Policy Engine: Checks permissions, budgets, risks, and approval requirements;
- Observability System: Records logs, metrics, call chains, and exceptions;
- Persistence Layer: Saves task states, results, and audit records.
If the specification only states “support agent registration, automatic scheduling, and skill accumulation” without defining state models, interface contracts, failure semantics, and security boundaries, the agent will likely fill in these blanks itself. The resulting code might contain numerous classes, configurations, and directories, but these elements only exist in form; they do not form a reliable operational mechanism together.
Therefore, to judge whether the architecture is truly implemented, you cannot look at the code volume or whether the directory structure is complete. You must answer a few verifiable questions:
- How does a task’s state change from creation to completion?
- Can the task be safely retried after a failure?
- Is it possible for the same task to be executed repeatedly?
- Who is responsible for permission validation before an agent calls a tool?
- How does the system handle partial results after a model call times out?
- After adding a new skill, can the runtime actually discover and load it?
- Can any production call be traced back to a specific task and operator?
If there are no clear answers to these questions, the so-called “agent architecture” is usually just concept packaging.
3. Why Skill Configurations Easily Become “Fake Capabilities”
In agent systems, skills are typically understood as a set of reusable instructions, tool calling methods, input/output specifications, or workflows. The problem is that the existence of a file does not mean the capability is in effect.
A skill must go through at least the following pipeline:
- The skill is defined and saved;
- The system scans the skill directory at startup or runtime;
- The skill passes format validation;
- The skill is registered in the available capability list;
- It can be retrieved during the task planning phase;
- The skill content is injected into the context during the execution phase;
- Tool calls are executed according to the skill’s constraints;
- The result is validated and fed back to the caller.
If only the first two steps are completed, the system may present the illusion of “complete configuration, but the agent never uses it.”
Common issues include:
- The skill file naming does not match the scanning rules;
- Configuration paths are inconsistent across different environments;
- The registration process provides no error feedback;
- The skill is loaded but does not enter the task planning context;
- The skill content exists only as plain text without structured constraints;
- The skill requirements do not match tool permissions;
- The running process does not reload after a skill is updated;
- Multiple skills have similar names, leading to uncertain matching results.
The way to improve this is to establish a testable lifecycle for skills, rather than just writing a documentation file. A validation flow like the following can be designed:
Discover skill-> Format validation-> Capability registration-> Availability check-> Simulated task call-> Output structure validation-> Record version and hash
Each step should have a clear failure outcome. For example, if the skill directory is empty, the system should not start silently; if a skill references a non-existent tool, it should immediately throw an error; if the skill’s output does not match the agreed format, it should block subsequent tasks from continuing.
More importantly, skills should have version numbers and changelogs. Otherwise, when system behavior changes, developers cannot determine whether it was due to model behavior changes, prompt content changes, or the skill itself being overwritten.
4. Connecting Tests to Production: A Dual Disaster of Cost and Security
One of the most severe issues in this case was that unit tests directly called the production inference API. The goal of unit tests is to quickly validate local logic. Ideally, they should be stable, cheap, repeatable, and independent of external systems.
Once tests directly connect to production APIs, multiple risks arise:
- Each test incurs real call costs;
- Test data might enter the production system;
- Incorrect parameters might trigger real tasks;
- Concurrent testing might cause resource waste;
- Test results are affected by external service fluctuations;
- Developers cannot easily distinguish test traffic from business traffic;
- Automatic retries might amplify API calls.
The correct approach is layered testing.
1. Unit Tests
For pure functions and local modules, use fixed inputs to validate deterministic results. For example, text splitting, state transitions, config parsing, and permission checks should never access the network.
2. Integration Tests
Verify collaboration between modules, but use mock models, virtual storage, and isolated queues. Even if real inference capabilities must be used, dedicated test credentials, strict low-quota limits, and desensitized data should be applied.
3. End-to-End Tests
When validating the complete flow, explicitly use test environment configurations and block production credentials at the entry layer. Test and production environments should not only have different directories; credentials, network egress, databases, and messaging channels must also be isolated.
Environment protection can be added at the code level:
def call_inference(request, env):if env == "test" and request.credentials.is_production:raise RuntimeError("Test environment is forbidden from using production credentials")if env == "test":return fake_inference(request)return real_inference(request)
Additionally, a second line of defense should be set up at the deployment and configuration levels, such as:
- Production credentials cannot be read by test processes;
- Test environments are forbidden from accessing production networks;
- Production APIs require additional service identity authentication;
- All call records are tagged with environment labels;
- Individual tasks have call count and amount limits;
- Tasks are automatically paused if abnormal growth occurs.
5. Why Agents Continuously Drain Budgets
The cost of an intelligent agent is usually not determined by a single call, but is jointly influenced by multiple factors:
Total Cost= Number of tasks× Iteration rounds per task× Context size per round× Tool call count× Price per call
When an agent can autonomously modify code, run tests, read logs, and retry based on errors, a loss of control in any single link can create a loop:
- Agent modifies code;
- Test fails;
- Agent reads error message;
- Modifies again;
- Triggers more tests;
- Continues calling the inference service;
- Executes repeatedly due to a lack of termination conditions.
Therefore, cost control cannot rely on the assumption that “the agent should know when to stop.” Hard limits must be established:
- Maximum execution rounds per single task;
- Maximum runtime per task;
- Total daily call quota;
- Budget cap per individual agent;
- Maximum external calls per test;
- Maximum consecutive failures;
- Human approval required after exceeding thresholds.
Simultaneously, the system must provide observability. At a minimum, it should log the task ID, agent ID, environment, model call count, input/output size, duration, failure reason, and cumulative cost. Without this data, developers can only discover issues passively after an anomalous billing statement appears.
6. Not Reviewing Code for Three Weeks: More Than Just Negligence
Letting agents work for extended periods is not an absolute mistake in itself. The real issue is the lack of staged verification.
Complex projects should not adopt a “let the agent finish everything, then review at the end” workflow, because errors will continuously accumulate in subsequent tasks. A more reasonable approach is to establish checkpoints:
- Review the architecture after completing directory and module division;
- Review task transitions after completing the state model;
- Review permissions and environments before connecting to external services;
- Review retry and idempotency before introducing automatic scheduling;
- Verify loading and invocation after adding the skill system;
- Run regression tests after completing each feature loop;
- Check change summaries, error logs, and cost data daily.
Manual review does not require reading every line of code, but critical paths must be checked, including authentication, network access, credential handling, data persistence, task scheduling, exception retries, and production configurations.
You can also require the agent to generate the following with every change submission:
- List of modified files;
- Design intent;
- Dependency changes;
- Risk notes;
- Test scope;
- Unresolved issues;
- Next steps.
This shifts code review from “reading a large amount of implementation details” to “verifying whether the design meets expectations.”
7. An Engineering Workflow for Agentic Development
A more robust workflow can be divided into six phases.
Phase 1: Freeze Boundaries
First, define what the project explicitly will not do to prevent continuous feature creep. Write down the inputs, outputs, dependencies, and failure behaviors for each module.
Phase 2: Design the State Model First
For scheduling systems and agent runtimes, prioritize defining task states, such as pending, running, success, failed, canceled, and pending approval. State changes must be traceable and recoverable.
Phase 3: Establish Environment Isolation
Development, testing, and production should use different configurations, credentials, and resources. No environment should be able to access another simply by “modifying a string.”
Phase 4: Let Agents Commit in Small Steps
Handle only one clear goal at a time, and require a runnable result to be submitted. Small commits make rollback easier and make it easier to locate the source of errors.
Phase 5: Automated Quality Gates
Before merging code, execute format checks, static analysis, unit tests, dependency checks, sensitive information scanning, and cost rule validations.
Phase 6: Continuous Observation of Running Results
After deployment, continuously observe error rates, task durations, call counts, resource consumption, and exception retries. An agent system is not finished once deployed; it requires long-term operation and maintenance.
Conclusion: Stronger Agents, Stronger Governance
Intelligent coding agents can significantly reduce repetitive development costs and help individuals quickly build complex prototypes. However, they do not automatically understand business boundaries, architectural principles, or production risks. Especially when agents can autonomously modify code, run tests, and call external services, developers must treat them as automated systems with execution capabilities, not just standard code completion tools.
This experience—where issues were only discovered after three weeks—demonstrates that what truly determines a project’s success is not how much code the agent wrote, but whether verifiable engineering constraints were established: architecture requires staged reviews, skills require real invocation validations, tests must be isolated from production, costs must have hard limits, and key changes must retain human review.
Only by front-loading these control points can intelligent agents evolve from “high-efficiency code generators” into “controllable, auditable, and sustainable engineering collaborators.”
