\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).

\paragraph{SkillOrganism Substrate Integration.}
\label{sec:substrate-integration}
The \texttt{SkillOrganism} runtime (\S\ref{sec:multi-cellular}) composes the three-layer context model described in \S\ref{par:three-layer-context}. An optional \texttt{substrate: BiTemporalMemory} parameter attaches a bi-temporal fact store to the organism. When present, the run loop is extended with a read path and a write path at each stage boundary:

\begin{verbatim}
organism = skill_organism(
    stages=[research, strategist, evaluator, adversary],
    fast_nucleus=fast, deep_nucleus=deep,
    substrate=BiTemporalMemory(),
)
\end{verbatim}

\noindent\textit{Read path.}
Before a stage executes, the runtime evaluates its \texttt{read\_query} field---either a subject string or a callable returning a \texttt{BiTemporalQuery}---and packages the result into a frozen \texttt{SubstrateView(facts, query, record\_time)}. This view is injected into the stage's metadata (for agent stages) or passed as an additional argument (for handler stages, via arity-aware dispatch). The \texttt{record\_time} captures the moment of the read, establishing the record-time horizon for this stage's knowledge.

\noindent\textit{Write path.}
After a stage executes, two mechanisms can emit facts: (1)~the convenience flag \texttt{emit\_output\_fact=True} auto-records the stage output with \texttt{subject=task}, \texttt{predicate=stage.name}; (2)~a \texttt{fact\_extractor} callable converts the stage result into one or more factual events. Each event specifies an operation---assert, correct, or invalidate---and is applied to the substrate via the standard \texttt{BiTemporalMemory} write API. The stage name serves as the default \texttt{source} for provenance.

When \texttt{substrate} is \texttt{None} (the default), the run loop is unchanged: no datetime operations are invoked, no metadata is injected, and all four original lifecycle hooks remain unmodified. Existing tests pass without alteration.

The integration directly enables the audit question from \S6.5: given a completed run, \texttt{retrieve\_belief\_state(at\_valid=t, at\_record=t\_stage)} reconstructs exactly what the organism believed at the moment stage $X$ executed, even if subsequent stages corrected or invalidated facts. Example~71 demonstrates this with a four-stage enterprise workflow where an adversary stage corrects a research assumption, and the original belief state remains fully reconstructible.

\paragraph{PatternLibrary Implementation.}
\label{sec:pattern-library-impl}
The \texttt{PatternLibrary} provides evolutionary memory for collaboration patterns. Templates are stored in an in-memory dictionary keyed by \texttt{template\_id}; run records accumulate in a list. The \texttt{top\_templates\_for(fingerprint)} method scores each template against a query fingerprint using a weighted combination of task-shape match (0.30), tool-count proximity (0.15), subtask-count proximity (0.15), required-role Jaccard overlap (0.20), tag Jaccard overlap (0.10), and historical success rate (0.10). This simple retrieval mechanism is intentionally stateless and deterministic, with richer adaptation (experience-driven scoring, decay) planned for Phase~4.

\paragraph{WatcherComponent Implementation.}
\label{sec:watcher-impl}
The \texttt{WatcherComponent} is a \texttt{SkillRuntimeComponent} that classifies stage-level signals into three categories following Dupoux et al.~\cite{dupoux2026learning}: \emph{epistemic} (from \texttt{EpiplexityMonitor}), \emph{somatic} (from \texttt{ATP\_Store}), and \emph{species-specific} (from \texttt{ImmuneSystem}). All signal sources are optional; the watcher is a no-op when none are attached.

After each stage, the watcher evaluates collected signals against configured thresholds and may write a \texttt{WatcherIntervention} to \texttt{shared\_state}. The run loop checks for this key after component hooks complete and before the \texttt{halt\_on\_block} guard. Three intervention kinds are supported: \texttt{RETRY} re-executes the current stage; \texttt{ESCALATE} re-executes with the deep nucleus; \texttt{HALT} breaks the stage loop. Component hooks are not re-invoked after retry or escalation, preventing recursive intervention loops.

The intervention-count convergence signal operationalizes the BIGMAS finding~\cite{hao2026bigmas}: when the ratio of interventions to observed stages exceeds \texttt{max\_intervention\_rate} (default 0.5), the watcher emits a non-convergence HALT. Example~73 demonstrates all three intervention paths.

\paragraph{Adaptive Assembly Implementation.}
\label{sec:adaptive-impl}
The \texttt{AdaptiveSkillOrganism} wrapper composes the full adaptive loop. The public factory \texttt{adaptive\_skill\_organism(task, fingerprint, library, ...)} auto-fingerprints the task if no fingerprint is provided, queries \texttt{PatternLibrary.top\_templates\_for()} for the best template, and calls \texttt{assemble\_pattern()} to convert the template's \texttt{stage\_specs} into a runnable topology (dispatching on \texttt{topology}: \texttt{skill\_organism}, \texttt{reviewer\_gate}, \texttt{specialist\_swarm}, or \texttt{single\_worker}). A \texttt{WatcherComponent} and \texttt{TelemetryProbe} are automatically attached.

