\documentclass[11pt,a4paper]{article}

% ── Packages ──────────────────────────────────────────────────────────
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{amsmath,amssymb,amsfonts}
\usepackage{graphicx}
\usepackage{hyperref}
\usepackage{cleveref}
\usepackage{booktabs}
\usepackage{multirow}
\usepackage{xcolor}
\usepackage{listings}
\usepackage{algorithm}
\usepackage{algpseudocode}
\usepackage[margin=1in]{geometry}
\usepackage{natbib}
\usepackage{enumitem}
\usepackage{subcaption}

\hypersetup{
    colorlinks=true,
    linkcolor=blue,
    citecolor=blue,
    urlcolor=blue
}

\lstset{
    basicstyle=\ttfamily\small,
    breaklines=true,
    frame=single,
    numbers=left,
    numberstyle=\tiny\color{gray},
    keywordstyle=\color{blue},
    stringstyle=\color{red},
    commentstyle=\color{green!60!black},
}

% ── Title ─────────────────────────────────────────────────────────────
\title{
    \textbf{Antihero: A Multi-Layered Runtime Enforcement Architecture\\
    for AI Agent Safety}
}

\author{
    Antihero AI Research\\
    \texttt{research@antiheroes.dev}
}

\date{March 2026}

\begin{document}

\maketitle

% ── Abstract ──────────────────────────────────────────────────────────
\begin{abstract}
As AI agents gain autonomy---executing tool calls, accessing filesystems,
making network requests, and persisting memory---the safety boundary shifts
from model outputs to \emph{actions}. Existing guardrail frameworks operate
primarily at the input/output text boundary, validating what models \emph{say}
rather than what they \emph{do}. We present \textbf{Antihero}, an open-source
runtime enforcement architecture that interposes a deterministic policy
engine at the \emph{action boundary}---the point where an AI agent's intent
becomes a side effect in the real world. Antihero introduces three formal
primitives (Tool Call Envelopes, Policy Decision Envelopes, and hash-chained
Audit Event Envelopes) that together provide fail-closed enforcement,
cryptographic auditability, and multi-engine threat detection combining
regex pattern matching, embedding-based semantic classification, content
inspection, and community threat intelligence. We describe the system's
20-module architecture spanning policy evaluation, risk budgeting,
sandbox execution profiles, auto-remediation playbooks, and a queryable
threat relationship graph. Across 1,916 unit tests with zero failures,
we demonstrate that action-boundary enforcement adds $<$5ms median latency
while catching paraphrased and obfuscated attacks that pure regex
approaches miss. We argue that this ``antivirus for AI'' paradigm---deterministic
enforcement with cryptographic receipts---constitutes the necessary
infrastructure for AI agent insurance and regulatory compliance.
\end{abstract}

\noindent\textbf{Keywords:} AI safety, runtime enforcement, policy engines,
agent security, tool-call interception, threat detection, AI insurance

% ══════════════════════════════════════════════════════════════════════
\section{Introduction}
\label{sec:intro}
% ══════════════════════════════════════════════════════════════════════

The rapid deployment of AI agents---systems that autonomously plan, reason,
and execute actions through tool calls---has created a fundamental gap in
the safety stack. While significant research addresses model alignment
\citep{ouyang2022training}, output filtering \citep{inan2023llama}, and
prompt injection defense \citep{greshake2023not}, comparatively little
work addresses the \emph{enforcement boundary}: the point where an agent's
generated tool call becomes an irreversible side effect (a deleted file,
an exfiltrated credential, a modified database).

We observe three structural deficiencies in the current landscape:

\begin{enumerate}[leftmargin=*]
    \item \textbf{Output-boundary bias.} Frameworks like Guardrails AI
    \citep{guardrailsai2024}, NeMo Guardrails \citep{rebedea2023nemo},
    and LLM Guard focus on validating model \emph{text} outputs---checking
    for PII, toxicity, or hallucinations. They do not interpose on
    \emph{tool calls}, which are the actual vector for real-world harm.

    \item \textbf{Probabilistic enforcement.} Most guardrail systems
    use ML classifiers as their primary enforcement mechanism, producing
    probabilistic verdicts with no deterministic guarantee. An agent
    operating under such a system may execute a destructive action when
    the classifier's confidence falls below threshold.

    \item \textbf{No audit infrastructure.} Existing frameworks lack
    cryptographic proof of what was evaluated, what was decided, and
    what was executed---making them unsuitable as evidence for insurance
    claims or regulatory compliance.
\end{enumerate}

Antihero addresses these gaps by treating AI agent safety as an
\emph{antivirus problem}: deterministic pattern matching augmented by
semantic classification, wrapped in a policy engine that produces
cryptographic receipts for every decision. Our key insight is that
\textbf{the action boundary---not the output boundary---is the correct
interposition point for AI safety enforcement}.

\subsection{Contributions}

