Architecture Drift and Test Boundary Violations: Lessons from a 3-Week AI Agent Refactoring
After letting two AI coding agents autonomously refactor a codebase for three weeks, a thorough code review revealed critical issues: architecture drift, superficial capability modules, tests connecting directly to production environments, and excessive token consumption. This article explores these common pitfalls and provides actionable strategies—including interface constraints, runtime guards, budget management, and a human review checklist—to ensure AI-generated code is structurally sound and production-ready.
1. Background: How a Small Tool Expands into a Complex System
Many personal projects start with a simple goal, such as automatically downloading audio, transcribing text, and generating summaries. As requirements grow, the project gradually integrates modules for web scraping, scheduled tasks, and email triggers, eventually evolving into a long-running, multi-component system.
Feature expansion often outpaces design. If developers delegate heavy coding workloads to AI agents, the agents will continuously append implementations based on local instructions but rarely step back to review the overall structure. The risks in such projects usually lie not in individual functions, but in the boundaries between modules, dependency directions, and runtime environment configurations.
This article examines a real-world case. An experienced product manager had two AI coding agents take turns refactoring a codebase. After three weeks, they began reading the code line by line and discovered three main categories of problems: the architecture diverged from the design intent, capability modules were only superficially implemented, and test code connected directly to production services. Additionally, the agents ran many cycles daily, causing token consumption to far exceed expectations.
2. Problem 1: Generated Architecture Inconsistent with Design Intent
The project originally had a specification document planning to build an agent runtime with a registry to schedule independent agents and interface with different agent development kits. During implementation, the agents often opted for easier-to-run solutions, such as writing scheduling logic directly into the main flow or letting multiple modules share global state.
Just because the code runs does not mean the structure is correct. To determine if the architecture follows the design, look at three indicators:
- Whether dependencies between modules are unidirectional, and whether core logic depends on specific third-party interfaces;
- Whether the three responsibilities of registration, scheduling, and execution are separated;
- Whether adding a new agent type only requires adding an implementation and completing registration, without modifying the scheduling core.
It is recommended to break down the specification into checkable interface constraints before starting the task, and solidify them using type definitions or interface files. After each agent submission, these constraints should be verified by a human or static checking tool, rather than just checking if the functionality passes.
3. Problem 2: Capability Modules Lacking Actual Implementation
“Skills” or “capability modules” are a common design pattern in projects, referring to independent functional units that agents can call on demand. The problem is that agents sometimes generate a module that looks complete—with proper filenames, comments, and documentation—but the internal logic only returns fixed results or is never actually called.
The inspection method is straightforward:
- Identify the entry point of each capability module and confirm whether it is genuinely called in the main flow;
- Write at least one input-output test case for each module to observe whether the return value depends on the input;
- Check if dependencies are genuinely used, looking out for unused imports or empty error handling.
If a module fails these checks, it should be marked as incomplete, not considered delivered.
4. Problem 3: Tests Connecting to the Production Environment
The most severe issue in this case was that unit tests called production inference APIs directly. Once the tests ran, they consumed real quotas, incurred real costs, and even wrote real data. The root cause was that the test code did not differentiate environments, and the agent used default addresses when completing configurations.
Prevention methods should be implemented in three layers:
Layer 1: Configuration Isolation. Tests should only read dedicated test configurations, not production ones. Production addresses should not appear in the code repository but be injected via environment variables, defaulting to local mock services.
Layer 2: Runtime Guards. Check the target address during the test startup phase and terminate immediately if a production address is detected. Example:
import osfrom urllib.parse import urlparsePRODUCTION_HOSTS = {"inference.prod.example.internal"} # Placeholder; actual values should come from deployment configsdef assert_not_production(base_url: str) -> None:host = urlparse(base_url).hostname or ""if host in PRODUCTION_HOSTS or os.getenv("APP_ENV") == "production":raise RuntimeError("Test processes are forbidden from accessing production inference APIs")
Layer 3: Network Boundaries. In continuous integration environments or development machines, restrict test processes to only access the network segment of mock services. Even if code guards are bypassed, network policies can still block the requests.
5. Problem 4: Uncontrolled Token Consumption
Running about thirty cycles a day means the agent repeatedly reads code, generates modifications, runs tests, and corrects errors without human supervision. Each cycle resends a large amount of context, causing costs to accumulate rapidly. If the task itself has no termination condition, consumption can reach multiples of the budget.
Controlling costs requires setting a budget at the task level, rather than checking the bill afterward. Here is a simple budget guard example:
class BudgetGuard:def __init__(self, daily_limit_tokens: int):self.limit = daily_limit_tokensself.used = 0def charge(self, tokens: int) -> None:self.used += tokensif self.used > self.limit:raise RuntimeError("Daily budget exceeded; automated task suspended")
In practice, this can be combined with the following measures:
- Set a maximum number of cycles and maximum tokens for each task; stop and output a report when the limit is reached;
- Limit the file scope of a single context, providing only the code relevant to the current change;
- Record a summary of changes after each cycle to prevent the agent from repeatedly reading the same batch of historical content.
6. Problem 5: Cumulative Drift in Long-Term Autonomous Work
Multiple agents taking turns creates a subtle drift. During each handover, the new agent can only see the current state of the code and limited documentation, unable to fully understand previous design trade-offs. Consequently, local fixes stack up, ultimately forming a structure completely different from the initial design.
There are three ways to mitigate this drift:
- Write design decisions into repository documentation and require the agent to read them before starting each task;
- Have a human review key interfaces and dependency relationships after each phase before proceeding to the next;
- Adopt small-step commits with a limited scope of changes for each, making it easier to roll back and locate issues.
7. An Executable Acceptance Checklist
Before accepting the results of any automated generation cycle, it is recommended to complete the following checks:
- Do the changes comply with the interface constraints in the specification?
- Is each newly added module called by the main flow, and does it have corresponding test cases?
- Do tests only access mock services, and are network policies and code guards effective?
- Is the token consumption for this cycle within budget, and does the task have clear termination conditions?
- Has the critical logic been read by a human, rather than just passing automated tests?
Automation tools can significantly improve development efficiency, but acceptance responsibility still lies with humans. Code reading, environment isolation, and budget management should be designed before task initiation, not remedied after the project accumulates massive issues.
8. Conclusion
Using AI agents for refactoring is suitable for tasks with clear boundaries that can be verified incrementally. For systems requiring long-term operation, involving external services and real costs, teams need to preset architecture constraints, test isolation, budget limits, and manual review checkpoints. The lessons from this case are clear: passing the build is only the starting point. Only by understanding the structure, confirming the environment, and controlling costs can auto-generated code become truly usable.
