AI Agent Automation Failures: Five Engineering Lessons from a Three-Week Rebuild

    A three-week experiment in fully automated AI coding ended with a production-endpoint test bug, a runaway API bill, and a rewritten codebase. This article walks through five failure patterns behind AI-driven agent automation—ambiguous specifications, hollow skills, unsafe test configurations, weak verification, and missing budget controls—and shows how to enforce them with machine-checkable contracts, typed skill interfaces, sandbox isolation, layered testing, and hard guardrails.

    1. The postmortem: three weeks in, and the code had never been read

    A product owner with years of experience shipping LLM-based systems ran an aggressive automation experiment on a personal knowledge-base project, using mainstream AI coding tools.

    The project started small—download a podcast, transcribe it, and generate a summary—then grew into a persistent service that scraped social-platform content, ran on a schedule, and triggered summaries from email events. On top of that, the owner added deep-research workflows, daily reflection over usage logs, and automatic skill and instruction-optimization suggestions. The ultimate goal was a runtime with a registry, the ability to schedule multiple independent agents, and support for different SDKs.

    The implementation approach was entirely “modern”: the owner wrote no code and maintained only a specification document while two coding agents took turns working on it. The resulting bill after three weeks was roughly five times a normal one-week budget—in a single day. More importantly, once the code was finally read, three problems became clear:

    • The so-called skills were just prompt assembly, with no real encapsulation of reusable capabilities.
    • Unit tests pointed at production reasoning endpoints, firing around 30 real calls per day.
    • The overall architecture diverged significantly from the written specification.

    The project was eventually rebuilt from scratch.

    This was not a case of “AI can’t write code.” On the contrary, the code ran, tests passed, and the commit history was uninterrupted for three weeks. The real problem was the absence of engineering constraints that made automated output trustworthy.

    2. Trap 1: a specification is intent, not an executable contract

    The biggest weakness of natural-language specifications is that they can be interpreted arbitrarily. A sentence like “build a real agent runtime” can be completed into completely different directory structures, abstraction levels, and dependency choices depending on the context. When two tools take turns, the later one sees only the code and a short summary—not the unwritten constraints in your head—so it tends to continue writing in place rather than correct deviations. Architecture drift accumulates with every handoff.

    The fix is to compile intent into machine-checkable contracts:

    1. # spec/contract.yaml —— turn the spec from a description into a gate
    2. modules:
    3. - name: scheduler # allowed to depend only on the modules below
    4. allowed_deps: [storage, queue]
    5. - name: agent_registry
    6. allowed_deps: [scheduler, sdk_adapter]
    7. invariants:
    8. - "registry must not issue network inference calls directly"
    9. - "test code must not reference endpoints.prod"
    10. checks:
    11. architecture: ["dep-cruiser", "import-linter"] # dependency-direction checks
    12. coverage_min: 70

    Three points matter here:

    • Dependency direction must be statically checkable.
    • Invariants must be written as assertions, not slogans.
    • Every handoff should include a “deviation list” that requires the agent to explicitly answer: what did I change, why, and which constraint did I violate?

    3. Trap 2: hollow skills with no capability boundaries

    Auto-generated “new skills” from log reflection sounds appealing, but the common implementation is simply appending paragraphs to a prompt template. The result is an ever-growing context, conflicting instructions, and unpredictable behavior—with no versioning or regression validation. A skill should be a reusable capability with a type signature, not a block of natural language.

    1. # skill = explicit input/output + timeout + idempotency + observability
    2. class Skill(Protocol):
    3. name: str
    4. version: str
    5. def run(self, payload: Payload) -> Result: ... # type constraint
    6. timeout_s: int = 30
    7. idempotent: bool = True # safe to retry

    Three supporting measures are needed:

    • A skill registry with semantic versioning, where changes require review.
    • A golden-sample regression set for every skill, which must also run when the prompt changes.
    • A fixed upper bound on the context budget; adding a new skill must retire an old one to prevent unbounded growth.

    4. Trap 3: unit tests wired to production—the most expensive lesson

    Unit tests misusing production reasoning endpoints expose the absence of configuration layering. No environment identifier should be assembled from string concatenation; it should be strongly inferred from the runtime context and validated again on the client side:

    1. def resolve_endpoint(ctx: Context) -> str:
    2. if ctx.env != "test":
    3. raise RuntimeError("Test environment missing; refusing external calls")
    4. return settings.test_endpoint # can only be a local stub or sandbox

    Three additional gates should be introduced:

    • At the network layer, outbound traffic is denied by default, and test domains go through a whitelist.
    • At the cost layer, set budget circuit breakers; a per-day or per-task token limit stops execution and triggers an alert when exceeded.
    • At the data layer, real credentials must not enter test processes; use short-lived, restricted tokens.

    The principle is “deny by default,” so that crossing a boundary requires an explicit action rather than happening by default.

    5. Trap 4: without layered verification, green tests mean nothing

    “All tests green” may only mean the assertions were written loosely enough. Trustworthy automation needs a pyramid of verification: static checks (types, dependency direction, dangerous API calls) → unit tests (deterministic, zero external dependencies) → contract tests (replay recorded responses for repeatability) → end-to-end tests (sandbox environment, minimal samples) → human review (architecture and security).

    It is especially important to add mutation testing and assertion-strength checks to prevent agents from weakening assertions just to make tests pass. All external calls should be recorded and replayed, keeping nondeterminism out of CI.

    6. Trap 5: no guardrails on budget and permissions

    The most easily overlooked cost of automation is tokens and call volume. Practical guardrails include:

    • Set a budget and time limit for each task; when exceeded, pause automatically and produce a progress snapshot.
    • Make “read-heavy, write-light” the default permission; write operations, dependency additions, and network access require explicit authorization.
    • Write every agent action to an audit log so it can be replayed and attributed.
    • Generate a daily “architecture drift report” and compare it item by item against the specification contract.

    7. A reusable implementation checklist

    • Specification as code: write invariants as assertions and enforce them in CI gates.
    • Contracted handoffs: include a deviation list and open questions with every exchange.
    • Capabilities with signatures: version skills, make them regression-testable, and cap the context.
    • Strong environment isolation: deny outbound traffic by default, and connect tests only to sandboxes.
    • Cost circuit breakers: enforce triple limits on budget, rounds, and duration, with alerts.
    • Human gates: architecture and high-risk changes must be reviewed before merging.

    If these capabilities are deployed in the cloud, a container platform can host the agent runtime, object storage can retain recorded samples, a message queue can distribute tasks, and logging and monitoring/alerting services can handle auditing and budget alerts—forming a closed loop that is observable, rollback-capable, and rate-limited. Baidu AI Cloud applies the same principles of least privilege and observability-first practice for this class of general engineering capabilities.

    8. Conclusion

    Three weeks bought one lesson: agents can speed up writing code, but they will not take responsibility for architecture decisions and risk. Only when intent becomes a verifiable contract, capabilities become bounded modules, and verification and budgets become hard gates does automation go from “looking fast” to “actually reliable.”