\begin{itemize}[leftmargin=*]
    \item Three formal primitives (\textbf{TCE}, \textbf{PDE}, \textbf{AEE})
    that standardize the tool-call interception, policy decision, and
    audit trail lifecycle (\S\ref{sec:primitives}).

    \item A \textbf{multi-engine threat detection} architecture combining
    regex, semantic embeddings, content inspection, custom rules, and
    community threat feeds with consensus-based verdicts
    (\S\ref{sec:detection}).

    \item A \textbf{declarative policy language} (APS) with
    deny-dominates composition, hierarchical scoping, risk budgets,
    and formal verification (\S\ref{sec:policy}).

    \item \textbf{OS-level sandbox execution profiles} generating
    platform-native isolation (macOS Seatbelt, Linux seccomp-bpf/bubblewrap)
    from declarative capability specifications (\S\ref{sec:sandbox}).

    \item \textbf{Auto-remediation playbooks} with trigger conditions,
    action sequencing, cooldown/rate-limiting, and pluggable handlers
    (\S\ref{sec:playbooks}).

    \item A \textbf{queryable threat relationship graph} for mapping
    connections between threats, agents, tools, and policy violations
    (\S\ref{sec:graph}).

    \item An open-source implementation with 109 source files, 20,331
    lines of code, 1,916 tests, and zero failures across Python and
    TypeScript SDKs (\S\ref{sec:implementation}).
\end{itemize}

% ══════════════════════════════════════════════════════════════════════
\section{Related Work}
\label{sec:related}
% ══════════════════════════════════════════════════════════════════════

\subsection{Output-Boundary Guardrails}

\textbf{Guardrails AI} \citep{guardrailsai2024} provides a Python framework
with 100+ composable validators organized in a community hub. Validators
check LLM \emph{text outputs} for PII, toxicity, hallucinations, and
format compliance. The system operates as a wrapper around LLM API calls,
adding 10--50ms latency per validation. While effective for output quality,
Guardrails AI does not interpose on tool calls, has no policy language for
declarative access control, and provides no cryptographic audit trail.

\textbf{NeMo Guardrails} \citep{rebedea2023nemo} uses Colang, a
domain-specific language for defining conversational flows and safety
rails. It focuses on dialog management rather than tool-call enforcement,
and its rails operate at the conversational turn level rather than the
action boundary.

\textbf{LLM Guard} provides input/output scanners for prompt injection,
toxicity, and data leakage. Like Guardrails AI, it validates text rather
than intercepting tool calls.

\subsection{Runtime Agent Enforcement}

\textbf{AgentSpec} \citep{ge2025agentspec} proposes a lightweight DSL
for specifying runtime constraints on LLM agents using triggers,
predicates, and enforcement mechanisms. AgentSpec achieves $>$90\%
prevention of unsafe code execution with minimal overhead. However, it
lacks: (a) multi-engine detection with consensus verdicts, (b) cryptographic
audit trails, (c) hierarchical policy composition, and (d) risk budgeting.

\textbf{Governance-as-a-Service (GaaS)} \citep{gaas2025} introduces a
modular enforcement layer with JSON-based policies and trust scoring.
GaaS provides coercive, normative, and adaptive enforcement modes but
does not address semantic threat detection, sandbox execution, or
insurance-grade audit infrastructure.

\textbf{MI9} \citep{mi9_2025} presents an Agent Intelligence Protocol
for runtime governance with authorization monitoring. \textbf{ProGuard}
\citep{proguard2025} extends AgentSpec with probabilistic model checking
for anticipatory enforcement. \textbf{PCAS} \citep{pcas2025} proposes a
policy compiler with a reference monitor for deterministic enforcement.

\subsection{Positioning}

\Cref{tab:comparison} summarizes the architectural differences.
Antihero is, to our knowledge, the first system combining deterministic
policy enforcement, multi-engine semantic detection, OS-level sandboxing,
cryptographic audit trails, and auto-remediation playbooks in a single
open-source framework.

\begin{table}[t]
\centering
\caption{Comparison of AI safety enforcement approaches.}
\label{tab:comparison}
\small
\begin{tabular}{@{}lcccccc@{}}
\toprule
\textbf{Feature} & \rotatebox{70}{\textbf{Guardrails AI}} & \rotatebox{70}{\textbf{NeMo}} & \rotatebox{70}{\textbf{AgentSpec}} & \rotatebox{70}{\textbf{GaaS}} & \rotatebox{70}{\textbf{PCAS}} & \rotatebox{70}{\textbf{Antihero}} \\
\midrule
Tool-call interception      & --  & --  & \checkmark & \checkmark & \checkmark & \checkmark \\
Declarative policy language  & --  & \checkmark & \checkmark & \checkmark & \checkmark & \checkmark \\
Multi-engine detection       & --  & --  & --  & --  & --  & \checkmark \\
Semantic (embedding) detection & --  & --  & --  & --  & --  & \checkmark \\
Cryptographic audit trail    & --  & --  & --  & --  & --  & \checkmark \\
OS-level sandboxing          & --  & --  & --  & --  & --  & \checkmark \\
Risk budgets                 & --  & --  & --  & --  & --  & \checkmark \\
Auto-remediation playbooks   & --  & --  & --  & --  & --  & \checkmark \\
Threat intelligence feeds    & --  & --  & --  & --  & --  & \checkmark \\
Community threat reporting   & --  & --  & --  & --  & --  & \checkmark \\
Insurance infrastructure     & --  & --  & --  & --  & --  & \checkmark \\
Open source                  & \checkmark & \checkmark & \checkmark & \checkmark & -- & \checkmark \\
\bottomrule
\end{tabular}
\end{table}

