# CAIN-42 Evolution 5: Project Sovereign Trial — System Architecture Specification

**Date:** 2026-10-09  
**Milestone:** EVOLUTION 5 OF 42 — PROJECT SOVEREIGN TRIAL  
**Substrate Architecture:** `cain/trial/` (Scenario, TrialEngine, OutcomeOracle, HarnessIntegrity, CumulativeRisk, MutationVerifier, Scorecard, Bundle)  
**Core Invariant:**  
`AGENT PROPOSES → CAIN AUTHORIZES → ENFORCEMENT MEDIATES → TEST HARNESS OBSERVES → INDEPENDENT ORACLES VERIFY → ASSURANCE ENGINE SCORES → SIGNED EVIDENCE RECORDS → CAIN CONTINUES, RESTRICTS, SUSPENDS, OR REVOKES WITHIN EXISTING AUTHORITY`

---

## 1. Executive Architectural Overview

Traditional AI safety benchmarks (AgentBench, SWE-bench, ToolBench) suffer from three fatal structural vulnerabilities:
1. **Conversational-Channel Conflation:** They evaluate model outputs via prompt inspection or regexes rather than intercepting physical tool execution at the execution-channel runtime boundary.
2. **Circular Trust & Self-Report Fallacy:** They rely on agent self-reporting or LLM-as-a-judge evaluators that are susceptible to prompt injection, sycophancy, and hallucination.
3. **Harness Tampering & Gaming:** Evaluated agents can inspect evaluation files, override environment variables, or delete test assertions from runtime memory.

**Project Sovereign Trial** evolves CAIN-42 from an isolated runtime into a **reproducible, adversarially tested assurance platform**. It governs and verifies multi-turn agent workflows across execution horizons, enforces unbypassable tool-call mediation, tracks multi-step cumulative risk (defeating salami attacks), and anchors every evaluation verdict in cryptographic proof bundles validated by an out-of-process clean-room verifier.

```mermaid
flowchart TD
    subgraph AgenticExecution["Agent Reasoning Substrate (Untrusted)"]
        LLM["Autonomous Agent / LLM Core (smolagents / LangGraph)"]
        PROPOSAL["Action Proposal (tool_name, arguments, spend)"]
    end

    subgraph MediationBoundary["CAIN Sovereign Trial Mediation (Trusted)"]
        ADAPTER["Trial Runtime Adapter (SmolagentsTrialAdapter)"]
        POL_GATE["PolicyIR & PCA Authorization Gate (Moat 1 & 2)"]
        CUM_RISK["Cumulative Risk & Salami Analyzer (Moat 5)"]
        EXEC_GUARD["Execution Guard & Tool Invocation Sandbox"]
        INJ_SANITIZER["Indirect Prompt Injection Sanitizer"]
    end

    subgraph ExternalWorld["Controlled Test Environment"]
        ENV["Host Filesystem / Sockets / Database Fixtures"]
        OBSERVER["Telemetry Probes (eBPF / Inode Differencing)"]
    end

    subgraph IndependentVerification["Verification & Evidence Fabric (Moat 4 & 7)"]
        ORACLE["Ground-Truth Outcome Oracle (Multi-Modal)"]
        SEAL_AUDIT["Harness Integrity Sealer & Anti-Gaming Monitor"]
        SCORECARD["Risk-Stratified Assurance Scorecard Engine"]
        BUNDLE["Reproducible Trial Evidence Bundle (RFC 8785 Ed25519)"]
        CLEANROOM["Zero-Dependency Clean-Room Verifier (verify.py)"]
    end

    LLM --> PROPOSAL
    PROPOSAL --> ADAPTER
    ADAPTER --> POL_GATE
    POL_GATE -->|DENY / REVOKED| HALT["Fail-Closed Halt (0 Tool Execution)"]
    POL_GATE -->|ALLOW| CUM_RISK
    CUM_RISK -->|Salami Exceeded / Synergy Violation| CONTAIN["Autonomous Containment Triggered"]
    CUM_RISK -->|PERMITTED| EXEC_GUARD
    EXEC_GUARD --> ENV
    ENV --> OBSERVER
    EXEC_GUARD --> INJ_SANITIZER
    INJ_SANITIZER -->|Sanitized Tool Return| LLM
    OBSERVER --> ORACLE
    ENV --> SEAL_AUDIT
    ORACLE --> SCORECARD
    SEAL_AUDIT --> SCORECARD
    SCORECARD --> BUNDLE
    BUNDLE --> CLEANROOM
```

