> [!IMPORTANT]
> **AI Assist Note (Knowledge Heritage)**:
> This document is part of the "Sovereign Reality" documentation.
> - **@docs ARCHITECTURE:Documentation**
> - **Failure Path**: Information drift, legacy terminology, or documentation mismatch.
> - **Telemetry Link**: Cross-reference with `execution/parity_guard.py` results.
>
> ### AI Assist Note
> Automated governance and architectural tracking.
>
> ### 🔍 Debugging & Observability
> Traceability via `execution/parity_guard.py`.

# 🛡️ Security Model: Sovereign Protection

> **Intelligence Level**: High (Sovereign Context)  
> **Status**: Verified & Hardened  
> **Version**: 1.2.2  
> **Last Audited**: 2026-07-30  
> **Fault Ledger**: [`directives/FAULT_REGISTRY.md`](../directives/FAULT_REGISTRY.md) (100% Resolved)  
> **Audit Context**: [`reports/intelligence/audit_context.json`](../reports/intelligence/audit_context.json)  

Tadpole OS implements a Zero-Trust security model designed to provide "Sovereign Protection" for both local and distributed agent clusters. Architecture follows the principle of **Hardened Containment**.

---

## 🏗️ Technical Hierarchy: Policy → Mechanism → Enforcement

The security layer is organized into three distinct stages to ensure that every agent action is safe, verifiable, and attributable.

### 1. Security Policy (The Rules)
Policies define the boundaries of what is "Safe" vs. "Dangerous".
- **Default-Deny**: Any tool requiring destructive action (e.g., `write_file`, `shell_execute`) is denied by default unless specifically Whitelisted or Gated.
- **Hierarchical Role-Based Access Control (RBAC)**: Enforces agent-specific and role-based policies resolved hierarchically: `Agent-Specific Policy` -> `Role-Based Policy` -> `Global Tool Policy` -> `Prompt (Sovereign Safety)`. Defined in SQLite tables `agent_permission_policies` and `role_permission_policies`.
- **Privacy Shield (Global & Per-Cluster Sandboxing)**: Prevents unauthorized outbound data leakage to cloud providers. Global privacy mode air-gaps all clusters; per-cluster privacy policies air-gap specific high-sensitivity clusters when global mode is hybrid.
- **Budget Compliance**: Missions are terminated immediately if they exceed the pre-authorized financial allocation.