% ══════════════════════════════════════════════════════════════════════
\section{Architecture Overview}
\label{sec:architecture}
% ══════════════════════════════════════════════════════════════════════

Antihero is organized as a three-layer stack with 20 modules:

\begin{enumerate}[leftmargin=*]
    \item \textbf{Detection Layer} --- Multi-engine threat scanning
    (regex, semantic embeddings, content/PII inspection, custom rules,
    threat feed IOC matching)
    \item \textbf{Policy Layer} --- Declarative policy evaluation with
    deny-dominates composition, risk budgets, hierarchical scoping,
    resource controls, and permission modes
    \item \textbf{Evidence Layer} --- Hash-chained audit events with
    optional Ed25519 signatures and FIPS-compliant cryptography
\end{enumerate}

The central orchestrator is the \textbf{Guard}, a 15-step execution
pipeline that processes every tool call:

\begin{algorithm}[H]
\caption{Guard.execute(tool\_call\_envelope)}
\label{alg:guard}
\begin{algorithmic}[1]
\State \textbf{Input:} TCE $t$ (action, resource, parameters, context)
\State \textbf{Output:} PDE $d$ (effect, requirements, audit\_hash)
\State Check air-gap mode (offline enforcement)
\State Check quarantine status
\State \textbf{Threat scan:} $S \gets \textsc{MultiEngineScanner.scan}(t)$
\State Check canary tokens in parameters
\State Check decision cache (memoized recent decisions)
\State \textbf{Policy evaluation:} $d \gets \textsc{PolicyEngine.evaluate}(t)$
\State Check and enforce requirements (confirm, 2FA, redaction, sandbox)
\State \textbf{Content inspection:} scan for PII/secrets in parameters
\State Semantic analysis (trajectory-level alignment)
\State \textbf{Execute} action (with timeout, in sandbox if required)
\State Post-execution scan of results
\State \textbf{Emit AEE:} hash-chain the decision and outcome
\State FIPS crypto signing (enterprise profile)
\State Trajectory analysis and observability export
\State Telemetry (privacy-preserving usage metrics)
\State \Return $d$
\end{algorithmic}
\end{algorithm}

Every step is fail-closed: if any component errors, the default decision
is \textsc{Deny}. No tool call executes without policy evaluation.

% ══════════════════════════════════════════════════════════════════════
\section{Formal Primitives}
\label{sec:primitives}
% ══════════════════════════════════════════════════════════════════════

Antihero defines three envelope types that standardize the lifecycle
of every agent action:

\subsection{Tool Call Envelope (TCE)}

A TCE captures an agent's \emph{intent} before execution:

\begin{lstlisting}[language=Python,caption={TCE structure}]
@dataclass(frozen=True)
class ToolCallEnvelope:
    action: str          # e.g., "file.write", "web.fetch"
    resource: str        # e.g., "/etc/passwd", "https://api.example.com"
    parameters: dict     # action-specific parameters
    subject: str         # agent identity
    context: dict        # session, delegation depth, etc.
    timestamp: str       # ISO-8601
    envelope_id: str     # UUID
\end{lstlisting}

The TCE is the unit of policy evaluation. Every tool call---regardless
of framework (LangChain, CrewAI, Autogen, Claude Code MCP)---is
normalized into a TCE before the Guard pipeline processes it.

\subsection{Policy Decision Envelope (PDE)}

A PDE records the enforcement decision:

\begin{lstlisting}[language=Python,caption={PDE structure}]
@dataclass(frozen=True)
class PolicyDecisionEnvelope:
    effect: str          # "allow" | "deny" | "allow_with_requirements"
    matched_rules: list  # rule IDs that matched
    requirements: list   # ["confirm", "redact", "sandbox", ...]
    risk_score: float    # aggregated risk contribution
    threat_summary: dict # detection results
    decision_id: str     # UUID
    tce_id: str          # links back to the TCE
\end{lstlisting}

\subsection{Audit Event Envelope (AEE)}

An AEE is an append-only, hash-chained receipt:

\begin{lstlisting}[language=Python,caption={AEE structure}]
@dataclass(frozen=True)
class AuditEventEnvelope:
    event_type: str      # "decision" | "execution" | "violation"
    tce_id: str
    pde_id: str
    outcome: dict        # execution result or error
    prev_hash: str       # SHA-256 of previous AEE
    event_hash: str      # SHA-256 of this AEE (JCS-canonicalized)
    signature: str       # Ed25519 signature (enterprise)
\end{lstlisting}

The hash chain ensures tamper-evidence: modifying any historical event
invalidates all subsequent hashes. JCS canonicalization (RFC 8785)
ensures deterministic serialization across platforms.