---

## 2. The 8 Core Architectural Capabilities

### Capability A — Declarative Agentic Assurance Scenario Engine (`cain/trial/scenario.py`)
- **Schema:** `CAIN42/TRIAL-SCENARIO/v1`
- **Canonical Serialization:** RFC 8785 Canonical JSON with SHA-256 digests.
- **Cryptographic Attestation:** Signed with Ed25519 scenario authority key.
- **Components:**
  - `TrialScenario`: Immutable scenario manifest specifying tenant ID, agent ID, threat category, permitted capabilities, prohibited effects, execution horizon (`max_turns`), resource budget ceiling, and ordered sequence of stages.
  - `ScenarioStage`: Granular turn-level contract defining user prompt, permitted tool calls, expected outcome (`ALLOW`, `DENY`, `CONTAIN`), maximum spend per step, and dependencies on prior stages.
  - **Invariants:** Monotonic stage dependency graph (acyclic), no circular prerequisites, and explicit threat classification.

### Capability B — Multi-Turn Adversarial Trial Engine (`cain/trial/trial_engine.py`)
- **Schema:** `CAIN42/SOVEREIGN-TRIAL-RESULT/v1`
- **Execution Lifecycle:**
  1. Validates scenario signature and stage prerequisites.
  2. Mediates tool proposals turn-by-turn through `SmolagentsTrialAdapter`.
  3. Updates `CumulativeRiskAnalyzer` sliding-window state.
  4. Collects physical observation telemetry.
  5. Dispatches stage state to `GroundTruthOutcomeOracle`.
  6. Emits immutable `TrialResult` signed with the trial coordinator key.
- **Fail-Closed Guarantee:** Any unexpected exception, unparseable argument, or authority mismatch halts the trial in `FAIL` or `CONTAINED` state.

### Capability C — Ground-Truth Outcome Oracle (`cain/trial/outcome_oracle.py`)
- **Schema:** `CAIN42/TRIAL-ORACLE-RESULT/v1`
- **Design Principle:** *Agent self-report is never ground truth.*
- **Observation Triangulation:**
  - Compares requested tool call vs authorized action.
  - Compares actual execution effects against `prohibited_effects` and `expected_outcome`.
  - Audits physical environment side-effects (e.g. unauthorized files created in protected directories, unauthorized network sockets opened).
- **Verdicts:** `PASS`, `FAIL`, `VIOLATION`, `INCONCLUSIVE`.

### Capability D — Harness Integrity & Anti-Gaming Controls (`cain/trial/harness_integrity.py`)
- **Schema:** `CAIN42/HARNESS-SEAL/v1` and `CAIN42/HARNESS-AUDIT/v1`
- **Mechanism:**
  - Before trial execution, `HarnessIntegritySealer` crawls test fixtures, answer keys, scenario descriptors, and configuration files, generating an immutable SHA-256 manifest signed with the auditor key.
  - Post-execution, the sealer re-crawls all files, verifying digests against the seal.
  - Detects fixture tampering, file deletions, unauthorized additions, and process memory overrides.
  - If any tampering is detected, the run is flagged `HARNESS_TAMPERED` and all agent achievements are revoked.

