Agent = Model + Execution Harness

Agent Kernel (`agent_kernel`)

A framework-free execution kernel written in Python 3.12 with Pydantic v2 contracts, SQLite append-only episodic storage, a 7-state finite state machine, a Tri-State Memory Quarantine write gate, Hybrid RRF retrieval, an in-memory bidirectional Knowledge Graph, and Pearlian Structural Causal Models. Verified across 165 automated `pytest` tests.

Launch 7-State FSM Sandbox View Source on GitHub (yogami/agent-kernel) View Empirical Benchmarks Read "The Missing Compiler" Essay →
7-State Bounded FSM (`max_steps=5`)
0.025ms 3-Hop Graph Traversal
0.0% Contradiction Memory Writes
RRF k=60 Hybrid BM25 + Dense RAG
165 Tests Pytest Verification Suite

1. Why Non-Coding Agents Need a Runtime Compiler

Software coding agents benefit from a built-in deterministic oracle: the compiler, static type checker, and unit test suite. When a coding agent invents a method signature, `rustc` or `pytest` halts execution immediately and returns a stack trace with line numbers.

Agents operating in clinical decision support, medical device compliance (EU MDR, ISO 14971), or pharmaceutical product specification parsing (80-page Summary of Product Characteristics / SmPC dossiers) lack a natural compiler. Without an external execution harness, generic ReAct tool loops exhibit three recurring failure modes:

We built `agent_kernel` using Hexagonal Architecture (`domain/ports.py`) to enforce deterministic runtime invariants around stochastic language models while keeping domain policies decoupled in declarative config packs (`config/packs/vN/` and `policies/*.json`).

2. Step-Budgeted Finite State Machine (`core/execution_loop.py`)

The inner loop of `agent_kernel` (`core/execution_loop.py` and `domain/state_machine.py`) forbids open-ended `while True` tool recursion. Every turn executes inside an explicit seven-state machine with a fail-closed error transition (`FAIL_CLOSED`), governed by hard step limits (default `max_steps = 5` raising `BudgetExceededError`), token and USD cost ceilings, and a signature cycle detector that raises `LoopDetectedError` if an identical `(tool_name, canonical_args)` invocation repeats.

State 01 COMPOSE_CONTEXT

`core/context_ram.py` assembles promoted `semantic_facts` (wrapped in untrusted data delimiters), Hybrid RAG chunks, and causal DAG state.

State 02 MODEL_CALL

`infrastructure/llm_adapter.py` dispatches structured reasoning with active config pack rules and span telemetry (`ops/telemetry.py`).

State 03 VALIDATE_TOOL_CALL

Validates closed Pydantic v2 tool schemas (`tools/registry.py`) and checks sliding-window signature history for loop cycles.

State 04 INTERVENTIONAL_GATE

`core/causal_gate.py` & `core/graph_memory.py` execute pre-flight multi-hop graph assertions and Pearlian $do(X)$ causal simulations.

State 05 EXECUTE_TOOL

Runs sandboxed tool handlers (`core/sandbox/`) with path-traversal guards, network isolation, and deterministic audit logging.

State 06 VALIDATE_OUTPUT

`core/guardrails.py` enforces PHI/PII output redaction (`PAT-*`, `MRN:*`), citation checks, and bounded In-Flight Agent Steering retries.

State 07 PERSIST_EPISODE

Writes immutable turn trace to `episodes` (`sqlite_episode_store.py`) and routes candidate facts into `fact_quarantine`.

Interactive 7-State FSM & Tri-State Memory Airlock Simulator

Test how agent_kernel evaluates 3-hop pharmacological contraindications and filters ungrounded candidate facts before promoting to semantic_facts.

Ready
Click "Run 7-State Kernel Cycle" to inspect state transitions, SQLite table routing, and WebCrypto SHA-256 episode receipt.

3. Core Kernel Subsystems & File Architecture

Memory Plane · `core/memory_promoter.py`

Tri-State Memory Quarantine