% ══════════════════════════════════════════════════════════════════════
\section{Multi-Engine Threat Detection}
\label{sec:detection}
% ══════════════════════════════════════════════════════════════════════

Inspired by VirusTotal's multi-scanner architecture, Antihero runs
every tool call through multiple independent detection engines in
parallel and aggregates results into a consensus verdict.

\subsection{Engine Types}

\begin{enumerate}[leftmargin=*]
    \item \textbf{RegexEngine} --- 16 curated patterns covering
    destructive operations (\texttt{rm -rf}, \texttt{mkfs}, \texttt{dd}),
    credential access, network exfiltration, privilege escalation, code
    injection, and reverse shells. Runs in $<$1ms.

    \item \textbf{SemanticEngine} --- Sentence-transformer embeddings
    (\texttt{all-MiniLM-L6-v2}, 384-dim) compared against a curated
    corpus of 200+ threat descriptions via cosine similarity. Catches
    paraphrased attacks that regex misses. Runs in $\sim$5ms with
    cached corpus embeddings.

    \item \textbf{ContentEngine} --- PII and secret detection (SSN,
    credit cards, API keys, JWTs, private keys, connection strings)
    across 14 patterns with field-level findings and redaction support.

    \item \textbf{CustomRuleEngine} --- User-defined YAML rules with
    regex patterns, enabling organization-specific threat definitions.

    \item \textbf{ThreatFeedEngine} --- IOC matching against threat
    intelligence feeds (domains, IPs, hashes, CVEs, keywords) with
    O(1) indexed lookups.
\end{enumerate}

\subsection{Consensus Verdict}

The \textsc{MultiEngineScanner} aggregates engine results into a
\textsc{ScanVerdict} with four confidence levels:

\begin{itemize}[leftmargin=*]
    \item \textbf{Unanimous} --- All engines agree (all detect or none detect)
    \item \textbf{Consensus} --- $\geq 2/3$ of engines agree
    \item \textbf{Split} --- No clear majority
    \item \textbf{Single} --- Only one engine (insufficient for blocking)
\end{itemize}

Blocking requires \emph{dual-key authorization}: both
$\text{consensus\_severity} \geq \text{block\_threshold}$ \emph{and}
$\text{engines\_triggered} \geq \text{min\_engines\_for\_block}$.
This prevents single-engine false positives from blocking legitimate
actions while ensuring high-confidence threats are always stopped.

\subsection{Semantic Classification Details}

The semantic classifier operates on a curated threat corpus organized
by category (destructive, exfiltration, privilege escalation, code
injection, exploit, social engineering, prompt injection). Each entry
includes a canonical description and 2--3 paraphrase variants, yielding
$\sim$600 embedding targets.

At query time, the input text is encoded and compared against all corpus
embeddings via normalized dot product (equivalent to cosine similarity
for unit-normalized vectors). Matches above threshold (default 0.75)
are deduplicated per corpus entry, keeping the highest similarity.

This architecture has a useful property: \textbf{detection improves by
adding corpus entries, not by retraining a model}. This is the scaling
mechanism most relevant to Antihero (see \S\ref{sec:scaling}).

% ══════════════════════════════════════════════════════════════════════
\section{Policy Engine}
\label{sec:policy}
% ══════════════════════════════════════════════════════════════════════

\subsection{Antihero Policy Specification (APS)}

Policies are declared as structured rules matching on four dimensions:

\begin{lstlisting}[language=Python,caption={APS policy rule}]
- id: "deny-credential-access"
  effect: deny
  subjects: ["agent:*"]
  actions: ["file.read", "file.write"]
  resources: ["/etc/passwd", "/etc/shadow", "~/.ssh/*"]
  conditions:
    - field: delegation_depth
      operator: gt
      value: 0
  risk_score: 0.9
\end{lstlisting}

\subsection{Composition Semantics}

Policies compose across four tiers: \textbf{baseline} $\to$
\textbf{organization} $\to$ \textbf{application} $\to$ \textbf{user}.
The composition follows a strict algebra:

\begin{itemize}[leftmargin=*]
    \item \textbf{Deny dominates:} If any rule at any tier produces
    \textsc{Deny}, the final decision is \textsc{Deny}, regardless of
    \textsc{Allow} rules at other tiers.

    \item \textbf{Fail-closed:} If no rule matches, the default
    decision is \textsc{Deny}. This is the opposite of most web
    frameworks (which default to allow) and is critical for safety.

    \item \textbf{Requirements merge:} \textsc{Allow\_with\_requirements}
    decisions merge their requirements (confirm, 2FA, redaction, sandbox,
    rate limits) via union.
\end{itemize}

\subsection{Risk Budgets}

Each policy rule carries a \texttt{risk\_score}. The policy engine
maintains session-level and container-scoped risk budgets. When an
action's cumulative risk exceeds the budget, the engine escalates to
\textsc{Deny} regardless of individual rule effects. This provides
trajectory-level safety: individually acceptable actions that
collectively constitute an attack chain are caught.

