\section{Formal Syntax: The Agentic Operad}\label{sec:operad}

To formalize admissible agent compositions, we define a typed operad of wiring diagrams, denoted as
\textbf{WAgent}. Here the operad serves primarily as a syntax: a ``grammar'' for connecting operations
(boxes) via typed wires. It specifies which agent topologies are well-formed. When we make probabilistic
or behavioral claims below, those claims rely on additional assumptions about the implementations
inhabiting the boxes, not on the operadic syntax alone~\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}\}.
\label{eq:wire-types}
\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.
\label{eq:parallel-composition}
\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.
\label{eq:serial-composition}
\end{equation}
\begin{itemize}[leftmargin=*]
\item \textbf{Biological Analogy:} A Signal Transduction Pathway (Protein A activates Protein B).
\item \textbf{Static Type Checking:} 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).
\label{eq:trace-feedback}
\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 combine the wiring syntax with a simple stochastic failure model to analyze when the Coherent
Feed-Forward Loop (CFFL) suppresses errors more effectively than a direct serial connection on
high-stakes tasks.

\paragraph{Reading convention.}
For readers coming from AI agent systems rather than category theory, each result in this section should be read in three layers: the wiring diagram tells us which signals or approvals can reach an action sink; the stochastic or trust model assigns probabilities or integrity levels to those signals; the proof then converts that structural constraint into a failure or authorization bound.

