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.
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.
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:
| Layer | Failure without it | Production mechanism |
|---|---|---|
| 1. Turn serialization | User sends a follow-up message mid-tool-call; two loops mutate session state concurrently | Single actor / queue per session with explicit policy (followup, steer, or interrupt) |
| 2. Idempotent side effects | Network retry after timeout sends duplicate email, double-charges wallet, or opens duplicate PR | Deterministic idempotency key persisted before external execution; terminal results replayed on retry |
| 3. Capacity admission | Webhook or cron burst spawns 200 concurrent agent loops, exhausting GPU KV-cache or API spend | Bounded worker slots + priority lane reserving capacity for interactive human turns over background sweeps |
| 4. Blast-radius isolation | Runaway shell command mutates sibling sessions, leaks .env, or hangs indefinitely | Per-attempt timeout + abort signal, isolated filesystem/container, and deterministic command/path blocklists |
| 5. Grounded provenance | Ungrounded model fabrication looks identical to a cross-tenant data leak, destroying user trust | Mandatory 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.
i-dot-aiOne 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:
i-dot-ai/redbox (6,000+ civil servants across Cabinet Office, No10, and
DSIT, up to OFFICIAL-SENSITIVE): When the team published their sunset reflections
(5 Key Lessons), usage telemetry revealed a humbling split: engineers built sophisticated
multi-step RAG pipelines for ministerial briefing packs, yet ~70% of real usage
was civil servants simply needing fast, secure, auditable LLM access on sensitive documents where
public SaaS tools were banned. The features that actually drove retention (NPS 56, ~2 hours saved
per week) were citation verification, strict security boundaries, and low-friction UX
— not exotic multi-agent choreography.i-dot-ai/lex (8.4M+ UK legislation and amendment records):
Demonstrates the clean modern pattern for domain grounding: instead of building another bespoke
chat silo, expose authoritative, version-aware hybrid semantic search (220K Acts + 892K
amendments) over an MCP (Model Context Protocol) server so any compliant host
(Claude Code, Cursor, internal agents) reasons over exact statutory revisions rather than stale
pretraining weights.pass@1 lies: passk and environment-state evalsAcademic 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 apass8of0.808 = 16.8%. Four out of five production users hitting that workflow repeatedly will experience a policy violation or broken state.
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):
0. Assert the post-run database rows, emitted tool
calls, and passing test suite deterministically.min aggregation across turns, never mean).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.While building and operating devin-harness across production repositories, five recurring agent failure modes forced specific deterministic countermeasures:
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.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.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.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.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.