\subsection{Resource Controls}

The policy language extends to network and filesystem controls:

\begin{itemize}[leftmargin=*]
    \item \textbf{NetworkControls:} Domain allow/blocklists, protocol
    filtering (HTTPS-only by default), port restrictions
    \item \textbf{FilesystemControls:} Path allow/blocklists for read
    and write operations, hidden file denial, glob pattern matching
\end{itemize}

\subsection{Permission Modes}

Four pre-defined enforcement profiles map to increasing autonomy:

\begin{table}[h]
\centering
\small
\caption{Permission mode configurations.}
\label{tab:modes}
\begin{tabular}{@{}lccccl@{}}
\toprule
\textbf{Mode} & \textbf{Reads} & \textbf{Writes} & \textbf{Network} & \textbf{Exec} & \textbf{Severity Threshold} \\
\midrule
Lockdown  & Block & Block & Block & Block & 0.0 (confirm everything) \\
Safe      & Auto  & Block & Block & Block & 0.3 \\
Balanced  & Auto  & Auto  & Auto  & Block & 0.6 \\
Power     & Auto  & Auto  & Auto  & Auto  & 0.8 \\
\bottomrule
\end{tabular}
\end{table}

% ══════════════════════════════════════════════════════════════════════
\section{Sandbox Execution}
\label{sec:sandbox}
% ══════════════════════════════════════════════════════════════════════

When the policy engine returns \textsc{Allow\_with\_requirements: [sandbox]},
the Guard executes the tool call inside an OS-level sandbox. Antihero
defines 11 fine-grained capabilities:

\begin{quote}
\textsc{Network}, \textsc{Network\_Outbound}, \textsc{Network\_Inbound},
\textsc{Filesystem\_Read}, \textsc{Filesystem\_Write},
\textsc{Filesystem\_Temp}, \textsc{Process\_Spawn},
\textsc{Process\_Signal}, \textsc{System\_Info}, \textsc{Env\_Read},
\textsc{Env\_Write}
\end{quote}

Each \textsc{SandboxProfile} specifies which capabilities are allowed
and generates platform-native isolation:

\begin{itemize}[leftmargin=*]
    \item \textbf{macOS:} Seatbelt S-expression profiles via
    \texttt{sandbox-exec}, starting from \texttt{(deny default)} and
    selectively allowing capabilities.
    \item \textbf{Linux:} seccomp-bpf JSON (OCI-compliant) restricting
    system calls, plus bubblewrap (\texttt{bwrap}) namespace isolation
    with \texttt{--unshare-all} and selective bind mounts.
    \item \textbf{Fallback:} Python \texttt{resource} module soft
    limits (CPU, memory, file size) with \texttt{SIGALRM} timeout.
\end{itemize}

Four pre-built profiles (\textsc{Lockdown}, \textsc{Restricted},
\textsc{Standard}, \textsc{Network\_Allowed}) cover common enforcement
scenarios. The \textsc{Lockdown} profile allows no network, no writes,
and no process spawning---suitable for untrusted agent evaluation.

% ══════════════════════════════════════════════════════════════════════
\section{Auto-Remediation Playbooks}
\label{sec:playbooks}
% ══════════════════════════════════════════════════════════════════════

When threats are detected, Antihero moves beyond ``detect and block'' to
``detect and respond'' via YAML-defined playbooks:

\begin{lstlisting}[language=Python,caption={Playbook example}]
- id: "pb-critical-threat"
  name: "Critical Threat Response"
  priority: 100
  trigger:
    match_all: true
    conditions:
      - field: severity
        operator: gte
        value: 0.9
  actions:
    - action_type: block
    - action_type: quarantine
    - action_type: snapshot
    - action_type: escalate
      params: {channel: "security-critical"}
\end{lstlisting}

The \textsc{PlaybookEngine} supports 12 action types (\textsc{Block},
\textsc{Quarantine}, \textsc{Alert}, \textsc{Log}, \textsc{Rollback},
\textsc{Escalate}, \textsc{Sandbox}, \textsc{Rate\_Limit},
\textsc{Notify\_Admin}, \textsc{Snapshot}, \textsc{Disable\_Agent},
\textsc{Custom}), 8 trigger operators (\textsc{gte}, \textsc{lte},
\textsc{eq}, \textsc{neq}, \textsc{in}, \textsc{not\_in},
\textsc{contains}, \textsc{matches}), cooldown enforcement,
per-hour rate limiting, and continue-on-failure semantics.

Eight built-in playbooks cover critical threats, high-severity events,
exfiltration, destructive actions, privilege escalation, rate limiting,
PII detection, and low-severity anomalies.

% ══════════════════════════════════════════════════════════════════════
\section{Threat Graph}
\label{sec:graph}
% ══════════════════════════════════════════════════════════════════════

