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.
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`).
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.
`core/context_ram.py` assembles promoted `semantic_facts` (wrapped in untrusted data delimiters), Hybrid RAG chunks, and causal DAG state.
`infrastructure/llm_adapter.py` dispatches structured reasoning with active config pack rules and span telemetry (`ops/telemetry.py`).
Validates closed Pydantic v2 tool schemas (`tools/registry.py`) and checks sliding-window signature history for loop cycles.
`core/causal_gate.py` & `core/graph_memory.py` execute pre-flight multi-hop graph assertions and Pearlian $do(X)$ causal simulations.
Runs sandboxed tool handlers (`core/sandbox/`) with path-traversal guards, network isolation, and deterministic audit logging.
`core/guardrails.py` enforces PHI/PII output redaction (`PAT-*`, `MRN:*`), citation checks, and bounded In-Flight Agent Steering retries.
Writes immutable turn trace to `episodes` (`sqlite_episode_store.py`) and routes candidate facts into `fact_quarantine`.
Test how agent_kernel evaluates 3-hop pharmacological contraindications and filters ungrounded candidate facts before promoting to semantic_facts.
Click "Run 7-State Kernel Cycle" to inspect state transitions, SQLite table routing, and WebCrypto SHA-256 episode receipt.
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.Dense embeddings miss exact clinical or regulatory codes (`ICD-10 I10`, `ISO-14971-7.4`, `SNOMED:73211009`). Our retrieval engine combines:
`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.
`core/causal_graph.py` and `core/causal_reasoner.py` implement Judea Pearl's three-level causal hierarchy:
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.
`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.
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)
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.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.
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 |
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 |
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) |
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.