To prevent unverified model assertions from poisoning future context, persistence (`infrastructure/sqlite_fact_store.py`) is split across three isolated tables:

  • episodes: Append-only immutable log of raw turns and tool calls.
  • fact_quarantine: Staging airlock where all candidate extractions land with `PENDING` status. Retrieval queries never read quarantine.
  • semantic_facts: Promoted store. Promotion requires passing closed Pydantic schema validation, semantic neighborhood contradiction checks, confidence thresholding (`score ≥ 0.85`), and SCM causal consistency verification.
Retrieval Plane · `infrastructure/hybrid_rag.py`

Hybrid RAG with RRF ($k=60$)

Dense embeddings miss exact clinical or regulatory codes (`ICD-10 I10`, `ISO-14971-7.4`, `SNOMED:73211009`). Our retrieval engine combines:

  • BM25 sparse lexical indexing for exact identifier and dosage matching.
  • Dense cosine vector index (`infrastructure/vector_index.py`) with metadata filtering.
  • Reciprocal Rank Fusion ($k = 60$) merging lexical and dense rankings, paired with cross-encoder reranking in enterprise adapters.
  • Strict provenance formatting attaching document, section, paragraph, and table coordinates to every retrieved chunk.
Graph Plane · `core/graph_memory.py`

25-Microsecond Knowledge Graph

`core/graph_memory.py` implements an in-memory bidirectional adjacency index (forward and reverse maps) with Radon Cyclomatic Complexity $\le 3$ across all 22 code blocks.

Before any tool executes, the graph gate traverses 1-to-3 hop transitive paths (such as brand-to-ingredient and drug-class cross-reactivity chains) in `0.025ms` (25 microseconds), while path-filtering preserves non-hazardous edges (`treats`) with a 0.0% false-positive rate on clean controls.

Causal Plane · `core/causal_graph.py`

Pearlian Structural Causal Gate

`core/causal_graph.py` and `core/causal_reasoner.py` implement Judea Pearl's three-level causal hierarchy:

  • Level 2 Interventional $do(X = x)$: Mutilates the causal DAG $G_{\bar{X}}$ by severing incoming arrows to $X$, simulating downstream organ stress or system load before physical tool execution.
  • Level 3 Counterfactuals: Runs the 3-step Abduction $\rightarrow$ Action $\rightarrow$ Prediction algorithm on failed episodes to isolate minimal root causes.
Policy Plane · `core/policy_engine.py`

Declarative Domain Packs

Mechanism is strictly separated from domain policy. The kernel loads versioned configuration packs (`config/packs/vN/`) and declarative policy manifests (`policies/clinical_contraindications.json`, `policies/renal_dosing.json`, `policies/fintech_trading_rules.json`).

In enterprise deployments, the same Hexagonal ports (`domain/ports.py`) bind to YAML Domain Packs for ISO 14971 medical device traceability and pharmaceutical SmPC extraction with OpenTelemetry in-flight steering.

Outer Loop · `ops/self_healer.py`

Monotonic Self-Healing Evaluator

`ops/self_healer.py` diagnoses failed traces on `evals/dev/`, uses counterfactual attribution to propose a candidate config pack (`config/packs/vN+1/`), and runs `ops/eval_runner.py` across three frozen splits:

`evals/golden/` (0% regression allowed), `evals/dev/` (diagnostic target), and `evals/holdout/` (sealed generalization set). Candidate packs commit only if both `golden` and `holdout` pass; otherwise the healer rolls back automatically.

4. Kernel Repository Layout & Declarative Domain Pack (`DomainPack`)

Below is the verified Hexagonal directory layout of `agent_kernel` alongside an example declarative Domain Pack manifest illustrating how ontology edges and in-flight steering rules are specified:

agent_kernel/
├── domain/                      # Pure business logic & typed Pydantic v2 contracts
│   ├── models.py                # Turn, Episode, CandidateFact, SemanticFact
│   ├── ports.py                 # Protocol interfaces (LLMProvider, Stores, Tools)
│   └── state_machine.py         # 7-state FSM transitions & BudgetExceeded/LoopDetected errors
├── core/                        # Kernel orchestration services
│   ├── execution_loop.py        # Step-budgeted FSM engine (max_steps=5, loop breaker)
│   ├── memory_promoter.py       # Tri-State admission gate (Quarantine -> Validate -> Promote)
│   ├── graph_memory.py          # 0.025ms bidirectional adjacency Knowledge Graph
│   ├── causal_graph.py          # Pearlian SCM DAGs, do(X) mutilation, Level 3 counterfactuals
│   ├── policy_engine.py         # Declarative policy evaluation engine
│   └── guardrails.py            # Deterministic PHI/PII output firewall & steering hooks
├── infrastructure/              # Pluggable adapters implementing domain/ports.py
│   ├── sqlite_episode_store.py  # Append-only immutable episode log
│   ├── sqlite_fact_store.py     # Tri-state tables (episodes, fact_quarantine, semantic_facts)
│   ├── hybrid_rag.py            # BM25 + Dense Cosine + Reciprocal Rank Fusion (k=60)
│   └── mcp_server.py            # Anthropic Model Context Protocol (JSON-RPC 2.0) server
├── ops/                         # Evaluation, Prometheus telemetry & Self-Healer
│   ├── run_abc_clinical_eval_v2.py # Live frontier LLM A/B/C evaluation runner
│   ├── benchmark.py             # 100-record Synthea longitudinal stress simulator
│   └── self_healer.py           # Monotonic golden/dev/holdout non-regression healer
└── tests/                       # 165 passing pytest unit & integration tests (~5s)

Enterprise YAML Domain Pack Extension (ISO 14971 / Pharma SmPCs)

Because `domain/ports.py` abstracts storage and policy evaluation behind Python `Protocol` interfaces, scaling from local SQLite + JSON policies (`policies/*.json`) to enterprise regulatory graphs requires only a declarative YAML Domain Pack manifest:

domain_name: "medtech_iso14971_traceability"
version: "2.1.0"

ontology:
  entity_types: [ProductRequirement, Hazard, HazardousSituation, Harm, RiskControl, VerificationProtocol]
  allowed_relations:
    - [ProductRequirement, exposes_hazard, Hazard]
    - [Hazard, mitigated_by, RiskControl]
    - [RiskControl, verified_by, VerificationProtocol]

memory_airlock:
  min_confidence: 0.85
  require_verbatim_span_citation: true
  mandatory_trace_links:
    Hazard: ["mitigated_by"]
    RiskControl: ["verified_by"]

in_flight_steering:
  max_retries: 2
  validators:
    - rule: "no_unmitigated_high_severity_hazard"
      severity: "BLOCKING"
      correction_template: >
        Hazard {{entity_id}} has severity={{severity}} but no linked RiskControl edge.
        Re-scan section {{section_ref}} for mitigation controls or mark status=QUARANTINED.

5. Empirical Benchmarks & Methodological Disclosures

We evaluate `agent_kernel` across three distinct test harnesses in the repository (`ops/run_abc_clinical_eval_v2.py`, `ops/benchmark.py`, and `ops/run_multihop_cell_b.py`). To maintain strict scientific integrity, live frontier API measurements are reported separately from deterministic pipeline simulations.

5.1 Live Frontier LLM Head-to-Head Evaluation (`ABC_CLINICAL_EVALUATION_V2.md`)

Executed against live frontier model APIs (`AsyncGeminiAdapter` running `gemini-3.5-flash-lite`) across $N = 12$ multi-hop clinical encounters (`evals/mtsamples/mtsamples_v2.jsonl`) containing planted temporal contradictions, renal dosing constraints, and multi-drug interactions:

