When AI Coding Agents Rebuild a Codebase: A Three-Week Failure Case Study and Engineering Guardrails
This article examines a real-world project where two AI coding agents were tasked with refactoring a personal content-processing tool into a full agent runtime over three weeks. The result was a fundamental architectural mismatch, misconfigured tests hitting production endpoints, excessive token consumption, and a complete rewrite. The analysis identifies root causes such as non-executable specifications, missing task accounting, weak environment isolation, and insufficient human oversight. It then provides practical guardrails: executable specs, least-privilege agent runtimes, strict test/production separation, cost budgets, quality gates, multi-agent collaboration protocols, and milestone-based acceptance. A verification checklist is included for teams adopting agent-assisted software engineering.
AI coding agents have been widely expected to turn natural language specifications into working software—splitting tasks, modifying code, writing tests, and even refactoring entire codebases. A product lead with both development and AI research backgrounds recently demonstrated a more sober reality: agents can quickly generate code that looks plausible, but without executable acceptance criteria, strict permission boundaries, and continuous human review, the larger the output scale, the higher the rework cost.
The project started as a personal content-processing tool that automatically downloaded audio, transcribed it, and generated summaries. It then expanded to content scraping, scheduled tasks, email-triggered summaries, and evolved further into an agent workflow including research, daily reflection, skill accumulation, and instruction optimization suggestions. To turn the system into a true agent runtime, the lead wrote a specification that included an agent registry, task scheduling, independent agents, and various agent integration layers. Instead of implementing the code personally, the lead had two coding agents alternate in writing the codebase. After three weeks, when the codebase was finally reviewed, fundamental deviations from the intended architecture became clear: key capabilities were never actually implemented, tests were incorrectly pointing to production inference endpoints, the agents ran about thirty rounds per day, consuming several times the weekly token budget, and the project ultimately had to be scrapped and rebuilt.
This is not a single-model capability issue but a typical example of agentic software engineering missing engineering constraints. Below, the analysis covers root causes, design principles, and practical deployment steps.
1. Root Cause Analysis: Why a “Three-Week Auto-Refactor” Goes Out of Control
1.1 Natural Language Specs Are Not Executable Specs
The specification described what should exist—“an agent registry,” “job scheduling for independent agents,” “support for different integration layers”—but lacked interface contracts, data structures, state machines, failure semantics, and acceptance test cases. Agents could only guess based on local context, often generating placeholder implementations that looked similar in naming but behaved differently. “Skill modules” might have been empty shells returning fixed results, lacking real input validation, error handling, and observability.
1.2 Dual-Agent Alternation Without a Unified Task Ledger
Two agents taking turns writing code appears to increase throughput, but it introduces state fragmentation. One agent may assume a module is complete, while the other re-implements or bypasses it in later context. One agent modifies an interface, while the other still calls the old version. Without a single-writer lock, change sets, and conflict resolution mechanisms, the codebase gradually becomes a patchwork of incompatible modifications.
1.3 No Hard Isolation Between Test and Production Interfaces
Unit tests should use test doubles, in-memory services, or contract stubs, but configuration drift caused tests to directly call production inference endpoints. With high test frequency and many rounds, costs were amplified. More critically, test behavior could pollute production data or trigger real billing. Environment isolation must not rely on developer discipline; it must be enforced by configuration, network policies, and secret compartmentalization.
1.4 Missing Cost Budgets and Round Limits
Agents tend to “keep trying until passing.” Without task-level token budgets, maximum round counts, timeouts, and backoff strategies, failed retries become budget sinks. Thirty rounds per day is not unusual, especially when tests mistakenly connect to real endpoints—each round may generate real costs.
1.5 Lack of Code Review and Quality Gates
The lead barely reviewed code for three weeks, effectively handing architectural decisions to agents with limited context windows. Agents are good at local fills but not at maintaining long-term system consistency. Without architecture rule checks, static analysis, type checking, change summaries, and human spot checks, deviations are not caught in time.
1.6 Acceptance Criteria Were Defined Too Late
The project progressed by “letting the agent keep writing” rather than by achieving a minimal end-to-end runnable system as a milestone. Without phased acceptance, direction errors were only discovered after three weeks, and rework covered the entire codebase.
2. Correct Practices: Putting Agents Inside Engineering Guardrails
2.1 Make Specifications Executable
Break specs into three layers:
- Architecture Decision Records: explain why the design is chosen.
- Interface Contracts: define input/output, error codes, idempotency.
- Acceptance Use Cases: define runnable behavioral assertions.
Every task slice should include a “Definition of Done”: which files can be changed, which interfaces are immutable, what tests are required, and how completion is proven. Example pseudo-config:
task:id: agent-registry-v1allowed_paths:- src/registry/forbidden_paths:- src/billing/contracts:- registry.register(input) -> agent_id- registry.resolve(agent_id) -> endpointacceptance:- unit_tests_pass- contract_tests_pass- no_prod_endpoint_referencebudget:max_tokens: 200000max_rounds: 8timeout_seconds: 1800
2.2 Least-Privilege Agent Runtime
The registry, scheduler, and integration layers should all follow least privilege: tool whitelists, network egress allowlists, read-only or restricted file system paths, and environment-scoped secrets. Agents should not have production credentials by default. Capability detection must be real: when registering a skill, the runtime must invoke its health check or contract test—if that fails, reject registration, preventing “fake skills” from entering the scheduling chain.
2.3 Test Environment Rejects Production by Default
Test configuration must explicitly declare dependency stubs, and production endpoint addresses must not appear in test config. Enforce via environment variables, network policies, and startup validation. If the test environment references production domains or production secrets, startup fails immediately. Example pseudo-code:
def assert_test_environment(config):if config.env != "test":raise RuntimeError("only test env allowed")if config.inference_endpoint in PROD_ENDPOINTS:raise RuntimeError("test must not use production endpoint")if config.credentials_scope != "test":raise RuntimeError("test credentials must be scoped")
2.4 Cost and Observability
Each task, agent run, and model call should carry a cost label, recording token consumption, round count, duration, and failure reason. Set task-level budgets and global circuit breakers: exceeding budget triggers an automatic pause and waits for human confirmation. Logging services, monitoring alerts, and audit trails should cover agent tool calls and external requests, especially attempts to access production interfaces.
2.5 Quality Gates and Human Review
Automated gates include static analysis, type checking, dependency vulnerability scanning, architecture rule checks, contract tests, and minimal end-to-end use cases. Coverage should not be the sole metric; focus on behavioral assertions of critical paths. Human review does not need to read every line of generated code, but must review architecture changes, interface changes, permission changes, and cost anomalies. Daily code reading and weekly audits should be institutionalized.
2.6 Collaboration Protocol for Dual-Agent Alternation
If using multiple agents, establish a shared task ledger, single-writer lock, change sets, and conflict resolution. Only one agent may write to the same task at any time. Each agent must produce a change summary and impact assessment. Before merging, run unified gates. Alternation is not simple handover; it is scheduling based on task state and capability.
2.7 Milestone Acceptance and Knowing When to Rewrite
Build a minimal end-to-end system first: one real registration, one real skill, one real scheduling, one test-stub invocation, and one cost record. After passing, scale up. If architectural deviations affect interfaces, permissions, or data models, rewrite early rather than letting agents patch on top of a wrong foundation.
3. Verification Checklist
- Does the specification include interface contracts and runnable acceptance cases?
- Does the test environment strictly forbid production endpoints and production secrets?
- Do agents have least privilege, tool whitelists, and audit logs?
- Does each task have a token budget, round limit, and timeout circuit breaker?
- Are skill registrations validated through real health checks and contract tests?
- For multi-agent collaboration, is there a task ledger, single-writer lock, and conflict resolution?
- Before merging, are static analysis, type checking, contract tests, and architecture rule checks run?
- Is there daily review of critical changes and weekly auditing of costs and anomalies?
- Is a minimal end-to-end system used as the first-phase acceptance?
Conclusion
AI coding agents are not unsuitable for refactoring, but they cannot be left unattended for three weeks without engineering guardrails. Agents improve local production speed, but system consistency, permission boundaries, cost control, and acceptance responsibility must still be borne by the engineering organization. By turning specifications into executable contracts, hard-isolating test from production, converting budgets and rounds into circuit-breaker conditions, and placing human review before architecture and permission changes, agents can become a controllable productivity tool rather than an accelerator of rework and budget incidents.
