Every autonomous system follows one structural identity: Agent = Model + Harness. In software engineering agents, the compiler, static type checker, and test runner provide an automatic deterministic harness. When a model invents a nonexistent struct field in Rust or breaks an interface contract in TypeScript, the compiler rejects the syntax tree within milliseconds and emits a precise line number. Domain agents operating outside software engineering have no native compiler.
1. What Happens Without a Runtime Compiler
Consider two concrete domain tasks we engineered harnesses for in our lab. The first parses 80-page pharmaceutical Summary of Product Characteristics (SmPC) regulatory dossiers to populate structured drug-safety graphs (mapping active substances, posology, contraindications, and adverse reactions to SNOMED CT and MedDRA ontologies). The second maintains end-to-end Design History File traceability for Class IIb and Class III medical devices under EU MDR and ISO 14971.
When an unconstrained language model processes these documents through a standard prompt-and-tool loop, three failure modes appear consistently across runs:
- Completeness Decay (Underextraction): On a multi-page clinical table listing 48 distinct adverse reactions across organ classes, raw models routinely extract 32 to 36 entries and terminate the JSON array early. Nothing crashes. The JSON is syntactically valid, so a basic schema parser marks the run as a success while 25% of the regulatory record is silently dropped.
- Ungrounded Attribute Synthesis: When a table cell spans a page boundary or uses nested footnotes for pediatric dosing intervals, the model interpolates plausible numbers rather than flagging an ambiguous span.
- Ontology Resolution Drift: Clinical text uses surface phrasing such as "elevated blood sugar" or "transient renal impairment." Without deterministic entity resolution against MedDRA or SNOMED CT concept IDs, the agent creates duplicate nodes that fracture downstream graph queries.
2. Why Prompt Stuffing Fails: Attention Dilution
The instinctive reaction to domain extraction errors is to append more rules to the system prompt. After a few weeks of production incidents, teams end up with a 15,000-token system prompt containing dozens of negative constraints, edge-case tables, and formatting warnings.
That approach hits an immediate wall. Transformer attention degrades across long middle contexts. When 80 pages of PDF markdown compete with 40 pages of static prompt instructions, adherence to individual edge-case rules drops sharply, latency climbs on every turn, and fixing one rule regressions another.
Instead of front-loading every possible domain exception into the static prompt, we moved domain enforcement out of the prompt and into the execution harness. We keep the initial system instructions minimal and apply contextual verification rules in-flight only when the agent touches a specific entity class or tool boundary.
3. The Six-Layer Agent Harness Architecture
In agent_kernel, we organize runtime control into six composable layers that surround the model:
┌──────────────────────────────────────────────────────────────────────┐
│ 1. WORKFLOWS Bounded 7-State FSM (Step, Token & USD Budgets) │
│ 2. SKILLS Typed Pydantic/JSON Schemas + Span Provenance │
│ 3. HOOKS OpenTelemetry (traceparent) Span Interceptors │
│ 4. GUARDRAILS Tri-State Memory Airlock & Ontology Validators │
│ 5. REVIEW LOOPS In-Flight Steering (Capped at 2 Hot-Context Retries)│
│ 6. ESCALATION Quarantine Queue with Side-by-Side Span Diffs │
└──────────────────────────────────────────────────────────────────────┘
In-Flight Agent Steering via OpenTelemetry Hooks
During the VALIDATE_OUTPUT state of our finite state machine, the agent emits a structured candidate payload before any database commit occurs. An OpenTelemetry span processor intercepts the candidate payload and runs deterministic domain validators against both the source document AST and the target ontology.
For pharmaceutical SmPC extraction, the validator compares the count of table rows in the parsed layout tree (extracted via Docling / PyMuPDF structural blocks) against the number of emitted JSON entities, verifies that every quoted source_span exists verbatim at the reported character offsets (char_start..char_end), and resolves clinical terms against a local SNOMED CT / MedDRA lookup index.
When the validator detects that 12 rows were skipped on page 44, or that a term failed ontology resolution, it does not abort the run or accept partial data. It injects a targeted, four-line steering prompt back into the active conversation state while the document remains hot in the model's KV cache:
[HARNESS STEERING INTERVENTION · RETRY 1/2]
Section 4.8 Table 2 (Page 44, rows 37-48) contains 12 unextracted table rows
under 'Hepatobiliary disorders' and 'Renal and urinary disorders'.
Emit only the missing AdverseReaction entities with verbatim char_start..char_end
offsets, or emit ExplicitAbstention if the rows are header dividers.
Because the correction arrives only when needed and points to exact structural coordinates, even smaller, faster models recover missing entities without losing precision. We cap steering loops strictly at 2 retries. If a candidate still fails validation on the second retry, the harness transitions deterministically to PERSIST_EPISODE with status QUARANTINED_FOR_HUMAN_REVIEW.
4. Tri-State Memory Quarantine: Stopping State Poisoning
Multi-agent and long-horizon workflows fail catastrophically when an early hallucination is written into shared long-term memory. Once a false claim enters a vector store or relational table, subsequent retrieval steps read it back as established fact.
Our harness (`core/memory_promoter.py` backed by SQLite in `infrastructure/sqlite_fact_store.py` or PostgreSQL via `domain/ports.py`) enforces a strict Tri-State Memory Airlock:
episodes(Immutable Audit Log): Every raw model generation, tool call, steering intervention, and latency trace is recorded append-only.fact_quarantine(Staging Airlock): Candidate domain facts extracted during an episode land here first with `PENDING` status. They are invisible to standard agent retrieval queries.semantic_facts(Promoted Store): A fact moves from quarantine tosemantic_factsonly after passing closed Pydantic schema validation, semantic neighborhood contradiction checks, confidence thresholding (score ≥ 0.85), and causal consistency checks against the domain Structural Causal Model.
In our live frontier model evaluation (`ops/run_abc_clinical_eval_v2.py` across $N=12$ multi-hop clinical encounters), un-gated models and generic ReAct harnesses wrote contradictory claims into active memory in 33.3% of encounters, and in our 100-record longitudinal Synthea stress test (`ops/benchmark.py`, 200 encounters), un-gated RAG suffered a 12.5% contradiction rate. The Tri-State Memory Airlock trapped all 25 conflicting assertions in `fact_quarantine`, reducing active memory contradictions to 0.0%.
5. Knowledge Graph Traceability & 25-Microsecond Blast-Radius Analysis
Hybrid retrieval (combining dense cosine embeddings with sparse BM25 lexical search via Reciprocal Rank Fusion $k=60$ in `infrastructure/hybrid_rag.py`) solves passage lookup. It does not solve transitive dependency analysis.
In medical device compliance (ISO 14971 and IEC 62304), regulatory state is a directed graph:
ProductRequirement (REQ-104: Infusion Pump Flow Rate Controller)
└── exposes_hazard ──> Hazard (HAZ-019: Over-infusion > 5% tolerance)
├── leads_to ──> HazardousSituation (SIT-008: Bolus overdose during titration)
└── mitigated_by ──> RiskControl (RC-042: Dual-channel hardware watchdog timer)
└── verified_by ──> VerificationProtocol (VP-211: Fault-injection bench test)
When an engineer modifies REQ-104 or updates a firmware parameter via webhook, asking a vector database "which verification protocols are invalidated by this requirement change?" fails because VP-211 shares almost no lexical or semantic overlap with the high-level requirement text.
agent_kernel (`core/graph_memory.py`) maintains an in-memory bidirectional adjacency index (with Radon Cyclomatic Complexity $\le 3$ across all 22 code blocks). Before any state-mutating tool call executes, the harness traverses $k$-hop transitive paths in 0.025 milliseconds (25 microseconds at P95), pairs that structural traversal with a Pearlian $do(X)$ interventional simulation on the domain's Structural Causal Model (`core/causal_graph.py`), and blocks any tool execution that triggers a downstream hazard or contraindication.
6. Decoupling Mechanism from Policy
The central design rule of agent_kernel is borrowed directly from operating system design: separate mechanism from policy. The Python execution engine knows how to enforce step budgets, intercept OpenTelemetry spans, run Reciprocal Rank Fusion, quarantine unverified facts, and traverse $k$-hop graphs. It knows nothing about pharmaceutical SmPCs, ISO 14971 hazards, or power-grid transformers until it loads a declarative YAML DomainPack at startup.
By treating the execution harness as a deterministic compiler around a stochastic reasoning core, we can deploy small, low-latency models on complex regulatory and engineering workflows without sacrificing auditability or safety invariants.