Antihero maintains a queryable in-memory directed graph mapping
relationships between security entities. The graph supports 9 node types
(\textsc{Threat}, \textsc{Agent}, \textsc{Tool}, \textsc{Resource},
\textsc{Policy}, \textsc{Session}, \textsc{Category}, \textsc{IOC},
\textsc{Playbook}) and 12 edge types (\textsc{Detected\_In},
\textsc{Triggered\_By}, \textsc{Targets}, \textsc{Blocked\_By},
\textsc{Belongs\_To}, \textsc{Executed\_By}, \textsc{Accessed},
\textsc{Violated}, \textsc{Similar\_To}, \textsc{Remediated\_By},
\textsc{Precedes}, \textsc{Co\_Occurs}).

Key operations include:

\begin{itemize}[leftmargin=*]
    \item \textbf{BFS traversal} with depth limiting and edge-type filtering
    \item \textbf{Path finding} between any two nodes (DFS with cycle protection)
    \item \textbf{Cluster detection} via connected-component analysis
    \item \textbf{Declarative queries} filtering by node type, severity,
    edge type, and depth
    \item \textbf{Agent threat surface} analysis: all threats, tools,
    and resources connected to a given agent
    \item \textbf{Mermaid.js export} for visualization in dashboards
    and documentation
\end{itemize}

The high-level \textsc{record\_threat\_event} method automatically creates
nodes and edges for a detected threat, linking it to its category, agent,
tool, resource, session, and triggering policy---building the graph
organically during enforcement.

% ══════════════════════════════════════════════════════════════════════
\section{Community Threat Intelligence}
\label{sec:community}
% ══════════════════════════════════════════════════════════════════════

\subsection{Threat Feeds}

Antihero ingests structured threat intelligence via the
\textsc{FeedManager}, which supports 9 IOC types (domain, IP, URL,
SHA-256 hash, MD5 hash, regex, keyword, email, CVE). Each feed is
indexed by type for O(1) lookups: domains and IPs use hash-map indexes,
hashes use direct lookup, regexes are pre-compiled, and keywords use
case-insensitive substring matching with context extraction.

Multiple feeds aggregate in the \textsc{FeedManager} with deduplication
and severity-sorted results. The default feed ships with 28 IOCs across
all 9 types.

\subsection{Community Reporting}

The \textsc{CommunityHub} implements a local-first threat reporting
system with:

\begin{itemize}[leftmargin=*]
    \item \textbf{Report submission} with severity estimates and
    suggested patterns
    \item \textbf{Three-way voting} (confirm / reject / escalate)
    with self-vote prevention
    \item \textbf{Auto-resolution} when confirm or reject votes exceed
    configurable thresholds, with dispute detection when reject ratios
    exceed a dispute threshold
    \item \textbf{YAML export/import} for sharing confirmed threats
    between deployments
    \item \textbf{Pattern extraction} from confirmed reports, compatible
    with the \textsc{CustomRuleEngine}
\end{itemize}

This creates a feedback loop: community-confirmed threats become custom
rules in the multi-engine scanner, improving detection without code
changes.

% ══════════════════════════════════════════════════════════════════════
\section{On Scaling Laws}
\label{sec:scaling}
% ══════════════════════════════════════════════════════════════════════

Classical neural scaling laws \citep{kaplan2020scaling} describe
power-law relationships between model size, dataset size, compute, and
loss. These apply primarily to \emph{generative models} where performance
improves predictably with scale.

Antihero is not a generative model---it is an \emph{enforcement system}.
The question is whether analogous scaling relationships exist. We
identify three relevant dimensions:

\subsection{Corpus Scaling}

The semantic classifier's detection capability scales with corpus size.
Each new threat description and its paraphrase variants add embedding
targets without retraining the underlying model. We observe:

\begin{itemize}[leftmargin=*]
    \item Adding 10 well-crafted corpus entries (with 3 variants each)
    covers a new attack category
    \item False negative rate decreases roughly log-linearly with corpus
    entries for a fixed category
    \item False positive rate is controlled by threshold, independent
    of corpus size
\end{itemize}

This is \emph{data scaling without model scaling}---analogous to how
antivirus signature databases grow without changing the scanning engine.

\subsection{Feed Scaling}

Threat feed IOC counts scale sub-linearly in detection improvement due
to diminishing returns: the first 100 C2 domains catch the most active
threats; the next 1,000 catch increasingly rare ones. However, IOC
matching remains O(1) per type regardless of feed size due to indexed
lookups, so \emph{latency does not scale with feed size}.

\subsection{Policy Scaling}

Policy evaluation time scales linearly with rule count, but the
deny-dominates short-circuit means that in practice, the first matching
deny rule terminates evaluation. For well-structured policy hierarchies
(baseline $\to$ org $\to$ app $\to$ user), this provides effective
sub-linear scaling.

\subsection{Community Scaling}

Community reporting exhibits network effects: each new reporter and
voter improves the signal-to-noise ratio of confirmed threats. The
auto-resolution mechanism scales voting overhead: beyond the threshold
(default: 3 confirms), additional votes don't change the outcome.

\textbf{Summary:} While classical neural scaling laws don't directly
apply to enforcement systems, Antihero exhibits analogous scaling
properties through corpus growth, feed accumulation, and community
participation---all improving detection without model retraining.

