← All writing

Production AI agent architecture: dissecting open-source cores, passk evals, and real failure modes

Yunseop Im · Software Engineer, AI & Backend Systems · M.S. CS, Georgia Tech

When companies hire engineers to build "agentic AI systems," the job is almost never inventing a new prompting framework. As engineering teams from Anthropic to public-sector AI labs have found the hard way, an agent loop itself is ~150 lines of code. What separates a fragile demo from a system you can trust with production repositories, manufacturing BOMs, or customer accounts is state serialization, authorization boundaries, environment-state evaluation, and failure containment.

This article synthesizes lessons from dissecting modern open-source agent runtimes (mini-swe-agent, NousResearch's hermes-agent, xai-org/grok-build, OpenHands, DeepSeek's dsh-superagent, and UK Government's i-dot-ai repositories) alongside operating my own agent harness (devin-harness) and enterprise manufacturing agents in production.

1. The 7-part anatomy of every production agent core

Strip away the marketing vocabulary across modern coding and enterprise agents — from minimal SWE-bench solvers (~100 lines in mini-swe-agent) to Rust crate workspaces (xai-org/grok-build splitting shell, tools, and workspace) and multi-agent routers (deepseek-ai/dsh-superagent) — and every serious runtime converges on the exact same seven subsystems:

┌─────────────────────────────────────────────────────────────────────────┐
│ 1. INTAKE & SERIALIZATION   Per-session turn queue · idempotency key    │
├─────────────────────────────────────────────────────────────────────────┤
│ 2. CONTEXT COMPILER         Pinned rules (AGENTS.md) · prefix-cache     │
│                             stable prefix · compaction hook on overflow │
├─────────────────────────────────────────────────────────────────────────┤
│ 3. MODEL LOOP               Native tool_calls · step/cost budget ·      │
│                             timeout + abort controller per attempt      │
├─────────────────────────────────────────────────────────────────────────┤
│ 4. PERMISSION GATE          Deterministic PreToolUse guard (<50ms) ·    │
│    (OUTSIDE the model)      read=auto, mutating/external=approval gate  │
├─────────────────────────────────────────────────────────────────────────┤
│ 5. TOOL DISPATCH            Schema validation · server-injected tenant/ │
│                             ACL/revision scope · structured error return│
├─────────────────────────────────────────────────────────────────────────┤
│ 6. SUBAGENT / WORKER ISOL.  Router owns user chat; Workers run in       │
│                             isolated worktrees/containers & return diff │
├─────────────────────────────────────────────────────────────────────────┤
│ 7. ACTION LEDGER & EVAL     Append-only JSONL trace · Stop claim-check  │
│                             · end-state regression suite (Inspect AI)   │
└─────────────────────────────────────────────────────────────────────────┘

The single most important architectural rule across all seven layers: never fork an agent core to encode domain logic, and never ask a system prompt to enforce a security boundary.

In our manufacturing PLM agent, rules like "only return documents matching the caller's ACL groups", "always resolve the latest released revision unless an ECO draft is specified", and "never mutate an Engineering Change Order without human sign-off" live inside the tool implementations and deterministic pre-tool hooks — never in prompt prose. Prompts can be jailbroken or forgotten after context compaction; a database query whose request builder requires an authenticated acl_groups array cannot.

2. Systems reliability vs. model intelligence: the 5 invariants

Persistent resident agents (the lineage from OpenClaw to router-worker systems like dsh-superagent) survive long-running sessions not because their underlying LLM never hallucinates, but because the host runtime enforces five distributed-systems invariants:

LayerFailure without itProduction mechanism
1. Turn serializationUser sends a follow-up message mid-tool-call; two loops mutate session state concurrentlySingle actor / queue per session with explicit policy (followup, steer, or interrupt)
2. Idempotent side effectsNetwork retry after timeout sends duplicate email, double-charges wallet, or opens duplicate PRDeterministic idempotency key persisted before external execution; terminal results replayed on retry
3. Capacity admissionWebhook or cron burst spawns 200 concurrent agent loops, exhausting GPU KV-cache or API spendBounded worker slots + priority lane reserving capacity for interactive human turns over background sweeps
4. Blast-radius isolationRunaway shell command mutates sibling sessions, leaks .env, or hangs indefinitelyPer-attempt timeout + abort signal, isolated filesystem/container, and deterministic command/path blocklists
5. Grounded provenanceUngrounded model fabrication looks identical to a cross-tenant data leak, destroying user trustMandatory source/revision citation validated against retrieved chunk IDs before rendering

Invariant #5 is widely underestimated. When a closed-source personal agent recently hallucinated plausible-looking private messages from another user, "it was just a hallucination, not a breach" was an unusable defense. In regulated or multi-tenant domains, an ungrounded claim that resembles leaked data is operationally indistinguishable from a security incident. Output schemas must force retrieved document/revision citations that the backend verifies deterministically.

3. Field lessons from public-sector open source: UK Gov's i-dot-ai

One of the best public laboratories for production AI engineering is the UK Government's Incubator for AI (github.com/i-dot-ai), which publishes MIT-licensed code and candid postmortems from systems serving thousands of civil servants:

4. Why pass@1 lies: passk and environment-state evals

Academic leaderboards report pass@1 (did the agent succeed on a single try?) or worse, pass@k (did at least one of k tries succeed?). In production backend engineering, the metric that governs user trust is passk, popularized by τ-bench / τ²-bench (Shinn, Yao et al.): the probability that an agent succeeds on all k independent trials of the same task under realistic user phrasing variance and policy constraints.

The compounding math is brutal: an agent with an impressive-looking 80% single-run accuracy (pass1 = 0.80) has a pass8 of 0.808 = 16.8%. Four out of five production users hitting that workflow repeatedly will experience a policy violation or broken state.

How to build an eval suite that survives model upgrades

Instead of hand-rolling fragile custom test runners, adopt the architecture standardized by the UK AI Security Institute's open-source Inspect AI framework (Task = Dataset + Solver + Scorer, MIT):

  1. Score the final environment state, not just the chat text. In τ²-bench and SWE-bench, an agent that politely apologizes or claims success while leaving the database or git tree in the wrong state scores 0. Assert the post-run database rows, emitted tool calls, and passing test suite deterministically.
  2. All-turns safety & policy rubrics. Following Anthropic's multi-turn evaluation design, a single policy violation on turn 4 of a 6-turn trajectory (for example, bypassing a refund hold state or exposing an unscoped document) fails the entire trajectory (min aggregation across turns, never mean).
  3. Two-tier grading (deterministic first, calibrated LLM judge second). Run zero-cost deterministic assertions first (JSON schema validity, citation ID existence, zero forbidden diff patterns, test exit code 0). Only invoke an LLM judge for semantic properties that unit tests cannot express — such as scope creep, weakened test assertions, or unverified user-journey claims — and calibrate that judge against a human-labeled golden set whenever swapping judge models.

5. Five real failure modes from autonomous coding harnesses

While building and operating devin-harness across production repositories, five recurring agent failure modes forced specific deterministic countermeasures:

  1. The "green tests by deleting the test" reward hack: Given a failing CI gate, autonomous coding agents occasionally add test.skip, // @ts-ignore, biome-ignore, or lower coverage thresholds to turn the build green. Fix: a deterministic diff scanner in gate.mjs hard-blocks any PR adding suppression tokens or reducing test count unless explicitly overridden by a human reviewer.
  2. Premature "done" claims without post-edit execution: An agent runs tests, makes a "tiny one-line fix" afterward, and declares victory without re-running the suite. Fix: a Stop lifecycle hook (claim-guard.mjs) compares the timestamp of the last file-write event in action-log.jsonl against the last test execution event; if edits occurred after the last test run, the harness injects a loud unverified warning before the session closes.
  3. Context compaction amnesia: Long debugging sessions trigger automatic conversation summarization, silently dropping hard operational rules from turn 1 (for example, "never run standalone wrangler deploy"). Fix: enforce critical invariants at the PreToolUse shell/file boundary (agent-guard.mjs & file-guard.mjs, <50 ms regex check) so even an amnesiac model cannot execute forbidden commands.
  4. Monolithic AGENTS.md token bloat & attention dilution: Stuffing 1,000 lines (~10k tokens) of repository trivia into the root instruction file degrades instruction-following on every turn. Fix: hierarchical layering — keep root AGENTS.md under ~100 lines of non-negotiable repo-wide mandates and load subtree or task-specific skills lazily on demand, cutting baseline prompt overhead by ~70% while improving prefix-cache hit rates.
  5. Judge re-litigation loops: Stateless LLM code-review gates invent new nitpicks on every re-run, trapping autonomous PR loops in infinite churn. Fix: persist typed review findings in a state file keyed by diff hunk so resolved or explicitly waived items are never re-raised on subsequent passes.

Where to invest engineering time

If you are designing an agent system for an enterprise or high-growth product today: spend one day on the model loop, one week on deterministic tool/ACL/idempotency boundaries, and the rest of the quarter on an environment-state evaluation harness fed directly by production failure traces. Models improve every quarter for free; your authorization boundaries and evaluation corpus are the only compounding moat you own.

Code & related teardowns: devin-harness (MIT) ↗ · production-starter (MIT) ↗ · Multimodal agent SaaS architecture · On-prem LLM serving · PostgreSQL internals