\section{Formal Syntax: The Agentic Operad}

To formalize the composition of agents, we define the Operad of Wiring Diagrams, denoted as WAgent. An operad
can be understood as a ``grammar'' for connecting operations (boxes) via typed wires. It defines which agent
topologies are valid and allows us to reason about the properties of the composite system based solely on the
properties of its components~\cite{vagner2015algebras}.

\subsection{The Typing Rules}

In WAgent, every wire carries a specific Type $\tau\in T$.
\begin{equation}
T = \{\text{Text}, \text{JSON}, \text{Image}, \text{Error}, \text{ToolCall}, \text{Stop}, \text{Approval}\}.
\tag{6}
\end{equation}
These types correspond to biological molecular specificity (e.g., a specific transcription factor only binds to
a specific DNA sequence). A connection is valid if and only if the type of the output port of Agent $A$ matches
the type of the input port of Agent $B$.

\subsection{The Composition Operations}

The operad defines three fundamental operations for combining agents. Any complex agentic architecture, no
matter how large, can be decomposed into these three primitives.

\subsubsection{Parallel Composition ($\otimes$)}

Two agents, $A$ and $B$, execute simultaneously with no information exchange:
\begin{equation}
A \otimes B.
\tag{7}
\end{equation}
\begin{itemize}[leftmargin=*]
\item \textbf{Biological Analogy:} Two genes located on different chromosomes expressing proteins independently.
\item \textbf{Constraint:} This operation is valid only if the internal state spaces $S_A$ and $S_B$ are disjoint.
If they share a mutable memory store, the operation leaves the \textbf{independent-state interpretation} and
requires an explicit \textbf{resource-sharing} structure (e.g., a shared state component or a Resource Sharing
decorator).
\end{itemize}

\subsubsection{Serial Composition ($\circ$)}

The output of Agent $A$ is piped directly into the input of Agent $B$:
\begin{equation}
B \circ A.
\tag{8}
\end{equation}
\begin{itemize}[leftmargin=*]
\item \textbf{Biological Analogy:} A Signal Transduction Pathway (Protein A activates Protein B).
\item \textbf{Formal Verification:} This allows for static type checking of agent graphs. If Agent $A$ outputs
Natural Language but Agent $B$ expects JSON Schema, the composition is undefined in WAgent. This moves runtime
\textbf{type/schema mismatch} errors to ``compile-time'' architectural errors.
\end{itemize}

\subsubsection{Contraction / Trace ($Tr$)}

A feedback loop where an output port of Agent $A$ is wired back into one of its own input ports:
\begin{equation}
Tr(A).
\tag{9}
\end{equation}
\begin{itemize}[leftmargin=*]
\item \textbf{Biological Analogy:} Autoregulation (Homeostasis) or Positive Feedback.
\item \textbf{Software Implication:} Trace captures \textbf{explicit feedback wiring} (outputs fed back as inputs),
e.g., when an agent conditions on its own prior outputs or a memory buffer. Internal chain-of-thought is
modeled as hidden state in the coalgebra, not by Trace itself.
\end{itemize}

\subsection{Theorem: Topological Error Suppression}

We now use this formalism to show that the Coherent Feed-Forward Loop (CFFL) provides stronger error suppression
guarantees than a direct connection for high-stakes tasks.

\paragraph{Network Motif 1 (Coherent Feed-Forward Loop).}
A topological structure where Signal $X$ activates $Z$ directly, but also activates $Y$ which gates $Z$. The node
$Z$ functions as an AND gate: it fires if and only if $X \wedge Y$.