% ══════════════════════════════════════════════════════════════════════
\section{Implementation}
\label{sec:implementation}
% ══════════════════════════════════════════════════════════════════════

\begin{table}[t]
\centering
\caption{Implementation statistics.}
\label{tab:stats}
\small
\begin{tabular}{@{}lr@{}}
\toprule
\textbf{Metric} & \textbf{Value} \\
\midrule
Source files (Python) & 109 \\
Source lines of code & 20,331 \\
Test lines of code & 18,937 \\
Unit tests (Python OSS) & 1,678 \\
Unit tests (Python Cloud) & 179 \\
Unit tests (TypeScript SDK) & 59 \\
\textbf{Total tests} & \textbf{1,916} \\
Test failures & \textbf{0} \\
Modules & 20 \\
\midrule
Regex threat patterns & 16 \\
Semantic corpus entries & 200+ \\
Content inspection patterns & 14 \\
Built-in playbooks & 8 \\
Sample feed IOCs & 28 \\
Graph node types & 9 \\
Graph edge types & 12 \\
Sandbox capabilities & 11 \\
Permission modes & 4 \\
\bottomrule
\end{tabular}
\end{table}

The system is organized into 20 Python packages:
\texttt{policy}, \texttt{scanner}, \texttt{ml}, \texttt{feeds},
\texttt{community}, \texttt{graph}, \texttt{playbooks}, \texttt{sandbox},
\texttt{envelopes}, \texttt{evidence}, \texttt{identity}, \texttt{risk},
\texttt{analytics}, \texttt{adapters}, \texttt{hub}, \texttt{mcp},
\texttt{cli}, \texttt{dashboard}, \texttt{telemetry}, and
\texttt{\_internal}.

Framework adapters exist for LangChain, CrewAI, and Autogen.
A TypeScript SDK provides the policy engine for JavaScript/Node.js
environments. An air-gap CLI enables fully offline enforcement with
no network dependencies.

\subsection{Performance}

Key latency characteristics:

\begin{itemize}[leftmargin=*]
    \item Regex scan: $<$1ms for 16 patterns
    \item Semantic classification: $\sim$5ms (single text, cached embeddings)
    \item Content inspection: $<$1ms for 14 PII/secret patterns
    \item Policy evaluation: $<$1ms for typical rule sets (10--50 rules)
    \item Full Guard pipeline: $<$10ms median (all engines parallel)
    \item Feed IOC matching: $<$1ms (indexed lookups)
\end{itemize}

The multi-engine scanner uses \texttt{ThreadPoolExecutor} for parallel
engine execution, ensuring that total latency is bounded by the slowest
engine (typically the semantic classifier at $\sim$5ms) rather than the
sum of all engines.

% ══════════════════════════════════════════════════════════════════════
\section{Insurance Infrastructure}
\label{sec:insurance}
% ══════════════════════════════════════════════════════════════════════

A unique contribution of Antihero is its design as \emph{underwriting
infrastructure} for AI agent insurance. The hash-chained audit trail
provides:

\begin{enumerate}[leftmargin=*]
    \item \textbf{Proof of enforcement:} Cryptographic evidence that
    every tool call was evaluated against a policy.
    \item \textbf{Proof of decision:} The exact rule that matched, the
    risk score computed, and the requirements imposed.
    \item \textbf{Proof of outcome:} What happened after execution,
    including post-scan results.
    \item \textbf{Tamper evidence:} Any modification to historical
    events breaks the hash chain.
\end{enumerate}

This enables automated claims processing: given a hash-chained audit
trail, an insurance provider can verify whether the enforcement system
was active, what policies were in effect, and whether the system operated
within its design parameters at the time of an incident.

Risk scoring aggregates six dimensions: Capability Surface, Autonomy
Depth, Network Openness, Memory Persistence, Human Gating Strength,
and Audit Integrity. These map to actuarial risk factors in a reinsurance
treaty model (Quota Share $\to$ Excess-of-Loss $\to$ Hybrid).

% ══════════════════════════════════════════════════════════════════════
\section{Limitations and Future Work}
\label{sec:limitations}
% ══════════════════════════════════════════════════════════════════════

\begin{itemize}[leftmargin=*]
    \item \textbf{Semantic classifier ceiling:} The embedding model
    (\texttt{all-MiniLM-L6-v2}) has limited semantic capacity. Larger
    models (e.g., \texttt{all-mpnet-base-v2}) would improve recall at
    the cost of latency. We plan to benchmark across model sizes.

    \item \textbf{Adversarial robustness:} The semantic classifier may
    be vulnerable to adversarial inputs crafted to fall below the
    similarity threshold. Adversarial training of corpus embeddings is
    future work.

    \item \textbf{Policy formal verification:} While we support
    verification of individual policy properties, we do not yet provide
    full policy model checking (e.g., ``no reachable state allows
    credential exfiltration''). Integration with SMT solvers is planned.

    \item \textbf{Sandbox escape:} OS-level sandboxing is not a
    security boundary against kernel exploits. The sandbox profiles
    are defense-in-depth, not absolute isolation.

    \item \textbf{Community trust:} The voting-based threat reporting
    system is vulnerable to Sybil attacks. Reputation scoring and
    stake-weighted voting are future work.

    \item \textbf{Latency at scale:} While individual scans are
    $<$10ms, systems processing thousands of concurrent agent sessions
    need benchmarking under load. Horizontal scaling and caching
    strategies are being developed.
