\section{Reference Implementation}

To instantiate the framework in executable form, we provide a reference implementation in Python.
The implementation, \texttt{operon-ai}\footnote{\url{https://github.com/coredipper/operon}}, is described in this section,
which summarizes key components and demonstrates that the abstractions in the paper translate into practical code.
It should be read as an executable prototype plus synthetic evaluation harness, not as complete empirical
validation of every biological analogy in the manuscript.

\subsection{Architecture Overview}

The implementation follows the biological organization:

\begin{itemize}[leftmargin=*]
\item \textbf{Core Types} (\texttt{core/types.py}): Signal, ActionProtein, FoldedProtein, CellState---the
categorical objects with their biological semantics.
\item \textbf{Core Wiring} (\texttt{core/wagent.py}): WiringDiagram, ModuleSpec, PortType, Wire,
DiagramExecutor---typed wiring with integrity labels and capabilities.
\item \textbf{Core Optics} (\texttt{core/optics.py}): PrismOptic, TraversalOptic,
ComposedOptic---wire-level conditional routing and batch transforms.
\item \textbf{Core Denaturation} (\texttt{core/denature.py}): StripMarkupFilter, NormalizeFilter,
ChainFilter---wire-level anti-injection sanitization.
\item \textbf{Core Coalgebra} (\texttt{core/coalgebra.py}): FunctionalCoalgebra, StateMachine,
ParallelCoalgebra, SequentialCoalgebra, finite-trace observational checking.
\item \textbf{Surveillance} (\texttt{surveillance/}): The immune system implementation with MHCDisplay,
TCell, Thymus, and ImmuneMemory components.
\item \textbf{Healing} (\texttt{healing/}): ChaperoneLoop implementing the structural self-healing pattern.
\item \textbf{Quality} (\texttt{quality/}): Chaperone protein with multi-strategy folding.
\item \textbf{Topology} (\texttt{topology/}): Network motifs including Quorum, Cascade, and Oscillator.
\item \textbf{Organelles} (\texttt{organelles/plasmid.py}): Plasmid,
PlasmidRegistry---capability-gated dynamic tool acquisition.
\item \textbf{Coordination} (\texttt{coordination/diffusion.py}): DiffusionField,
MorphogenSource---graph-based spatially varying morphogen gradients.
\item \textbf{Multi-cellular} (\texttt{multicell/}): CellType, ExpressionProfile, Tissue,
TissueBoundary---hierarchical multi-agent organization.
\end{itemize}

\subsection{Immune System Implementation}

The Adaptive Immunity motif is implemented as an integrated surveillance system:

\begin{verbatim}
@dataclass
class ImmuneSystem:
    thymus: Thymus          # Negative selection
    treg: RegulatoryTCell   # Tolerance/suppression
    memory: ImmuneMemory    # Threat signatures
    displays: dict[str, MHCDisplay]
    tcells: dict[str, TCell]
    profiles: dict[str, BaselineProfile]  # Trained baselines
\end{verbatim}

The \texttt{MHCPeptide} class captures behavioral fingerprints---statistical signatures of agent output
including response time distributions, vocabulary hashes, confidence patterns, and error rates. This
directly implements the MHC presentation concept from Section 4.7.

\paragraph{Two-Signal Activation.}
T-cell activation requires both signals:
\begin{verbatim}
class Signal1(Enum):
    SELF = "self"        # Matches baseline
    NON_SELF = "non_self"  # Anomalous behavior
    UNKNOWN = "unknown"  # Insufficient data (anergic)

class Signal2(Enum):
    NONE = "none"
    CANARY_FAILED = "canary"
    CROSS_VALIDATED = "cross"
    REPEATED_ANOMALY = "repeat"
    MANUAL_FLAG = "manual"  # Operator override
\end{verbatim}

An agent is only flagged when \texttt{Signal1 == NON\_SELF} \textbf{and} \texttt{Signal2 != NONE}.
This prevents false positives from transient anomalies, implementing the immunological requirement
for costimulation.

\subsection{Chaperone Implementation}

The Chaperone implements multi-strategy folding with provenance tracking:

\begin{verbatim}
class FoldingStrategy(Enum):
    STRICT = "strict"       # Exact JSON match
    EXTRACTION = "extraction"  # Find JSON in text
    LENIENT = "lenient"     # Type coercion
    REPAIR = "repair"       # Fix malformed JSON
\end{verbatim}

The \texttt{ChaperoneLoop} extends this into a healing loop where validation errors are fed back
to the generator:

\begin{verbatim}
class ChaperoneLoop:
    def heal(self, prompt: str) -> HealingResult:
        for attempt in range(self.max_retries + 1):
            raw = self.generator(prompt, error_context)
            folded = self.chaperone.fold_enhanced(raw, schema)
            if folded.valid:
                return HealingResult(HEALED, folded)
            error_context = self._format_error(folded)
        return HealingResult(DEGRADED, ubiquitin_tagged=True)
\end{verbatim}

This operationalizes the GroEL/GroES cage metaphor: the error trace becomes input to the
repair process, enabling context-aware correction.

\subsection{Trust and Provenance}

The implementation uses a simplified 3-level trust hierarchy that collapses the theoretical 4-level
model $\{U, T, S, R\}$ for practical deployment:

\begin{verbatim}
class IntegrityLabel(IntEnum):
    UNTRUSTED = 0   # User input, Retrieved, Self-generated
    VALIDATED = 1   # Schema-checked (Chaperone-folded)
    TRUSTED = 2     # Tool-grounded (deterministic output)
\end{verbatim}

This simplification merges \texttt{User}, \texttt{Retrieved}, and \texttt{Self} into \texttt{UNTRUSTED},
reflecting the common case where all non-tool sources require validation before trust elevation. The
full 4-level model can be recovered by subclassing \texttt{IntegrityLabel} with additional levels when
finer-grained provenance tracking is required.

The \texttt{ApprovalToken} carries explicit authorization metadata for privileged operations:

\begin{verbatim}
@dataclass(frozen=True)
class ApprovalToken:
    request_hash: str
    issuer: str
    reason: str = ""
    confidence: float = 1.0
    integrity: IntegrityLabel = IntegrityLabel.TRUSTED
    timestamp: datetime = field(default_factory=now)
\end{verbatim}

This operationalizes the Trust-Gated Lens: actions requiring high integrity must present an
\texttt{ApprovalToken} with sufficient integrity level.

\subsection{Plasmid Registry Implementation}

The Horizontal Gene Transfer mechanism (\S6.2) is implemented as a \texttt{PlasmidRegistry} with capability-gated acquisition:

\begin{verbatim}
@dataclass(frozen=True)
class Plasmid:
    name: str
    func: Callable[..., Any]
    required_capabilities: frozenset[Capability]
    tags: frozenset[str] = frozenset()

    def to_tool(self) -> SimpleTool:
        return SimpleTool(name=self.name, func=self.func,
                          required_capabilities=set(self.required_capabilities))
\end{verbatim}

The \texttt{Mitochondria} class is extended with \texttt{acquire()} and \texttt{release()} methods. When a \texttt{Mitochondria} instance is configured with an \texttt{allowed\_capabilities} envelope, acquisition checks $C_{\text{plasmid}} \subseteq C_{\text{agent}}$ before engulfing the tool; release implements plasmid curing. The registry supports both text search and pure tag filtering.

\subsection{Denaturation Layers Implementation}

The anti-prion defense (\S5.3) is implemented as wire-level filters conforming to a \texttt{DenatureFilter} protocol:

\begin{verbatim}
class DenatureFilter(Protocol):
    @property
    def name(self) -> str: ...
    def denature(self, value: str) -> str: ...
\end{verbatim}

Three concrete filters are provided:
\begin{itemize}[leftmargin=*]
\item \textbf{StripMarkupFilter}: Removes code blocks, ChatML tokens (\texttt{<|...|>}), \texttt{[INST]} tags, XML role tags (\texttt{<system>}, \texttt{<user>}), and role delimiters using compiled regex patterns.
\item \textbf{NormalizeFilter}: Applies Unicode normalization (NFKC), lowercasing, and control character removal to collapse homoglyph-based evasion.
\item \textbf{ChainFilter}: Composes multiple filters left-to-right.
\end{itemize}

Filters attach to wires in the \texttt{WiringDiagram}. The \texttt{DiagramExecutor} applies denaturation before optics: \texttt{denature} $\to$ \texttt{optic} $\to$ destination. This ensures that downstream agents receive sanitized data regardless of what the upstream agent produces.

\subsection{Multi-Cellular Organization Implementation}

The multi-cellular abstractions (\S6.5) are implemented in the \texttt{multicell/} package:

\paragraph{Cell Type Specialization.}
The \texttt{CellType} class encapsulates an \texttt{ExpressionProfile}---a mapping from gene names to expression levels (\texttt{OVEREXPRESSED}, \texttt{SILENCED}, etc.). Calling \texttt{differentiate(genome)} applies the profile to a shared \texttt{Genome}, producing a \texttt{DifferentiatedCell} with role-specific configuration. This implements the biological principle that a single genotype produces many
phenotypes.

\paragraph{Tissue Architecture.}
The \texttt{Tissue} class provides:
\begin{itemize}[leftmargin=*]
\item A \texttt{TissueBoundary} with typed input/output ports and a capability ceiling
\item Cell type registration with capability validation ($C_{\text{cell}} \subseteq C_{\text{tissue}}$)
\item Internal wiring via an embedded \texttt{WiringDiagram}
\item Optional \texttt{DiffusionField} for spatially varying morphogen gradients
\item Export as a \texttt{ModuleSpec} for organism-level composition
\end{itemize}

\paragraph{Metabolic-Epigenetic Coupling.}
The \texttt{HistoneStore} accepts an optional \texttt{energy\_gate} parameter pairing an \texttt{ATP\_Store} with a \texttt{MetabolicAccessPolicy}. When set, each \texttt{retrieve\_context()} call costs ATP. Under metabolic stress, only strongly embedded markers remain accessible; in the current implementation, marker strength serves as the cost proxy used to approximate Eq.~\eqref{eq:cost-gated-retrieval}.

\subsection{Bi-Temporal Memory Implementation}
\label{sec:bitemporal-impl}

The bi-temporal coalgebra (\S3.5) and temporal epistemic framework (\S6.5) are implemented in \texttt{operon\_ai/memory/bitemporal.py} as a standalone append-only fact store. The design deliberately avoids mutation: facts are frozen dataclasses, corrections close old records and append new ones, and point-in-time queries are pure filters.

\paragraph{Data Model.}
A \texttt{BiTemporalFact} carries 12 fields: subject/predicate/value triple, valid-time interval (\texttt{valid\_from}, \texttt{valid\_to}), record-time interval (\texttt{recorded\_from}, \texttt{recorded\_to}), source provenance, confidence, tags, and an optional \texttt{supersedes} pointer to the corrected fact. All facts are \texttt{@dataclass(frozen=True)}---a deliberate departure from the mutable \texttt{MemoryEntry} used by \texttt{EpisodicMemory}, justified by the append-only semantics.

\paragraph{Write Semantics.}
Three operations modify the store: \texttt{record\_fact()} inserts a new active record; \texttt{correct\_fact()} closes the old record's transaction interval via \texttt{dataclasses.replace()} and appends a new record with \texttt{supersedes} set; \texttt{invalidate\_fact()} marks a record as no longer active. The internal \texttt{\_facts} list is append-only except for the in-place close of \texttt{recorded\_to} on corrected records.

\paragraph{Retrieval.}
Three query methods implement the temporal epistemic operators: \texttt{retrieve\_valid\_at(at)} filters for facts valid at world-time \texttt{at} with active records only; \texttt{retrieve\_known\_at(at)} filters for facts recorded by system-time \texttt{at}; \texttt{retrieve\_belief\_state(at\_valid, at\_record)} intersects both axes, reconstructing the system's belief at any historical coordinate.

\paragraph{History and Audit.}
\texttt{history(subject)} returns all facts (including closed) sorted by record time; \texttt{diff\_between(t1, t2, axis)} computes set differences on either axis; \texttt{timeline\_for(subject)} returns all facts sorted by valid time. Together, these support the audit question: ``what changed between $t_1$ and $t_2$, and on which axis?''

This subsystem is intentionally decoupled from \texttt{HistoneStore} and \texttt{EpisodicMemory}. Integration bridges---converting histone marks to bi-temporal facts, or promoting episodic memories into the bi-temporal substrate---are planned for future work (\S9).

\subsection{Coalgebraic State Machines Implementation}

The coalgebra formalism (\S3.5) is made explicit and composable:

\begin{verbatim}
class Coalgebra(Protocol[S, I, O]):
    def readout(self, state: S) -> O: ...
    def update(self, state: S, inp: I) -> S: ...

@dataclass
class StateMachine(Generic[S, I, O]):
    state: S
    coalgebra: Coalgebra[S, I, O]
    trace: list[TransitionRecord] = field(default_factory=list)

    def step(self, inp: I) -> O: ...
    def run(self, inputs: list[I]) -> list[O]: ...
\end{verbatim}

\texttt{ParallelCoalgebra} and \texttt{SequentialCoalgebra} implement the composition operations from \S3.5. The \texttt{check\_bisimulation()} function tests observational equivalence (Eq.~\eqref{eq:bisimulation}) over an input sequence, returning a witness on divergence. Existing organelles (\texttt{HistoneStore}, \texttt{ATP\_Store}, \texttt{CellCycleController}) can be wrapped as coalgebras, enabling formal composition and finite-trace comparison of multi-organelle systems.

\subsection{Morphogen Diffusion Implementation}

The \texttt{DiffusionField} class implements the discrete-time diffusion dynamics (Eq.~\eqref{eq:morphogen-diffusion}):

\begin{verbatim}
class DiffusionField:
    def add_node(self, node_id: str): ...
    def add_edge(self, a: str, b: str, bidirectional=True): ...
    def add_source(self, source: MorphogenSource): ...
    def step(self):  # emit -> diffuse -> decay -> clamp
    def run(self, steps: int): ...
    def get_local_gradient(self, node_id) -> MorphogenGradient: ...
\end{verbatim}

Each \texttt{step()} applies four phases: emission (sources add morphogen), diffusion (concentration flows along edges, split evenly among neighbors), decay (uniform degradation), and clamping (enforce bounds). Nodes with no neighbors skip diffusion outflow, matching Eq.~\eqref{eq:morphogen-diffusion}'s isolated-node case. The \texttt{get\_local\_gradient()} method bridges to the existing \texttt{MorphogenGradient} API, enabling agents to read their local concentrations without awareness of the underlying graph dynamics.

\subsection{Optic-Based Wiring Implementation}

The wire-level optics (\S3.4) are implemented via an \texttt{Optic} protocol:

\begin{verbatim}
class Optic(Protocol):
    def can_transmit(self, data_type: DataType,
                     integrity: IntegrityLabel) -> bool: ...
    def transmit(self, value: Any, data_type: DataType,
                 integrity: IntegrityLabel) -> Any: ...
\end{verbatim}

Four concrete optics are provided:
\begin{itemize}[leftmargin=*]
\item \textbf{LensOptic}: Identity pass-through (equivalent to no optic).
\item \textbf{PrismOptic}: Transmits only if $\tau \in A$ (Eq.~\eqref{eq:prism-optic}). Enables fan-out routing.
\item \textbf{TraversalOptic}: Maps a transform over list elements (Eq.~\eqref{eq:traversal-optic}).
\item \textbf{ComposedOptic}: Chains optics left-to-right; all must accept.
\end{itemize}

Optics coexist with \texttt{DenatureFilter}s on the same wire. The \texttt{DiagramExecutor} processes them in order: denaturation $\to$ optic $\to$ destination. Prism rejection causes the wire to be skipped (not an error), enabling conditional routing patterns where different data types flow to different handlers.

\subsection{Interactive Demonstrations}

The repository also includes interactive Gradio demonstrations for individual organelles and composition
patterns---from single motifs (Membrane, Chaperone, Quorum Sensing) to multi-organelle orchestrations.
These demos are illustrative artifacts rather than controlled benchmarks.

\subsection{Evaluation Protocol (Synthetic Harness)}

We define a synthetic evaluation harness to exercise three motifs with reproducible procedures:
\begin{enumerate}[leftmargin=*]
\item \textbf{Chaperone Folding.} Generate JSON schemas with 3--8 required fields. Sample valid JSON and
apply 1--3 corruptions (e.g., missing quotes, trailing commas, type swaps, dropped fields). Measure the
fraction of outputs that can be folded into the schema under STRICT versus cascaded strategies
(EXTRACTION $\to$ LENIENT $\to$ REPAIR).
\item \textbf{Immune Detection.} Simulate agents with baseline distributions over response time,
vocabulary hash, structure hash, and confidence. Train on baseline samples, then introduce
``compromised'' agents by shifting distribution parameters and injecting anomalous hashes.
Measure sensitivity and false positive rate under the two-signal activation rule.
\item \textbf{Healing Loop.} Generate malformed outputs and run the ChaperoneLoop with and without
error-context feedback. Measure recovery within $k$ attempts (default $k=3$).
\end{enumerate}
These suites test whether the implemented motifs behave as intended under controlled corruption and anomaly
models; they do not estimate in-the-wild failure rates of production LLM systems.

\paragraph{Implementation.}
The harness is implemented in \texttt{eval/} with a JSON-configured CLI:
\begin{verbatim}
python -m eval.run --suite all --config eval/configs/default.json \
  --out eval/results/latest.json
\end{verbatim}
The output is a machine-readable JSON report (per-suite config + metrics) suitable for direct inclusion
in tables or plots.

\paragraph{Status.}
Synthetic runs indicate consistent qualitative gains within this harness (cascade $>$ strict, error-context $>$ blind retry,
immune detection $>$ chance). Table~\ref{tab:eval-summary} reports aggregated numeric results across
multiple seeds; real-world validation with LLM outputs remains ongoing.

\paragraph{Aggregated Results.}
We ran the harness across 100 deterministic seeds (1--100) using the default harness config
(\path{eval/configs/default.json}). The
aggregate results (pooled across seeds with Wilson 95\% intervals; $N$ is total pooled trials) are reported
in Table~\ref{tab:eval-summary}.

\paragraph{External Benchmark Suites.}
In addition to the synthetic suites above, the harness includes
suites derived from external benchmarks: (1)~function-call schemas from
the Berkeley Function Calling Leaderboard (BFCL)~\cite{patil2023gorilla}
test the Chaperone's folding pipeline against realistic tool-use schemas,
and (2)~prompt injection attack templates from
AgentDojo~\cite{debenedetti2024agentdojo} generate adversarial behavioral
shifts to test Immune System detection. These suites use the same
deterministic corruption and simulation methodology; results appear in the
lower section of Table~\ref{tab:eval-summary}.

\input{../eval/results/summary.tex}

\subsection{Limitations}

The current implementation has several limitations:

\begin{itemize}[leftmargin=*]
\item \textbf{Epiplexity:} Implemented with a mock embedding provider (\texttt{MockEmbeddingProvider}).
Integration with production embedding APIs and empirical calibration of the $\alpha$ mixing parameter
and threshold $\delta$ across diverse task types remain future work.
\item \textbf{Morphogen Diffusion:} The \texttt{DiffusionField} operates in a single process. Cross-agent
gradient propagation in distributed multi-process deployments with eventual consistency remains future work.
\item \textbf{Denaturation:} Filters target known syntactic patterns (ChatML, XML role tags, markdown
code blocks). Novel injection techniques using previously unseen syntax may bypass denaturation; custom
\texttt{DenatureFilter} implementations should be added as new attack patterns emerge.
\item \textbf{Finite-Trace Equivalence:} The \texttt{check\_bisimulation()} function tests over finite input sequences.
Coinductive bisimulation for infinite-trace systems is not yet supported.
\item \textbf{Benchmarking:} The evaluation harness covers synthetic suites and external benchmarks (BFCL,
AgentDojo). Real-world validation of the multi-cellular and diffusion components at production scale is
still in progress.
\end{itemize}

We release the implementation to enable further scrutiny and extension of the framework.