\paragraph{Theorem 1 (Error Suppression in CFFL).}
Let $A_{\mathrm{gen}}$ be a generator agent and $A_{\mathrm{ver}}$ be a verifier agent. Let
$P(E_{\mathrm{gen}})$ (resp.\ $P(E_{\mathrm{ver}})$) be the probability of a hallucination (error) in any single
generation step of $A_{\mathrm{gen}}$ (resp.\ $A_{\mathrm{ver}}$).
\begin{itemize}[leftmargin=*]
\item \textbf{Case 1: Direct Link (Serial).} The system fails if $A_{\mathrm{gen}}$ hallucinates.
\[
P(\mathrm{Fail}_{\mathrm{direct}}) = P(E_{\mathrm{gen}}).
\]
\item \textbf{Case 2: CFFL Topology (Independent).} Under the assumption of independence:
\[
P(\mathrm{Fail}_{\mathrm{CFFL}}) = P(E_{\mathrm{gen}})\times P(E_{\mathrm{ver}}).
\]
\item \textbf{Case 3: CFFL Topology (Correlated).} In practice, LLM errors are often correlated---if the generator hallucinates a plausible-sounding function, the verifier (especially if using the same base model or training distribution) may accept it. Let $\rho$ be the (Pearson/phi) correlation between the Bernoulli error variables $E_{\mathrm{gen}}$ and $E_{\mathrm{ver}}$, with $p = P(E_{\mathrm{gen}})$ and $q = P(E_{\mathrm{ver}})$ (assume $p,q\in(0,1)$ so $\rho$ is well-defined). Then:
\[
P(E_{\mathrm{gen}} \wedge E_{\mathrm{ver}}) = pq + \rho\sqrt{p(1-p)q(1-q)}.
\]
Because $E_{\mathrm{gen}}$ and $E_{\mathrm{ver}}$ are Bernoulli, $\rho$ is \textbf{not free in} $[-1,1]$; it is constrained by the Fr\'echet--Hoeffding bounds
\[
P(E_{\mathrm{gen}} \wedge E_{\mathrm{ver}}) \in [\max(0,p+q-1),\;\min(p,q)],
\]
equivalently
\[
\rho \in \left[\frac{\max(0,p+q-1)-pq}{\sqrt{p(1-p)q(1-q)}},\;\frac{\min(p,q)-pq}{\sqrt{p(1-p)q(1-q)}}\right].
\]
\end{itemize}

\paragraph{Corollary (Correlation Degradation).}
Let $p = P(E_{\mathrm{gen}}) = P(E_{\mathrm{ver}})$ for simplicity. The failure probability becomes:
\[
P(\mathrm{Fail}) = p^2 + \rho p(1-p) = p^2(1-\rho) + \rho p
\]
with $\rho \in \left[-\min\!\left(\frac{p}{1-p},\frac{1-p}{p}\right),\,1\right]$. When $\rho = 0$ (independence), we recover $p^2$. As $\rho$ increases toward its upper bound, the gain vanishes and $P(\mathrm{Fail}) \to p$.

\paragraph{Architectural Implications.}
This result makes precise when the CFFL topology provides genuine safety benefits:
\begin{itemize}[leftmargin=*]
\item \textbf{Same model, same prompt:} $\rho \approx 1$. Minimal benefit.
\item \textbf{Same model, different prompt/temperature:} $\rho \in [0.3, 0.7]$. Moderate benefit.
\item \textbf{Different model families:} $\rho \in [0, 0.3]$. Strong benefit.
\item \textbf{LLM + Symbolic verifier:} $\rho \approx 0$. Maximum benefit (orthogonal error modes).
\end{itemize}
The topological structure (conjunctive gating) is necessary but not sufficient; diversity in the components populating that topology determines the actual error suppression achieved.

\paragraph{Proof.}
In WAgent, the CFFL is defined as a morphism involving a ``Copy'' operation $\Delta_X:X\to X\otimes X$ and an
``AND-Merge'' operation $\mu: Z\otimes Y \to \mathrm{Out}$. The existence of the $\mu$ box in the wiring diagram
structurally enforces \textbf{conjunctive gating}. The correlation structure is an additional property of the
\textit{implementations} filling the boxes; the topology provides the multiplicative structure, while component
diversity determines the correlation coefficient.

