Three Weeks of AI Coding Agent Chaos: A Case Study in Uncontrolled Refactoring and What It Taught Us About Engineering Discipline

    This article examines a real-world engineering case where AI coding agents were given unsupervised control over a codebase refactoring effort for three weeks, leading to architectural drift, tests hitting production APIs, and a 5x token budget overrun. It breaks down the four critical failure modes observed—architecture mismatch, unsafe tests, runaway costs, and deceptive module naming—and provides concrete, actionable safeguards for teams adopting AI-assisted development.

    Introduction: A Cautionary Tale from a Small Internal Tool

    Many developers’ first foray into automation starts small. Perhaps a script to download podcast audio, transcribe it, and generate a summary. But as requirements grow, so does the system. Web scraping, scheduled jobs, email triggers, and eventually agentic workflows for deep research and daily reviews get bolted on. Functionality expands rapidly, but the code structure rarely keeps pace.

    In this particular case, the author did not write a single line of code. Instead, two different AI coding tools were given full autonomy to handle refactoring and feature development for three consecutive weeks. When the author finally reviewed the code, three critical issues emerged:

    1. Architecture Divergence: The actual implementation bore little resemblance to the specified design.
    2. Tests Attacking Production: Unit tests were directly calling production model inference endpoints.
    3. Exploding Token Costs: Around 30 autonomous iterations consumed five times the weekly token budget in a single day.

    The lesson here is clear: as code generation becomes more powerful, the need for engineering constraints grows in parallel. Faster generation also means faster propagation of errors.

    Problem 1: Architecture That Drifted from the Blueprint

    The design specification described a target state for the agent runtime. This included a registry to manage independent agents, a scheduler for task distribution, and an adapter layer to interface with different Agent SDKs. In the actual code, however, these boundaries existed primarily in names and comments. Real-world call relationships were directly coupled within the business logic.

    Common symptoms included:

    • The “registry” was a global dictionary with no lifecycle management or health checks.
    • Scheduling logic was scattered across multiple scripts, each duplicating retry and timeout implementations.
    • The adapter interface was silently modified in each iteration, leading to incompatible data structures between agents.

    Root Cause: Agents can only see the local context (e.g., a few files) during a modification. They are excellent at making minimal changes to recently-opened files but struggle to maintain a global architectural vision. Over dozens of iterations, a productive mechanism for divergence emerges. The code becomes a palimpsest of local patches that contradict the overall written intent.

    The Fix: Treat Architecture as Executable Code.

    Instead of relying on descriptive documentation, architecture rules must be turned into automatically verifiable constraints.

    1. Enforce Dependency Rules: Define strict module dependency directions (e.g., business logic must not import from the adapter layer).
    2. Introduce Contract Tests: Write tests for each interface that lock in the input and output data structures.
    3. Run Automated Checks: Run dependency checks after every single iteration. If a rule is violated, the merge/pull request must be blocked.

    A simple architectural guard script can look like this:

    1. # Architectural guard: Scan import dependencies to prevent the business layer from directly depending on the adapter layer
    2. FORBIDDEN = {
    3. "business": ["adapters"], # Business layer must not import adapter layer
    4. }
    5. for module in list_modules():
    6. for dep in module.imports:
    7. layer = layer_of(module)
    8. target = layer_of(dep)
    9. if target in FORBIDDEN.get(layer, []):
    10. fail(f"{module.name} illegally depends on {dep.name}")

    Problem 2: Unit Tests That Hit the Live API

    This was the most dangerous risk in the entire project. Unit tests should isolate external dependencies to validate local logic. Instead, these tests were directly invoking a production inference endpoint. Every time the test suite ran, it incurred real financial costs. Worse, it had side effects—writing to real data stores and potentially triggering emails or knowledge base updates.

    Root Causes:

    1. Incorrect Configuration Precedence: Test code fell back to default production endpoint values.
    2. Lack of Test Doubles: No mocks or fakes; external calls were not substituted.
    3. Unclear Environment Boundaries: Tests and production shared the same configuration and secret keys.

    The Fix: Fail-Closed by Default.

    The engineering principle is to “default to disconnecting external dependencies and only connect when explicitly allowed.” Configuration loading should enforce safety, and injections should be standard practice.

    1. # Config loading: Default to local stub service; production config must be injected by deployment pipeline
    2. env = read_env("APP_ENV", default="test")
    3. if env == "production" and not running_in_deploy_pipeline():
    4. raise Error("Non-deployment processes are prohibited from loading production configuration")
    5. inference_url = read_env(
    6. "INFERENCE_URL",
    7. default="http://localhost:8080/stub" # Local stub service, no cost
    8. )
    9. # Test with injected fake: assertions only care about business results
    10. def test_summarize_returns_title():
    11. client = FakeInferenceClient(response="Example Summary")
    12. result = summarize(client, text="Example Text")
    13. assert result.title != ""

    Additionally, configure the network egress whitelist in the CI/CD environment so that test stages cannot access public domains. This ensures that even if a configuration mistake occurs, requests cannot reach external services. Test credentials should be managed separately from production credentials and must not have access to production models.

    Problem 3: Runaway Token Costs

    The author’s daily expense reached approximately 100 USD—five times the typical weekly budget. Automation agent costs usually stem from three sources:

    • Context Overload: Each call carries a massive context window, including whole repositories or long logs.
    • Unbounded Retries: Failed tasks trigger automatic retries, and each attempt incurs a new fee.
    • Looping Inference: Tests or scripts loop through real-model calls without an upper bound.

    Cost blowouts are rarely caused by a single request; they are amplified by loops. For example, a task that fails and retries ten times with full code context rapidly accumulates cost.

    Control Measures:

    • Budget Limits: Set daily and per-task budget thresholds. Automatically pause operations when exceeded.
    • Comprehensive Logging: Log every call (model, input length, output length, cost) and archive it per task.
    • Intelligent Retries: Set a maximum retry count and exponential backoff. Distinguish between retryable errors and logical errors. Retrying logical errors is pointless and costly.
    • Context Slimming: For large files, create a summary and only put the relevant code fragments into the context window.

    Cost Estimation: A direct calculation. Cost per call = (input tokens × input price) + (output tokens × output price). Multiply this by the number of calls to get the task’s total cost. A budget guard implementation outline:

    1. # Budget circuit breaker: Check cumulative cost before every call
    2. def guarded_call(task, request):
    3. estimated = estimate_cost(request.input_tokens, request.max_output_tokens)
    4. if task.spent + estimated > task.budget:
    5. raise BudgetExceeded(task.id)
    6. response = call_model(request)
    7. task.spent += actual_cost(response)
    8. log_usage(task.id, response)
    9. return response

    Placing these checks at the call entry point allows a team to spot anomalies before they become full-scale crises, rather than discovering them when the bill arrives.

    Problem 4: Modules Named as ‘Skills’ That Were Not Skills

    During the code review, the author found that modules labeled “skills” were, in reality, simple functions or prompt snippets. They had no defined input/output contracts, no registration mechanism, and no failure handling. The name described a design vision that the code did not implement.

    This is a common issue in agentic systems. Language models excel at generating plausible names and comments, making superficial structure look complete to a reviewer.

    Validating a Capability Module:

    Ask these four questions. If any one fails, the module should be treated as incomplete, not as a finished capability:

    1. Definition: Does it have clear input and output data structures?
    2. Discoverability: Can it be independently discovered and loaded by the registry?
    3. Testability: Does it have unit tests that will fail if the functionality breaks?
    4. Autonomy: Can it run independently of the caller’s context?

    Root Cause Analysis: Local Correctness, Global Chaos

    Four root causes can be identified from this case:

    1. Unenforced Intent: Goals existed as natural language text, not executable constraints. The agent filled in the details it assumed.
    2. Delayed Human Validation: Verification relied on human review, which was postponed for three weeks. The longer the iteration cycle, the more errors compound and the higher the cost to fix.
    3. Lack of Environmental Isolation: Permissions and environment boundaries were not explicitly designed. Agents could read and write production configs without any safeguards.
    4. Lack of Observability: Costs and behaviors were opaque until the bill arrived.

    These four roots lead directly to the solutions: Contract-Based Specifications, Short-Cycle Validation, Environment Isolation, and Budget Circuit Breakers.

    An Engineering Practice Guide for AI Coding Agents

    To safely integrate AI coding agents into a project, establish these constraints in order:

    1. Small, Atomic Iterations: Restrict each task to a single module, and require runnable test results for submission.
    2. Architectural Protection: Use automated dependency checks to block illegal imports and write the architecture rules into the CI pipeline.
    3. Environment Isolation: Use separate keys and endpoints for development, testing, and production. Test credentials must not access production models.
    4. Budget Circuit Breakers: Halt automatic tasks when thresholds are hit; wait for manual confirmation to continue.
    5. Human Review Gates: At the end of each phase, a human must read the critical path code, focusing on interfaces, dependencies, and data flow.
    6. Specification Synchronization: Keep specifications and code in sync. If a deviation is required, revise the spec first, then modify the code.

    Pre-Merge Review Checklist

    Before merging any code generated by an AI agent, verify the following:

    • Offline Capability: Can the tests pass in a network-disconnected environment?
    • Secret Integrity: Are there any hard-coded production addresses or keys in the configuration?
    • Contract Completeness: Do new modules have defined input/outputs and corresponding tests?
    • Cost Rationality: Is the daily expenditure still within the budget?
    • Path Traceability: Does every component registered in the registry have a real, callable path?
    • Spec Traceability: Can every requirement in the specification be traced to its implementation in the code?

    Conclusion

    High-velocity code generation without high-integrity engineering controls is a recipe for disaster. AI coding agents are powerful junior developers that require senior-level supervision and automated guardrails. The tools for safety—contract tests, dependency checks, environment isolation, and budget limits—are not optional; they are the price of entry for leveraging these tools effectively.