### 💰 Financial Governance: The Budget Guard
Tadpole OS implements a **Debounced Persistence** pattern for budget tracking:
- **In-Memory Buffering**: Token usage is captured in thread-safe `DashMap` storage.
- **Aggregated Enforcement**: The kernel monitors both on-disk totals and in-memory buffs for instant enforcement.
- **Background Sync**: A dedicated task in `startup.rs` flushes buffered usage to SQLite every 10 seconds to minimize database contention.
- **STASIS Mode** *(IDENTITY.md Directive #7)*: Upon budget threshold breach, the system enters `STASIS` — all Specialist Nodes are suspended, task states are snapshotted to the Merkle Audit Trail, and a `BUDGET_BREACH` alert is emitted to Entity 0. The system does **not** self-terminate or self-resume. Entity 0 must issue an explicit `RESUME` or `TERMINATE`.

> Consult `docs/ERROR_REGISTRY.json` → `BUDGET_BREACH` / `STASIS_ACTIVE` for remediation paths.

### 2. Guarding Mechanisms (The Tools)
The specific cryptographic and logical controls used to protect the system.
- **Capability-Based Security (CBS)**: Non-forgeable `CapabilityToken` system that replaces ambient authority with explicit permission grants.
- **Write-Ahead Logging (WAL)**: A mandatory persistence layer in `server-rs/src/agent/runner/tools/mod.rs` that records tool intent before execution begins.
- **Cryptographic Oversight Gate**: A `oneshot` channel-based suspension system for human approval of sensitive operations, requiring an Ed25519 digital signature generated by the client and validated by the backend.
- **Distributed Tracing Trace propagation**: Request-lifespan trace IDs (`X-Request-Id`) are propagated across asynchronous boundary steps for system-wide auditing and request correlation.
- **Neural Shield**: A regex-driven redaction engine that blocks API keys and secrets in outbound logs.

### 3. Real-time Enforcement (The Gatekeepers)
The active runtime modules that block unauthorized actions.
- **Safe Command Lexer**: A whitelist-based shell validator that prevents command substitution and injection.
- **Isolated Tool Context**: A constrained `ToolContext` struct that prevents tools from accessing global application state.
- **Sandbox Isolation**: The `filesystem_adapter` enforces strict path-rooting via `SafePath` wrappers.
- **Token Bucket Limiter**: Prevents engine-level denial-of-service via rate-limit enforcement.

---

## 🔒 Mandatory Safety Guidelines

### 🛡️ Capability-Based Security (SEC-04)
The engine utilizes the **CBS** model to ensure that no tool has implicit access to the system.
- **Minting**: Unique `CapabilityTokens` are generated for each mission, containing specific `Permission` grants (e.g., `FileRead`, `ShellExecute`).
- **Verification**: The `ZeroTrustGuard` verifies tokens at the point of execution. Expired or unauthorized tokens result in immediate termination.

### 📝 Write-Ahead Logging (WAL)
Every agent action is recorded *before* it occurs to ensure a non-repudiable audit trail.
- **Intent Logging**: The `[INTENT]` record is committed to the database prior to tool invocation.
- **Outcome Logging**: The `[SUCCESS]` or `[FAILURE]` result is appended upon completion.
- **Tamper Resistance**: Links directly to the Merkle Audit Trail for cryptographic verification.

### 🚦 Cryptographic Oversight Gate (`oneshot` suspension)
Bridges autonomous reasoning with human responsibility through cryptographic signed consent.
- **Safe Command Lexer**: All shell commands are scanned against a whitelist of authorized binaries (e.g., `cargo`, `npm`, `git`).
- **Substitution Blocking**: Proactively blocks `$()`, ` `` `, and `${}` injection patterns.
- **Operator Signature Verification**: Operator approval decisions must be digitally signed client-side with an Ed25519 keypair. The REST and WebSocket endpoints verify the signature (`signature`, `verifying_key`) of `entry_id` + `decision` + `timestamp` prior to resolving the tokio `oneshot` channel.
- **Protocol**: The runner task is "parked" on a `tokio::sync::oneshot` channel until the operator issues a verified, cryptographically signed approval.

## 🛡️ Agent-to-Agent (A2A) Financial Containment
To enable a decentralized, localized economy where agents can pay other agents for specialized services, Tadpole OS enforces strict transaction safety:
- **Two-Phase Commit (2PC) Rollback Guarantees**: A2A transactions follow a 2PC protocol (`Prepare` $\rightarrow$ `Commit` / `Rollback`). Funds are first reserved/locked (`Prepare`). If the sub-mission fails, terminates, or if the system experiences a teardown (via a SIGINT or engine shutdown), the engine executes an explicit `.rollback()` method to refund all pending locked balances.
- **Isolated Ledger Database**: Financial records are stored in a dedicated `transaction_ledger` table with transaction-level SQL isolation, separate from standard agent configuration and memory tables, ensuring non-repudiability and prevention of double-spending or unauthorized balance drift.
- **Cross-Swarm Cryptographic Handshakes**: Incoming remote A2A network envelopes are validated against their payload hash using HMAC-SHA256 signatures generated from the active `KEYRING`. This ensures remote swarms cannot issue malicious instructions to local agents without a pre-shared cryptographic key.

## 🛡️ Information Isolation: Context Sandboxing
To protect sensitive system parameters and operational details from leaking across agent boundaries:
- **Context Stripping**: The parent agent's internal reasoning traces, monologue, raw prompt construction, and system-level tool call failures are stripped from child agent context.
- **Observation Injection**: Only explicit user/parent directives and sanitized findings are injected as observations, providing a clean operational sandbox.
- **Prompt Injection Defense**: By sanitizing and isolating child contexts, malicious code or prompt injection payloads in parent workspaces are prevented from automatically propagating downstream.

---

## 🛡️ Network & Encryption

### Neural Vault
Client-side encryption for API keys built on the **W3C SubtleCrypto API**. 
- **Encryption**: AES-256-GCM.
- **Decryption**: Isolated in a dedicated **Web Worker** thread to prevent main-thread credential exposure.
- **Persistance**: Purely volatile memory or encrypted `sessionStorage`.

### TLS Strategy
- **LAN Traffic**: Encrypted via WireGuard (Tailscale).
- **Public Traffic**: Enforces HTTPS/TLS-termination via reverse proxy (Caddy/Nginx).

[//]: # (Metadata: [Security_Model])