Evaluation Metric (Live API, N=12) Track A: Raw Frontier LLM Track B: Generic ReAct Harness Track C: `agent_kernel`
Memory Contradiction Writes (Lower is better) 33.3% 33.3% 0.0% (Quarantined)
Drug Contraindication Escapes (Lower is better) 0.0% 8.3% (Skipped tool call) 0.0% (Pre-flight Graph Gate)
PHI / PII Data Exposure Rate (Lower is better) 8.3% 8.3% 0.0% (Output Firewall)
Median End-to-End Turn Latency (P50) 7.3s 18.7s 5.4s
Why Track B (Generic ReAct Harness) Escaped on Contraindications (8.3%): In Track B, the agent was provided with drug-interaction lookup tools, but tool invocation was left to the LLM's probabilistic choice. When the model assumed a prescription was benign, it bypassed tool execution entirely. In Track C (`agent_kernel`), `INTERVENTIONAL_GATE` runs deterministically in the state machine before any output is emitted, eliminating probabilistic tool-skipping and cutting P50 latency from 18.7s to 5.4s by avoiding multi-turn ReAct meandering.

5.2 High-Volume Longitudinal Pipeline Simulation (`BENCHMARK_REPORT.md`)

To profile memory table growth, loop breaking, and admission control overhead across 100 multi-encounter Synthea patient records (200 encounters) without incurring live LLM token spend, `ops/benchmark.py` runs a deterministic pipeline stress test:

Simulation Metric (100 Records / 200 Encounters) System A: Flat Un-Gated RAG System A+: Schema-Checked System B: `agent_kernel`
Fact Contradiction Rate in Active Memory 12.5% 12.5% 0.0% (25 items trapped in quarantine)
Schema Breakage Rate 12.5% 0.0% 0.0%
Simulated PII / PHI Leakage Rate 100.0% 87.5% 0.0% (`DeidentifyTextTool` + Firewall)
Runaway Loop Incidents 12.5% 0.0% 0.0% (`max_steps=5` + Cycle Breaker)
Algorithmic State-Machine Overhead (p95) 15.0 ms 10.0 ms 7.7 ms

5.3 Multi-Hop Knowledge Graph Ablation & Audit (`MULTIHOP_GRAPH_ABLATION_REPORT.md`)

Evaluated across 20 clinical fixtures in `evals/multihop/dataset.json` testing 1-hop direct allergies, 2-hop brand-to-ingredient links (`Augmentin -> Amoxicillin`), 3-hop class cross-reactivity, and 5 clean controls:

Graph Traversal Dimension (N=20 Fixtures) Cell A: 1-Hop Flat Lookup Cell B: `core/graph_memory.py` (k-Hop)
1-Hop Direct Allergy Interception 100.0% (5/5) 100.0% (5/5)
2-Hop Brand-to-Ingredient Interception 0.0% (0/5) 100.0% (5/5)
3-Hop Class Cross-Reactivity Interception 0.0% (0/5) 100.0% (5/5)
Clean Control False Positive Rate 0.0% (0/5) 0.0% (0/5)
Median In-Memory Traversal Latency (P50 / P95) 0.0224 ms (P50) 0.0052 ms (P50) / 0.025 ms (P95)
Mandatory Methodological Disclosure (`MULTIHOP_GRAPH_ABLATION_REPORT.md`): `core/graph_memory.py` resolves 3-hop relational paths in 25 microseconds (P95) with zero false positives on clean controls. However, as documented in our repository's internal audit report, Cell A in this 20-fixture micro-benchmark only ingested patient chart facts (`chart_facts`) and performed a 1-hop string equality check (`fact.object.lower() == prompt_drug.lower()`), whereas Cell B was populated with the brand-to-ingredient and class cross-reactivity ontology triples. If those same ontology triples are loaded into a relational SQLite/PostgreSQL schema and queried with a 3-way `JOIN` or `WITH RECURSIVE` CTE, relational SQL also achieves 100% recall on 2-hop and 3-hop paths. The architectural advantage of `core/graph_memory.py` is ergonomics and sub-25-microsecond in-memory adjacency traversal for arbitrary $k$-hop paths without writing multi-join SQL per hop depth.

Discuss Runtime Harnesses or Inspect Our Papers

Have questions about our step-budgeted FSM, Tri-State Memory Quarantine, or Knowledge Graph verification gates? Reach out directly for architectural discussions or research exchange.

Get in Touch Read "The Missing Compiler" Essay All Lab Research Papers