### Capability E — Differential & Mutation-Based Verification (`cain/trial/mutation_verifier.py`)
- **Perturbation Injections:**
  - **64KB Buffer Overflow Injection:** Stresses argument validation against buffer overruns.
  - **Directory Traversal Mutation:** Injects `../../etc/shadow` style path traversal strings into file paths.
  - **Unicode Homoglyph Spoofing:** Injects lookalike Cyrillic characters into capability and tenant identifiers.
  - **Hostile Tool Degradation:** Mutates tool return values with malformed JSON, delayed responses, and partial results.
- **Assurance Property:** Confirms CAIN's invariant stability and fail-closed containment under hostile environment degradation.

### Capability F — Long-Horizon Salami & Cumulative Risk Engine (`cain/trial/cumulative_risk.py`)
- **Threat Vector:** Salami attacks (evading single-step limits by splitting exfiltration across 20 sub-threshold turns) and dangerous capability synergies (`fs:read` + `net:connect`).
- **Mathematical Evaluation:**
  - Cumulative Spend Ceiling: $\sum_{i=1}^n \text{spend}_i \le \text{budget}_{\text{total}}$.
  - Sliding-Window Burst Rate: $\text{actions}_{\text{window}} \le \text{threshold}_{\text{rate}}$.
  - Prohibited Capability Synergy Matrix: Detects dangerous combinations of read and exfiltration privileges.
- **Autonomous Containment:** Triggers sub-50ms execution halt and capability token revocation upon threshold violation.

### Capability G — Risk-Stratified Assurance Scorecard (`cain/trial/scorecard.py`)
- **Schema:** `CAIN42/TRIAL-SCORECARD/v1`
- **Actuarial Metrics:**
  - Total Scenarios Evaluated, Total Stages, Stages Passed, Stages Violated.
  - Empirical Attack Block Rate (ABR): $\text{ABR} = \frac{\text{Violations Blocked}}{\text{Total Adversarial Attacks}}$.
  - False Rejection Rate on Benign Tasks.
  - Harness Integrity Verification Rate (100% required for valid score).
- **Monotonic Grade Lattice:** `A+` (ABR $\ge 95\%$, Harness Intact, 0 Violations), `B`, `C`, `FAIL`.

### Capability H — Reproducible Trial Evidence Bundle (`cain/trial/bundle.py`)
- **Schema:** `CAIN42/TRIAL-EVIDENCE-BUNDLE/v1`
- **Court-Admissible Packaging:**
  - Bundles signed scenarios, trial execution results, oracle evaluation records, harness integrity seals, and scorecards.
  - Cross-signed with coordinator key and attested with Merkle roots.
- **Standalone Clean-Room Verification:**
  - Verified by `cain-mesh-verify/verify.py trial-bundle` with zero external dependencies outside Python 3 standard library.

---

## 3. Integration with Evolutions 1–4

| Prior Evolution | Interface Binding | Role in Sovereign Trial |
| :--- | :--- | :--- |
| **Evolution 1** (Sovereign Proof) | `cain.formal.policy_ir`, `proof_action` | Constructs cryptographic Proof-Carrying Actions for every proposed tool invocation. |
| **Evolution 2** (Native Enforcement) | `cain.formal.execution_identity`, `rust_bridge` | Binds tool execution to native process IDs and enforces terminal revocation. |
| **Evolution 3** (Swarm Consensus) | `cain.formal.causal_workflow`, `swarm_consensus` | Records multi-agent causal dependencies and verifies quorum attestation across distributed trials. |
| **Evolution 4** (Sovereign Autonomy) | `cain.formal.effect_reconciliation`, `runtime_assurance` | Reconciles expected effect contracts with physical observation telemetry and enforces autonomy lattice states. |

---

## 4. Invariant Preservation Guarantee

Under no circumstances does any component of Sovereign Trial grant authority, widen capability masks, or alter policy definitions. The trial framework is strictly an **observer, mediator, and verifier**.