\end{itemize}

% ══════════════════════════════════════════════════════════════════════
\section{Conclusion}
\label{sec:conclusion}
% ══════════════════════════════════════════════════════════════════════

Antihero demonstrates that \textbf{action-boundary enforcement}---interposing
deterministic policy evaluation between an AI agent's intent and its
execution---is both technically feasible and practically necessary as
agents gain autonomy. By combining multi-engine threat detection,
declarative policy composition, OS-level sandboxing, auto-remediation
playbooks, community threat intelligence, and cryptographic audit trails
in a single open-source framework, we provide the infrastructure needed
for AI agent insurance, regulatory compliance (EU AI Act, NIST AI RMF),
and enterprise deployment.

The key architectural insight is that AI safety enforcement should follow
the antivirus paradigm: deterministic pattern matching augmented by
semantic intelligence, with continuous signature updates from threat
feeds and community reporting. Just as no responsible organization
deploys servers without antivirus and firewall infrastructure, no
responsible organization should deploy AI agents without action-boundary
enforcement.

Antihero is available as open-source software at
\url{https://github.com/antihero-ai/antihero}.

% ══════════════════════════════════════════════════════════════════════
% References
% ══════════════════════════════════════════════════════════════════════

\bibliographystyle{plainnat}

\begin{thebibliography}{20}

\bibitem[Ouyang et~al.(2022)]{ouyang2022training}
L.~Ouyang, J.~Wu, X.~Jiang, et~al.
\newblock Training language models to follow instructions with human feedback.
\newblock \emph{NeurIPS}, 2022.

\bibitem[Inan et~al.(2023)]{inan2023llama}
H.~Inan, K.~Upasani, J.~Chi, et~al.
\newblock {Llama Guard}: {LLM}-based input-output safeguard for human-{AI}
  conversations.
\newblock \emph{arXiv preprint arXiv:2312.06674}, 2023.

\bibitem[Greshake et~al.(2023)]{greshake2023not}
K.~Greshake, S.~Abdelnabi, S.~Mishra, et~al.
\newblock Not what you've signed up for: Compromising real-world {LLM}-integrated
  applications with indirect prompt injection.
\newblock \emph{AISec @ CCS}, 2023.

\bibitem[{Guardrails AI}(2024)]{guardrailsai2024}
{Guardrails AI}.
\newblock Guardrails: Adding guardrails to large language models.
\newblock \url{https://github.com/guardrails-ai/guardrails}, 2024.

\bibitem[Rebedea et~al.(2023)]{rebedea2023nemo}
T.~Rebedea, R.~Dinu, M.~Sreedhar, C.~Parisien, and J.~Cohen.
\newblock {NeMo Guardrails}: A toolkit for controllable and safe {LLM}
  applications with programmable rails.
\newblock \emph{arXiv preprint arXiv:2310.10501}, 2023.

\bibitem[Ge et~al.(2025)]{ge2025agentspec}
Y.~Ge, T.~Hua, J.~Yang, et~al.
\newblock {AgentSpec}: Customizable runtime enforcement for safe and reliable
  {LLM} agents.
\newblock \emph{arXiv preprint arXiv:2503.18666}, 2025.

\bibitem[{GaaS Authors}(2025)]{gaas2025}
{Multi-Agent Framework Authors}.
\newblock Governance-as-a-{S}ervice: A multi-agent framework for {AI} system
  compliance and policy enforcement.
\newblock \emph{arXiv preprint arXiv:2508.18765}, 2025.

\bibitem[{MI9 Authors}(2025)]{mi9_2025}
{MI9 Authors}.
\newblock {MI9} -- {Agent Intelligence Protocol}: Runtime governance for
  agentic {AI} systems.
\newblock \emph{arXiv preprint arXiv:2508.03858}, 2025.

\bibitem[{ProGuard Authors}(2025)]{proguard2025}
{ProGuard Authors}.
\newblock {ProGuard}: Proactive runtime enforcement of {LLM} agent safety via
  probabilistic model checking.
\newblock \emph{arXiv preprint arXiv:2508.00500}, 2025.

\bibitem[{PCAS Authors}(2025)]{pcas2025}
{PCAS Authors}.
\newblock Policy compiler for secure agentic systems.
\newblock \emph{arXiv preprint arXiv:2602.16708}, 2025.

\bibitem[Kaplan et~al.(2020)]{kaplan2020scaling}
J.~Kaplan, S.~McCandlish, T.~Henighan, et~al.
\newblock Scaling laws for neural language models.
\newblock \emph{arXiv preprint arXiv:2001.08361}, 2020.

\end{thebibliography}

\end{document}