After execution, the wrapper records a \texttt{PatternRunRecord} in the library (closing the scoring feedback loop) and populates the watcher's experience pool with \texttt{ExperienceRecord} instances for each intervention. The experience pool persists across runs: when rule-based decision logic returns no intervention, the watcher consults past experiences with matching (stage, signal category, fingerprint shape) and recommends the intervention kind that was most often successful. Rule-based decisions always take priority; experience is a fallback. Example~74 demonstrates the full lifecycle; Example~75 demonstrates experience-driven recommendations.

\paragraph{Cognitive Mode Annotations.}
\label{sec:cognitive-modes-impl}
The \texttt{CognitiveMode} enum classifies stages as \texttt{OBSERVATIONAL} (System~A: passive sensing, information gathering) or \texttt{ACTION\_ORIENTED} (System~B: active decision-making, execution). The annotation is an optional field on \texttt{SkillStage}; when absent, it is inferred from the existing \texttt{mode} field (\texttt{fast}/\texttt{fixed} $\to$ \texttt{OBSERVATIONAL}, \texttt{fuzzy}/\texttt{deep} $\to$ \texttt{ACTION\_ORIENTED}). The \texttt{WatcherComponent} collects cognitive-mode signals and reports mode mismatches (e.g., an observational stage routed to the deep nucleus) as informational epistemic signals. The \texttt{mode\_balance()} method summarizes the System~A/B distribution across a run.

\paragraph{Sleep Consolidation Implementation.}
\label{sec:consolidation-impl}
The \texttt{SleepConsolidation} class composes \texttt{AutophagyDaemon}, \texttt{PatternLibrary}, \texttt{EpisodicMemory}, \texttt{HistoneStore}, and optionally \texttt{BiTemporalMemory} into a five-step post-batch consolidation cycle: (1)~prune stale context via autophagy, (2)~replay successful run records and promote them from WORKING to EPISODIC tier in episodic memory, (3)~compress recurring high-success patterns into new consolidated \texttt{PatternTemplate} instances, (4)~run counterfactual replay over bi-temporal corrections to detect cases where updated facts would have changed the outcome, and (5)~promote frequently-accessed ACETYLATION histone marks to permanent METHYLATION.

The \texttt{counterfactual\_replay()} function performs static analysis: it calls \texttt{diff\_between(run\_time, now, axis="record")} to find corrections that occurred after the original run, then matches corrected fact subjects/predicates against stage names in the template. When matches are found, it reports that the outcome may have differed, without re-executing the workflow. Example~77 demonstrates the full consolidation cycle.

\paragraph{Social Learning Implementation.}
\label{sec:social-learning-impl}
The \texttt{SocialLearning} class wraps a \texttt{PatternLibrary} with peer-exchange semantics. \texttt{export\_templates()} filters by success rate and run count; \texttt{import\_from\_peer()} computes an effective score (peer success rate $\times$ trust score) for each template and adopts those exceeding the adoption threshold. The \texttt{TrustRegistry} uses exponential moving average: $s_{t+1} = \alpha \cdot \text{outcome} + (1-\alpha) \cdot s_t$ with $\alpha=0.3$, giving more weight to recent outcomes. Provenance tracking maps each adopted template to its source peer, enabling trust updates when adoption outcomes are recorded. The watcher's curiosity signals extend the epistemic signal category with a \texttt{source="curiosity"} derived from \texttt{EpiplexityMonitor}'s EXPLORING status, triggering ESCALATE when embedding novelty exceeds a configurable threshold on fast models. Example~78 demonstrates template exchange; Example~79 demonstrates curiosity signals.

\paragraph{Developmental Staging Implementation.}
\label{sec:developmental-impl}
The \texttt{DevelopmentController} wraps a \texttt{Telomere} (composition, not inheritance) and maps the fraction of telomere consumed to a \texttt{DevelopmentalStage}: EMBRYONIC ($<10\%$), JUVENILE ($10\text{--}35\%$), ADOLESCENT ($35\text{--}70\%$), MATURE ($>70\%$). Thresholds are configurable via \texttt{DevelopmentConfig}; transitions are one-directional and never regress, even if telomeres are renewed. Learning plasticity decreases monotonically (1.0 at EMBRYONIC, 0.25 at MATURE).

\texttt{CriticalPeriod} frozen dataclasses declare time-limited learning windows by specifying \texttt{opens\_at} and \texttt{closes\_at} stages. The controller evaluates period status on each tick: once the organism passes \texttt{closes\_at}, the window is permanently shut. The \texttt{Plasmid} dataclass gains a \texttt{min\_stage} field; \texttt{Mitochondria.acquire()} checks the organism's current developmental stage before granting tool access. Teacher-learner scaffolding via \texttt{SocialLearning.scaffold\_learner()} filters templates by the learner's stage and applies a plasticity bonus to effective trust, enabling mature organisms to guide younger ones. Example~80 demonstrates the full lifecycle; Example~81 demonstrates scaffolding.

\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.