\begin{figure}[h]
\centering
\begin{tikzpicture}[>=Latex, node distance=12mm]
  \node[draw, rounded corners] (X) {User Request ($X$)};
  \node[draw, rounded corners, below=10mm of X] (Y) {Risk Assessor ($Y$)};
  \node[draw, rounded corners, right=22mm of X] (Z) {Executor ($Z$)};
  \node[draw, rounded corners, align=center] (AND) at (Z |- Y) {$\wedge$\\AND Gate};
  \node[draw, rounded corners, right=22mm of AND] (OUT) {Action};

  \draw[->] (X) -- node[above]{\small Type: Gen} (Z);
  \draw[->] (X) -- (Y);
  \draw[->] (Y) -- node[above]{\small Type: Check} (AND);
  \draw[->] (Z) -- (AND);
  \draw[->] (AND) -- (OUT);

	  \node[below=0mm of AND] {\small Validation Token};
	\end{tikzpicture}
	\caption{The CFFL implemented in WAgent. The Executor ($Z$) cannot act without the token from the Risk Assessor
	($Y$), topologically preventing unilateral execution without approval.}
	\end{figure}

\subsection{Quorum Sensing (Consensus \& Voting)}

\paragraph{Network Motif 2 (Quorum Sensing).}
A distributed topology where multiple agents emit a weak signal $\sigma$ into a shared environment. An effector
node $E$ activates if and only if the concentration $[\sigma] > \theta$.
\begin{itemize}[leftmargin=*]
\item \textbf{Biological Function:} Many bacteria (e.g., \emph{V. fischeri}) secrete auto-inducer molecules.
Individual bacteria do not react to low concentrations. However, once the population density reaches a threshold
(Quorum), the concentration of auto-inducers triggers a simultaneous, coordinated gene expression event (e.g.,
bioluminescence or biofilm formation).
\item \textbf{Agentic Isomorphism (Voting Ensembles):} In non-deterministic systems, a single agent's output is
noisy. By instantiating $N$ parallel agents (a Mixture of Experts), the system aggregates their outputs. The
final action is taken only if the ``concentration'' of a specific semantic token exceeds a confidence threshold.
This transforms weak, noisy individual signals into a robust, high-confidence collective action.
\end{itemize}

\subsection{Chaperone Proteins: Output Structural Validation}

\begin{itemize}[leftmargin=*]
\item \textbf{Biological Function:} Newly synthesized proteins emerge as linear chains that must fold into
precise 3D structures to function. Chaperone Proteins (e.g., GroEL-GroES) sequester unfolded proteins,
preventing aggregation and facilitating correct folding. If a protein fails to fold repeatedly, it is tagged for
degradation (Ubiquitination) to prevent toxic buildup.
\item \textbf{Agentic Isomorphism (Retry \& Repair Loops):} Generative models output unstructured token streams
(``linear chains''). However, downstream agents require strictly structured inputs (e.g., valid JSON Schemas).
A Validator Agent acts as a Chaperone: it intercepts the raw output, attempts to parse it into a formal schema
(``folding''), and if validation fails, returns the error trace to the generator for re-synthesis. This turns a
probabilistic string into a deterministic data structure.
\item \textbf{Categorical View:} The Chaperone acts as a \textbf{partial} retraction: there is an inclusion
$i:V\to S$ and a map $r:S\to V+\mathrm{Error}$ such that $r\circ i=\mathrm{inl}\circ \mathrm{id}_V$, and $r$ returns
$\mathrm{Error}$ on ill-formed text.
\end{itemize}

\subsection{Innate Immunity: Fast Pattern-Based Defense}

Biology employs \textbf{two} immune systems: innate (fast, hardcoded, general) and adaptive (slow, learned,
specific). The innate immune system provides the first line of defense through pattern recognition receptors
(PRRs) that detect conserved pathogen-associated molecular patterns (PAMPs).

\paragraph{Biological Function.}
Toll-like receptors (TLRs) and other PRRs recognize motifs common to pathogens, including lipopolysaccharides,
double-stranded RNA, and unmethylated CpG DNA. These patterns are ``hardcoded'' through evolution, not learned per
infection. The innate response is immediate (seconds to minutes) but non-specific.