\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).}\label{thm:cffl-error-suppression}
Let $A_{\mathrm{gen}}$ be a generator agent and $A_{\mathrm{ver}}$ be a verifier agent. Let
$E_{\mathrm{gen}}$ denote the event that the generator emits an erroneous candidate, and let
$M_{\mathrm{ver}}$ denote the event that the verifier \emph{misses} that error and still emits an approval token.
\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(M_{\mathrm{ver}}).
\]
\item \textbf{Case 3: CFFL Topology (Correlated).} In practice, generator errors and verifier misses are often correlated---if the generator hallucinates a plausible-sounding function, the verifier (especially if using the same base model or training distribution) may be more likely to accept it. Let $\rho$ be the (Pearson/phi) correlation between the Bernoulli variables $E_{\mathrm{gen}}$ and $M_{\mathrm{ver}}$, with $p = P(E_{\mathrm{gen}})$ and $q = P(M_{\mathrm{ver}})$ (assume $p,q\in(0,1)$ so $\rho$ is well-defined). Then:
\[
P(E_{\mathrm{gen}} \wedge M_{\mathrm{ver}}) = pq + \rho\sqrt{p(1-p)q(1-q)}.
\]
Because $E_{\mathrm{gen}}$ and $M_{\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 M_{\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{Assumptions.}
The theorem uses the minimal failure model appropriate for a two-stage execution gate: in the direct serial case, an erroneous action is emitted exactly when the generator emits an erroneous candidate; in the CFFL case, an erroneous action is emitted exactly when the generator emits an error \emph{and} the verifier still approves it.

\paragraph{Corollary (Correlation Degradation).}
Let $p = P(E_{\mathrm{gen}}) = P(M_{\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{High correlation:} Reusing the same model family, prompt structure, or evidence sources can
make verifier misses positively correlated with generator errors, erasing much of the gain.
\item \textbf{Heterogeneous generators and verifiers:} Prompt diversity or model-family diversity can
reduce correlation, but the magnitude is empirical rather than universal.
\item \textbf{Orthogonal checks:} Symbolic or tool-grounded verifiers are a useful limiting case because
their failure modes need not mirror the generator's linguistic ones.
\end{itemize}
These are architectural heuristics rather than fitted universal ranges for $\rho$. The topological structure
(conjunctive gating) is necessary but not sufficient; diversity in the components populating that topology
determines the actual error suppression achieved.

\paragraph{Operational takeaway.}
For agent designers, the result is simple: adding a reviewer buys multiplicative safety only when the reviewer is not making the same mistakes as the generator. The AND gate gives the multiplicative structure; correlation gives that improvement back.

\paragraph{Proof sketch.}
In the direct serial topology there is only one path from the generator to the action sink, so an erroneous final action occurs iff the generator emits an erroneous candidate. Thus
\[
\mathrm{Fail}_{\mathrm{direct}} = E_{\mathrm{gen}},
\qquad
P(\mathrm{Fail}_{\mathrm{direct}})=P(E_{\mathrm{gen}}).
\]

In the CFFL topology, the action sink is downstream of an AND gate. An erroneous final action can occur only if the generator emits an erroneous candidate \emph{and} the verifier misses that error while still approving it. Therefore
\[
\mathrm{Fail}_{\mathrm{CFFL}} = E_{\mathrm{gen}} \wedge M_{\mathrm{ver}}.
\]
Under independence this gives
\[
P(\mathrm{Fail}_{\mathrm{CFFL}})=P(E_{\mathrm{gen}})P(M_{\mathrm{ver}})=pq.
\]
For the correlated case, let $X=\mathbf{1}_{E_{\mathrm{gen}}}$ and $Y=\mathbf{1}_{M_{\mathrm{ver}}}$. Since $X,Y$ are Bernoulli,
\[
P(E_{\mathrm{gen}} \wedge M_{\mathrm{ver}})=\mathbb{E}[XY]
=\mathbb{E}[X]\mathbb{E}[Y]+\mathrm{Cov}(X,Y)
=pq+\rho\sqrt{p(1-p)q(1-q)}.
\]
The Fr\'echet--Hoeffding bounds then give the admissible range of $\rho$. The topology contributes the conjunction; implementation diversity determines the covariance term.

\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$), so the wiring diagram encodes an approval dependency rather than allowing execution by $Z$ alone.}
		\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 Correspondence (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 Correspondence (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 Correspondence (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$ Low-latency regex/structural rejection
\item \textbf{Adaptive (Provenance)} $\to$ Trust-gated access control
\item \textbf{Behavioral (T-cell)} $\to$ Statistical anomaly detection accumulated over time
\end{enumerate}
In practice, inexpensive front-line filters absorb many routine attacks, while provenance and behavioral
layers handle ambiguous cases that survive the first pass. The exact split is deployment-dependent and is
not estimated here.

\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 Correspondence (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 class: \texttt{User}, \texttt{Tool}, \texttt{Self}, or \texttt{Retrieved}. In the reference design these labels are structurally attached to the message flow rather than inferred from content; cryptographic signing is an optional stronger implementation, not an assumption of the theorem.
\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 $\succeq$ denote the policy preorder on provenance labels, and let $s' = update(s, m)$ denote the state transition:
\begin{equation}
put(s, m) =
\begin{cases}
s' & \text{if } \mathcal{P}(m) \succeq \tau_{\text{action}} \\
\bot & \text{otherwise}
\end{cases}
\label{eq:trust-gated-lens}
\end{equation}
where $\tau_{\text{action}}$ is the minimum trust level required for the action.
\end{itemize}

\paragraph{Theorem 2 (Resistance to Content-Level Trust Forgery).}\label{thm:injection-resistance}
Let $\mathcal{I}$ be an injection attack that attempts to insert a message $m_{\text{mal}}$ while forging a higher-trust provenance label in its \emph{content}. If the provenance labels are \textbf{structurally enforced} (i.e., $\mathcal{P}$ is computed from message metadata / ingress channel, not content), then:
\[
\mathcal{P}(m_{\text{mal}}) = \chi(m_{\text{mal}}) \quad \text{(actual ingress-channel provenance)}
\]
where $\chi(m_{\text{mal}}) \in \{U, R, S, T\}$ is fixed by the wire through which the message enters. Therefore any Trust-Gated action whose threshold satisfies $\chi(m_{\text{mal}}) \nsucceq \tau_{\text{action}}$ will reject $m_{\text{mal}}$ regardless of its content.

\paragraph{Assumptions.}
The theorem assumes that provenance is assigned by the runtime or wiring layer from ingress-channel metadata, that the trust gate decides solely from that assigned provenance and the action threshold, and that the attacker can modify message \emph{content} but not the channel through which the message enters.

\paragraph{Operational takeaway.}
For an AI agent system, this means a user string can \emph{look} like a system message or tool result, but if the runtime tags it as user-originated before the model sees it, wording alone cannot authorize a privileged action.

\paragraph{Proof sketch.}
Let $c=\chi(m)$ denote the ingress channel of message $m$. By assumption, provenance is computed from channel metadata rather than payload, so the provenance map factors through the channel:
\[
\mathcal{P}(m) = \widetilde{\mathcal{P}}(c)
\]
for some policy map $\widetilde{\mathcal{P}}$. Hence any two messages entering on the same channel receive the same provenance label regardless of content. In particular, replacing a benign user message with a maliciously worded user message does not change its label. The trust gate accepts iff
\[
\widetilde{\mathcal{P}}(c) \succeq \tau_{\text{action}}.
\]
Since payload edits do not change $c$, content alone cannot change the acceptance decision. The only way to obtain a higher-trust label is to compromise or impersonate a genuinely higher-trust ingress channel, which lies outside the theorem's model.

\paragraph{Scope.}
The theorem is intentionally narrow. It shows that content alone cannot promote a message into a
higher-trust class when provenance is assigned by structure. It does \emph{not} imply that low-trust
content cannot still confuse or distract an agent; it only shows that such content cannot satisfy a
higher-integrity gate without access to a genuinely higher-trust channel.

\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 Correspondence (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)
\label{eq:oscillator-trace}
\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.