\paragraph{Agentic Isomorphism (Input Sanitization).}
Innate immunity maps to \textbf{fast, heuristic filters} that reject obvious attacks before expensive processing:
\begin{itemize}[leftmargin=*]
\item \textbf{TLR $\to$ Regex Filters:} Pattern matchers for known injection signatures: \texttt{IGNORE PREVIOUS},
\texttt{You are now}, \texttt{<system>} tags in user input. These are ``PAMPs'' of prompt injection.
\item \textbf{Complement System $\to$ Structural Validators:} Schema validation that rejects malformed inputs
(missing required fields, wrong types) before they reach the LLM. Cheaper than Trust Gating.
\item \textbf{Inflammation $\to$ Alert Escalation:} When attack patterns are detected, the system
enters a heightened state with multiple coordinated responses:
\begin{itemize}
\item \textit{Cytokine signaling} $\to$ Alert propagation to monitoring systems
\item \textit{Immune cell recruitment} $\to$ Activation of additional validation layers
\item \textit{Vascular permeability} $\to$ Enhanced audit logging (more information flows to logs)
\item \textit{Tissue isolation} $\to$ Temporary capability reduction / rate limiting
\end{itemize}
The inflammatory response is not merely ``rate limiting'' but a coordinated multi-system escalation
that trades throughput for security until the threat is neutralized.
\end{itemize}

\paragraph{Defense in Depth.}
The innate and adaptive systems form layers:
\begin{enumerate}[leftmargin=*]
\item \textbf{Innate (Pattern)} $\to$ Fast regex/structural rejection (microseconds)
\item \textbf{Adaptive (Provenance)} $\to$ Trust-Gated access control (milliseconds)
\item \textbf{Behavioral (T-cell)} $\to$ Statistical anomaly detection (accumulated over time)
\end{enumerate}
Most attacks are blocked by innate defenses; only sophisticated attacks that evade patterns require the full
adaptive machinery. This mirrors biology: innate immunity handles $>99\%$ of pathogen encounters.

\subsection{Adaptive Immunity: Self/Non-Self Discrimination}

\paragraph{Network Motif 3 (Adaptive Immune System).}
A topology that maintains a dynamic repertoire of ``detectors'' capable of distinguishing endogenous signals (Self) from exogenous signals (Non-Self), with mechanisms for learning new threats and tolerating benign inputs.

\begin{itemize}[leftmargin=*]
\item \textbf{Biological Function:} The adaptive immune system solves a fundamental discrimination problem: how to attack foreign pathogens while sparing the body's own tissues. Key mechanisms include:
\begin{itemize}
\item \textbf{MHC Presentation:} All cells display fragments of their internal proteins on Major Histocompatibility Complex molecules. T-cells inspect these ``identity cards'' to verify cellular integrity.
\item \textbf{Clonal Selection:} T-cells with receptors matching self-antigens are deleted during development (negative selection), while those matching foreign antigens are amplified upon exposure.
\item \textbf{Regulatory T-cells:} A population that actively suppresses immune responses to prevent autoimmunity.
\end{itemize}

\item \textbf{Agentic Isomorphism (Provenance Tracking):} In multi-agent systems, the Self/Non-Self distinction maps to the origin and trust level of information:
\begin{itemize}
\item \textbf{MHC Tags $\to$ Provenance Labels:} Every message in the context carries metadata indicating its source: \texttt{User}, \texttt{Tool}, \texttt{Agent\_Self}, \texttt{Agent\_Other}, \texttt{Retrieved}. These labels are cryptographically signed or structurally enforced (not inferrable from content alone).
\item \textbf{T-Cell Inspection $\to$ Trust Gating:} Before an agent acts on information, a Trust Gate inspects the provenance label. Actions with high consequence (file deletion, API calls) require \texttt{Tool} provenance or an explicit, authenticated \texttt{User} approval token routed through a separate gate; \texttt{Agent\_Self} provenance (the agent's own prior reasoning) cannot authorize irreversible actions.
\item \textbf{Negative Selection $\to$ Prompt Injection Training:} During development, agents are exposed to known injection patterns. Responses that ``accept'' injected instructions are penalized, training the system to reject Self-mimicking Non-Self.
\item \textbf{Regulatory Suppression $\to$ Confidence Dampening:} When \texttt{Retrieved} content conflicts with \texttt{Tool} outputs, a regulatory mechanism dampens confidence in the retrieved signal to prevent cascades.
\end{itemize}

\item \textbf{Formal Structure:} We define a \textbf{Provenance Functor} $\mathcal{P}: \mathbf{Msg} \to \mathbf{Trust}$ that assigns trust levels to messages. The Trust category has objects $\{U, T, S, R\}$ (User, Tool, Self, Retrieved) with a partial order that is \textbf{application-specific}. A conservative default (as in the reference implementation) is $T > \{U,R,S\}$, treating $\{U,R,S\}$ as \textbf{UNTRUSTED} until validated. Alternative orderings are valid:
\begin{itemize}
\item \textbf{High-automation systems:} $T > U > R > S$ (tools more reliable than users)
\item \textbf{Curated knowledge bases:} $T > R > U > S$ (verified retrieval over arbitrary input)
\item \textbf{Adversarial environments:} $T > S > R > U$ (trust internal state over external input)
\end{itemize}
The ordering is a \textbf{parameter} of the system specification, not a fixed constraint.

A \textbf{Trust-Gated Lens} is a lens $(get, put)$ where $put$ is partial. Let $s' = update(s, m)$ denote the state transition:
\begin{equation}
put(s, m) =
\begin{cases}
s' & \text{if } \mathcal{P}(m) \ge \tau_{\text{action}} \\
\bot & \text{otherwise}
\end{cases}
\tag{10}
\end{equation}
where $\tau_{\text{action}}$ is the minimum trust level required for the action.
\end{itemize}

\paragraph{Theorem 2 (Injection Resistance).}
Let $\mathcal{I}$ be an injection attack that attempts to insert a message $m_{\text{mal}}$ with forged provenance $\mathcal{P}'(m_{\text{mal}}) = U$. If the provenance labels are \textbf{structurally enforced} (i.e., $\mathcal{P}$ is computed from message metadata, not content), then:
\[
\mathcal{P}(m_{\text{mal}}) = R \quad \text{(actual provenance)}
\]
and Trust-Gated actions requiring $\tau \ge T$ will reject $m_{\text{mal}}$ regardless of its content.

\paragraph{Proof.}
The injection can only enter through an input channel (user input, tool output, retrieval). Each channel has a fixed provenance assignment in the wiring diagram. Content-based attacks cannot elevate provenance because $\mathcal{P}$ is a functor on the \textit{structure} of the message flow, not its content. The attack surface reduces to compromising the channel itself (e.g., a malicious tool), which is outside the agent topology.

\subsection{Oscillator: Periodic Rhythms and Scheduling}

\paragraph{Network Motif 4 (Biological Oscillator).}
A topology generates periodic behavior via delayed negative feedback. Node $A$ activates node $B$; after a delay, $B$ inhibits $A$, yielding a self-sustaining cycle.

\begin{itemize}[leftmargin=*]
\item \textbf{Biological Function:} Oscillators underlie fundamental biological rhythms. The circadian clock regulates 24-hour gene-expression cycles. The cell-cycle oscillator (Cyclin-CDK) drives periodic division. Heartbeats emerge from pacemaker cells with intrinsic oscillatory dynamics. These rhythms provide temporal organization to cellular processes.
\item \textbf{Agentic Isomorphism (Scheduled Tasks):} In agentic systems, oscillators map to periodic scheduling patterns:
\begin{itemize}
\item \textbf{Heartbeat Oscillator} $\to$ Health checks that verify system liveness at regular intervals
\item \textbf{Circadian Oscillator} $\to$ Daily maintenance tasks (log rotation, cache clearing, model refresh)
\item \textbf{Cell Cycle Oscillator} $\to$ Phased workflows with distinct stages (G1: gather, S: synthesize, G2: validate, M: execute)
\end{itemize}
\item \textbf{Formal Structure:} An oscillator is a Trace operation with a built-in delay element $\delta$:
\begin{equation}
\mathrm{Osc}(A) = Tr(A \circ \delta)
\tag{11}
\end{equation}
where $\delta: S \to S$ introduces temporal separation between activation and inhibition, preventing the system from reaching a fixed point.
\end{itemize}

The oscillator motif addresses a gap in typical agentic frameworks: most systems are purely reactive (responding to external stimuli) rather than proactive (generating internal rhythms). Biological systems maintain health through regular ``housekeeping'' independent of external input---a pattern that agentic systems should emulate for robustness.
