> For the complete documentation index, see [llms.txt](https://gotts.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gotts.gitbook.io/docs/gotts-vaults/vault/10-safety.md).

# Safety Architecture

> **Part of**: [Vault PRD](/docs/gotts-vaults/vault.md) | **Last Updated**: 2026-02-17

***

## Safety Architecture

### Defense-in-Depth for Vault Operations

The vault applies a 15-layer defense model. See [shared/safety-layers.md](/docs/prd-shared/safety-layers.md) for the **canonical layer definitions, scope matrix, and TEE limitations**.

The vault implements **all 15 layers (0-10, 2.5, 13-15)**. Layers 0 and 10 are vault-specific (always active). Layers 1-9 are provided by the vault's built-in safety checks, or by mcp-server's full pipeline when installed as an optional peer dependency. Layers 4 and 5 provide the **reactive defense** layer that transforms agent security from purely preventive to also reactive, specifically targeting prompt injection attacks.

**Layer 2.5: MCP Integrity Verification** (new — addresses the primary attack surface):

> Research consensus: The MCP interface is the #1 attack vector for AI agents in DeFi (CrAIBench arXiv:2503.16248, TradeTrap arXiv:2512.02261, protocol exploits survey arXiv:2506.23260). Memory injection is more powerful than prompt injection. "Fake MCP" servers manipulate trading decisions. Prompt-based defenses are fundamentally inadequate for stored context corruption.

For vault operations (the highest-value targets), the MCP integrity layer provides:

1. **Tool provenance signing**: Vault MCP tool responses are cryptographically signed — agents verify signatures before acting on vault state data
2. **Independent state verification**: Before vault writes (deposit, withdraw, rebalance), critical state is re-read via a separate RPC endpoint
3. **MCP-Guard**: Three-stage detection (static + semantic + fine-tuned E5) achieving 96% accuracy on attack detection
4. **Memory integrity hashing**: Context hash stored outside LLM context window, verified before every vault write

See [mcp-server/09-safety.md](/docs/gotts-safe-mcp-server/mcp-server/09-safety.md) Section 6.10 for the full specification.

**Layer 8: API Response Validation** (when using Uniswap Trading API path):

When vault operations use the Uniswap Trading API execution path (`GOTTS_UNISWAP_API_KEY` is configured), Layer 8 (API Response Validation) from the MCP server safety pipeline applies. This validates transaction data integrity (`TransactionRequest.data` non-empty), quote freshness (reject quotes > 30s), routing type consistency, Permit2 signature matching, and gas fee thresholds before any vault write operation. See [mcp-server/09-safety.md](/docs/gotts-safe-mcp-server/mcp-server/09-safety.md) Section 6.7a for the full specification.

### Layer 0: ERC-8004 Identity Verification (Vault-Specific)

Before any operation enters the safety pipeline, the vault tool verifies the calling agent's ERC-8004 registration:

1. Query `identityRegistry.getAgentWallet(agentId)` -- verify wallet matches
2. Query `identityGuardian.credentialFrozen(agentId)` -- reject if credential is frozen
3. Query `identityGuardian.getEffectiveReputation(agentId)` -- apply transfer decay (see below)
4. Enforce tier-based limits using the vault's configured tier thresholds and the effective (post-decay) reputation

If identity, freeze check, or reputation check fails, the operation is rejected before reaching the safety pipeline.

#### Identity Theft Defense Mechanisms

ERC-8004 identity NFTs are standard ERC-721 tokens with no built-in transfer friction. The protocol adds five defense mechanisms to detect, delay, and recover from identity theft. Full architecture details are in [03-custody.md](/docs/gotts-vaults/vault/03-custody.md) Section 8; contract specification is in [06-contracts.md](/docs/gotts-vaults/vault/06-contracts.md) Section 10.15a.

> **v1 scope**: For v1, only **two** of the five mechanisms ship: *reputation decay on transfer* and *velocity signal detection*. The remaining three (SBT milestone locks, behavioral anomaly detection, per-identity ERC-7265 breakers) are deferred until ERC-8004 stabilizes past Draft status. This reduces the identity attack surface area for a standard still being refined. All five mechanisms are retained in the specification below for completeness; deferred items are marked.

**Reputation Decay on Transfer**:

When an ERC-721 `Transfer` event is detected for an identity NFT, the effective reputation drops to near-zero and recovers linearly over 30 days. This prevents an attacker from immediately using a stolen high-reputation identity to access high-value vaults.

```
effectiveRep = baseRep * min(timeSinceTransfer / 30 days, 1.0)
```

| Time Since Transfer  | Effective Reputation (if base = 100) | Tier Impact         |
| -------------------- | ------------------------------------ | ------------------- |
| 0 (just transferred) | 0                                    | Drops to Unverified |
| 1 day                | 3.3                                  | Unverified          |
| 7 days               | 23.3                                 | Basic               |
| 15 days              | 50.0                                 | Verified            |
| 30 days              | 100.0                                | Full restoration    |

This decay does **not** apply to key rotation on the same smart contract wallet (no `Transfer` event is emitted when keys rotate). Only actual NFT transfers trigger decay.

**Transfer Velocity Signal**:

Identities with 2+ transfers within a 90-day rolling window are automatically flagged as high-velocity. High-velocity identities:

* Are downgraded to Basic tier regardless of reputation score
* Trigger elevated monitoring on all vault operations
* Cannot deposit above the Basic tier cap ($10,000)
* Must wait for the 90-day window to clear before full tier access is restored

**Soulbound Reputation SBTs**:

Reputation milestones (First Deposit, Steady Staker, Diamond Hands, etc.) are issued as **non-transferable SBTs** held inside the agent's smart contract wallet. When an identity NFT transfers to a new wallet:

* The SBTs stay in the original wallet -- the new owner inherits the identity handle but not the granular reputation credentials
* The effective reputation (after decay) reflects only the transferable base score, not SBT-boosted milestones
* SBTs serve as an audit trail: the original wallet retains proof of its historical identity association

This implements the a16z two-token model: non-transferable "points" (SBTs) alongside the transferable "coin" (identity NFT). Points cannot be purchased and must be earned through on-chain actions.

**Behavioral Anomaly Detection**:

Post-transfer behavioral change detection provides a secondary signal for identity sale or theft:

* **Transaction pattern shift**: Different contract interaction patterns, function call distributions, or gas spending profiles compared to pre-transfer history
* **Timing profile change**: Different time-of-day or day-of-week activity patterns
* **Counterparty shift**: Interactions with a substantially different set of addresses post-transfer
* **Rapid capability change**: Immediate use of vault features the identity had not previously used

Anomaly detection is advisory (triggers monitoring alerts and human review) rather than blocking, to avoid false positives from legitimate operational changes.

**ERC-7265 Circuit Breaker for Identity-Gated Outflows**:

If an identity's vault withdrawals exceed **2x the 7-day moving average**, the ERC-7265 circuit breaker activates automatically. Two modes are supported:

* **Delay settlement** (default): Outflows during the circuit break period are held in custody and settled after a 24-hour cooldown, giving guardians time to freeze the credential if theft is confirmed
* **Revert mode**: Outflows during the circuit break period revert immediately, requiring the agent to wait for the break to clear

Circuit breaker parameters are per-identity and configurable by the vault creator:

| Parameter                       | Default  | Description                                             |
| ------------------------------- | -------- | ------------------------------------------------------- |
| `withdrawalThresholdMultiplier` | 2.0x     | Multiple of 7-day moving average that triggers breaker  |
| `breakerCooldown`               | 24 hours | Duration of the circuit break                           |
| `breakerMode`                   | delay    | `delay` (hold and settle) or `revert` (reject outflows) |

### Layer 1: Wallet Architecture (TEE Key Management + Defense-in-Depth)

Agent wallet keys are generated, stored, and used exclusively inside Trusted Execution Environments (AWS Nitro Enclaves). Keys never leave secure hardware. Privy is the supported TEE wallet provider. See [03-custody.md](/docs/gotts-vaults/vault/03-custody.md) for provider selection and architecture details.

**TEE Limitations — All TEEs Breakable for <$50 (D-036)**: Two escalating attacks have rendered TEE-only security untenable:

* **TEE.Fail** (ACM CCS 2025): Physical side-channel attacks using <$1,000 hardware break Intel SGX, Intel TDX, and AMD SEV-SNP. Forged TDX attestation proofs on Ethereum BuilderNet.
* **BadRAM** (De Meulemeester et al., IEEE S\&P 2025): DDR4/DDR5 SPD chip tampering costing **<$10** breaks AMD SEV-SNP. Some DIMMs enable **software-only attacks via SSH**.
* **Battering RAM** (Van Bulck et al., IEEE S\&P 2026): A DDR4/DDR5 memory interposer costing **<$50** breaks **Intel TDX, AMD SEV-SNP, AND NVIDIA Confidential Computing**, forging attestation quotes with "UpToDate" trust designation. All major cloud TEE vendors acknowledged.

The convergence of these findings is definitive: for cloud-hosted agents, **TEEs provide defense-in-depth, not defense-in-total**. Time-delayed proxy execution (Layer 4) is the **primary** security primitive — it is the only mechanism that no hardware attack, prompt injection, or compromised LLM can bypass, because enforcement is on-chain and cancellation requires a separate key. TEEs remain necessary (they raise the attack bar for remote-only adversaries and prevent the most common key exfiltration vectors) but must be layered with policy engine enforcement (Layer 3), time-delayed execution (Layer 4), and active monitoring (Layer 5).

Additionally, **SEAgent** (Ji et al., arXiv:2601.11893, Jan 2026) identifies the **confused deputy problem** in multi-agent LLM systems: inter-agent trust exploitation achieves an **84.6% attack success rate** versus 46.2% for direct prompt injection. This reinforces that the agent authorization boundary — not the key management boundary — is the critical attack surface.

**ERC-7579 SmartSession for Agent Wallets**: The SmartSession module (developed by Rhinestone and Biconomy) enables session key-based delegation with granular policies -- exactly what agent vaults need. An agent receives a scoped session key allowing specific vault operations (rebalancing, harvesting) within defined limits, without accessing the root owner key. Composable with:

* **SpendingLimitHook**: Enforces per-period spending caps per session key
* **ColdStorageHook**: Timelock on withdrawals above a threshold
* **AllowedTargetsHook**: Restricts session key to specific contract addresses

Session key scopes map to reputation tiers:

| Tier       | Session Scope          | Max Operation Size | Session Duration |
| ---------- | ---------------------- | ------------------ | ---------------- |
| Unverified | deposit/withdraw only  | $1,000             | 1 hour           |
| Basic      | deposit/withdraw/claim | $10,000            | 4 hours          |
| Verified   | + rebalance            | $50,000            | 24 hours         |
| Trusted    | + adapter management   | $100,000           | 7 days           |
| Sovereign  | full Allocator scope   | Unlimited          | 30 days          |

### Layer 2: Prompt Injection Defense

Prompt injection is ranked **OWASP LLM01:2025** — the number-one security vulnerability for LLM applications. The UK's NCSC warns it may be a problem that is never fully solved. Claude's System Card reports blocking approximately 88% of prompt injections, but **12% still succeed**. For an agent managing a DeFi vault, a 12% failure rate is catastrophic.

**The Confused Deputy Problem**: The AI agent holds legitimate credentials but can be tricked into misusing them. Attackers don't need to steal keys — they manipulate the agent's reasoning. CrAIBench research on ElizaOS demonstrated how adversaries inject malicious instructions into prompts or historical interaction records, leading to unintended asset transfers. Critically, **prompt-based defenses were found ineffective** against context manipulation; only fine-tuning-based defenses and architectural separation provided meaningful protection.

**Mandatory mitigations for vault agents:**

1. **System prompt hardening**: Agent knows its role is vault-only (deposit, withdraw, monitor). Treats all on-chain data (vault names, token symbols, metadata URIs) as data, never as instructions. Refuses operations outside its defined scope.
2. **Data/decision separation (dual-LLM architecture)**: Recommended for high-AUM agents (>$50K). One sandboxed LLM processes untrusted external data (vault metadata, token names, on-chain strings) and produces sanitized summaries. A separate privileged LLM receives only sanitized summaries and makes tool-calling decisions. This prevents the attack vector where malicious vault metadata or token names contain injection payloads.
3. **Mandatory simulation**: Every write operation is simulated via `eth_call` against real-time blockchain state before broadcast. The simulation reveals expected balance changes. If the simulation shows unexpected fund movement, the transaction is rejected before signing.
4. **TEE-enforced policy engine as hard stop**: Layers 1 and 3 provide cryptographic enforcement. Even if the LLM is fully compromised, the TEE refuses to sign transactions outside the policy-defined envelope -- unauthorized contracts, unauthorized methods, unauthorized value transfers are all rejected at the hardware level.
5. **Time-delayed proxy as reactive stop**: Layers 4 and 5 provide the reactive defense that no preventive mechanism offers. Even if a transaction passes all preventive checks (because prompt injection makes it "legitimate-looking"), the mandatory delay window allows automated monitoring and human review to catch and cancel it before execution.
6. **Multi-agent defense pipeline**: Research from early 2026 (arXiv:2509.14285) demonstrates a multi-agent pipeline achieving **100% prompt injection mitigation** across all tested scenarios. The pattern: a domain LLM generates candidate actions, a mandatory guard agent vets for policy violations and attack indicators, and only guarded output reaches execution. For Gotts Vaults, every agent action touching funds should pass through an independent guard model before signing. The zero-click RCE vulnerability in MCP-based IDEs (CVE-2025-59944) -- where a Google Docs file triggered an agent to execute a Python payload via MCP server -- demonstrates that tool-calling agents are uniquely vulnerable to indirect injection.
7. **CaMeL capability-based authorization (D-040)**: CaMeL (Debenedetti et al., arXiv:2503.18813, Mar 2025; 66+ citations) creates a capability-based security layer that **separates control flow from data flow**. Untrusted data can never impact program flow. Achieves 77% task completion with provable security (vs 84% undefended). For vault agents, this translates to: agents receive **capability tokens** authorizing specific transaction types (deposit, withdraw, rebalance), amounts (within tier limits), and destinations (vault contract addresses). The capability token is a structured object independent of the LLM's reasoning — even a fully compromised LLM cannot forge a capability it was not issued. Beurer-Kellner et al. (arXiv:2506.08837, Jun 2025) provide six principled design patterns with a critical result: **general-purpose agents with broad capabilities are inherently insecurable with current LLM technology**. This validates the vault's narrow-scope agent design — vault agents should implement the **Action-Selector** pattern (pre-defined transaction templates only) and **Plan-Then-Execute** pattern (fix the plan before processing any external data).
8. **Formal privilege specification via DSL (D-040)**: Progent (Shi et al., arXiv:2504.11703, Apr 2025) introduces the first privilege control framework using a domain-specific language (DSL) for fine-grained tool access policies, with **formal verification via Z3 SMT solver** for policy analysis. For vault wallets, this enables formally verified policy definitions — e.g., "agent may deposit <= $10,000 to whitelisted vault addresses without delay; rebalances > $50K require 1h delay and monitoring approval" — with provable guarantees that the policy cannot be violated regardless of agent behavior.

**Defense layering ensures no single bypass is sufficient:**

```
    Layer 1: System prompt instructs vault-only behavior
            ↓ (12% bypass rate — insufficient alone)
    Layer 2: Dual-LLM prevents data-as-instructions
            ↓ (requires compromising two separate LLMs)
    Layer 3: TEE policy engine restricts agent to proxy only
            ↓ (cryptographic — cannot be reasoned around)
    Layer 4: Time-delayed proxy queues tx with mandatory wait
            ↓ (on-chain — tx is publicly visible and cancellable)
    Layer 5: Monitoring bot evaluates and can cancel during delay
            ↓ (automated + human review)
    Layer 6: Simulation detects unexpected fund movement
            ↓ (on-chain state verification)
    Layer 7: Solidity modifiers reject unauthorized callers
            ↓ (immutable code — no override possible)

    Result: Even a fully compromised LLM cannot move funds.
            Layers 1-3 are preventive. Layers 4-5 are reactive.
            Layers 6-7 are enforcement.
```

### Layer 3: Policy Engine (TEE-Enforced Signing Policies)

Privy provides a declarative policy engine evaluated inside the TEE at signing time. No application code can bypass them. In proxy-enhanced mode, the policy restricts the agent to calling only `announce()` on the proxy contract -- not direct contract calls. See [03-custody.md](/docs/gotts-vaults/vault/03-custody.md) section 3 for the full policy specification including vault-participant, vault-manager, and proxy-enhanced templates.

### Role-Based Proxy Enforcement Matrix

Proxy usage is not "all-or-nothing". It is enforced by role and operation class:

| Role                    | Operation Class                                                             | Proxy Requirement       | Delay Tier            |
| ----------------------- | --------------------------------------------------------------------------- | ----------------------- | --------------------- |
| Participant / Allocator | Read-only (`vault_get_*`, rankings/config reads)                            | Not applicable          | None                  |
| Participant / Allocator | Registration/enrollment (`vault_register_agent`, `vault_enroll_reputation`) | Optional                | Routine               |
| Participant / Allocator | Deposit/withdraw <= standard threshold                                      | Optional (configurable) | Standard when proxied |
| Participant / Allocator | Deposit/withdraw > standard threshold                                       | **Required**            | Elevated/High         |
| Manager                 | Rebalance, collect fees, liquidity moves                                    | **Required**            | Elevated/High         |
| Creator / Admin         | Parameter/config changes, role changes, pause/unpause, proxy config         | **Required**            | High/Critical         |

Default policy for core-v1:

* Manager/admin classes are proxy-required.
* Participant writes may be direct only below configured thresholds.

### Execution and Cancel Ownership Model

| Stage                            | Primary Owner                                              | Requirements                                                                                                                                                                                                                                                                                                                                      |
| -------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Announcement (`proxy_announce`)  | Execution agent (`vault-manager` or delegated role)        | Must run simulation before announce                                                                                                                                                                                                                                                                                                               |
| Monitoring and policy evaluation | Watchdog service                                           | Multi-provider event stream + deterministic policy checks                                                                                                                                                                                                                                                                                         |
| Execution (`proxy_execute`)      | Any executor via Permissionless Executor Framework (D-061) | Must re-simulate against latest state before execute. Reward: gas refund + small tip. Any address can call `execute()` after delay elapses — no registration required. The `vault-executor` agent (see [09-agents-skills.md](/docs/gotts-vaults/vault/09-agents-skills.md)) is the canonical agent role for this, but any EOA or bot can execute. |
| Cancellation (`proxy_cancel`)    | Dedicated cancel authority                                 | Separate key with cancel-only policy                                                                                                                                                                                                                                                                                                              |

**Note on execution model**: Proxy execution is one of several operations unified under the Permissionless Executor Framework (see [06-contracts.md](/docs/gotts-vaults/vault/06-contracts.md) Section 10.1b, D-061). The same `IExecutable` interface and reward model applies to CrossVaultCoordinator submissions, LVR-theta calibrations, and behavioral regime classifications. This eliminates the implicit dependency on unspecified "executor services" — all executor-dependent operations are explicitly permissionless with self-funding incentives and Dutch auction escalation for liveness.

### Fail-Mode Policy

* **Required-proxy operations** are **fail-closed** by default.
  * If monitor health is degraded or cancel authority is unavailable, new high-risk announcements are rejected.
* **Optional-proxy operations** may run fail-open only when explicitly configured.
* Announcements that pass delay but are not executed before expiry become stale and must be re-announced.

### Layer 4: Time-Delayed Execution (Announce-Wait-Execute)

> **v1 CRITICAL PATH**: The time-delayed proxy is the PRD's own identified **primary security primitive** (D-036). TEE-based controls (Layers 1-3) provide defense-in-depth but have a documented 12% bypass rate for prompt injection. Without the proxy, v1 security relies entirely on preventive controls. A **simplified v1 proxy** (announcement + fixed delay + cancel, without variable delay tiers or Dutch auction escalation) is a **blocking requirement for mainnet launch**. See "v1 Minimum Proxy" below and [14-milestones.md](/docs/gotts-vaults/vault/14-milestones.md) Phase 3 acceptance gate.

Proxy-required writes route through a time-delayed proxy (`packages/agent-proxy/`). Instead of directly calling vault contracts, the agent calls `announce(target, value, data)` on the proxy. The transaction is stored on-chain as a hash with a mandatory delay before execution.

**Variable Delay Schedule** -- delay duration scales with transaction risk:

| Risk Tier | Delay             | Example Operations                                         | Threshold        |
| --------- | ----------------- | ---------------------------------------------------------- | ---------------- |
| Routine   | 0s (bypass proxy) | Read-only queries, small deposits under $100               | < $100           |
| Standard  | 10 min            | Vault deposits/withdrawals under $10K                      | $100 - $10K      |
| Elevated  | 1 hour            | Rebalances, CCA bids, LP deployment                        | $10K - $100K     |
| High      | 24 hours          | Parameter changes, large withdrawals, proxy config changes | > $100K          |
| Critical  | 48 hours          | Vault pause/unpause, manager role changes                  | Admin operations |

Vault creators configure which risk tier applies to each operation type. The `DelayEngine` SDK class (`packages/agent-proxy/sdk/`) computes the appropriate delay for a given transaction based on the configured risk tier mapping.

**Announcement expiration**: Every announcement has a configurable expiration window (default 24 hours after the delay elapses). If not executed within the expiration, the announcement becomes stale and must be resubmitted. This prevents forgotten announcements from executing days later.

Three integration paths are supported (see [03-custody.md](/docs/gotts-vaults/vault/03-custody.md) Section 2.7):

1. **Safe + Zodiac Delay Modifier** (default, battle-tested)
2. **ERC-7579 DelayedExecutor** (cross-platform)
3. **Custom AgentProxy contract** (maximum flexibility)

### Layer 5: Active Monitoring + Cancel Authority (Veto Window)

The monitoring service is the human (or automated) counterpart to the on-chain delay mechanism. Without active monitoring, the delay provides no security -- it merely adds latency.

**Cancel Authority Architecture:**

The cancel authority is a dedicated key (separate EOA from both owner and agent) with a minimal policy: it can only call `cancel()` and `cancelAll()` on proxy contracts. If this key is compromised, the attacker can only prevent transactions (denial of service), never initiate them.

**Redundant Detection:**

The monitoring bot uses two independent detection layers:

1. **Primary**: Custom bot using viem's `watchContractEvent` connected to multiple WebSocket RPC providers (e.g., Alchemy + QuickNode + Infura). Events are deduplicated by `txId`.
2. **Secondary**: Tenderly Web3 Action triggered by the same event, providing managed infrastructure with built-in retry and no operational overhead.

**Automated Evaluation Policy:**

Every `TransactionAnnounced` event is evaluated against a three-tier decision matrix:

* **Auto-cancel**: Unknown target contracts, dangerous selectors (e.g., `approve()` to unrecognized spenders), addresses not on whitelist
* **Human review**: High-value transactions above threshold, unusual patterns, first-time targets
* **Allow**: Transactions matching known-good patterns (recognized vaults, standard operations within normal ranges)

**Multi-Channel Alerting:**

Notifications fire to Telegram, Discord, and PagerDuty (for high-value transactions requiring human acknowledgment) in parallel. Every announcement generates at least one notification -- even allowed transactions are logged for audit.

**Tenderly Simulation Before Cancel:**

For the "human review" tier, the monitoring bot can optionally simulate the queued transaction via Tenderly to verify it actually does something harmful before cancelling. This reduces false positives.

**Infrastructure Requirements:**

* Run on 2+ cloud providers (AWS + GCP) with restart policies
* WebSocket heartbeat checks and automatic reconnection
* Cancel authority key stored in KMS (AWS KMS, HashiCorp Vault), not environment variables
* **OpenZeppelin Monitor** (self-hosted, replaces sunsetting OZ Defender) for event detection
* **OpenZeppelin Relayer** (self-hosted) for cancel authority key management with nonce handling

### v1 Minimum Proxy (Blocking Requirement for Mainnet)

The full proxy specification above includes variable delay tiers, Dutch auction escalation, and multiple integration paths. For v1, a **simplified proxy** is the blocking requirement. Deferred complexity can be added in subsequent phases.

**v1 scope (MUST ship)**:

* `announce(target, value, data)` — stores transaction hash on-chain with a fixed delay
* `execute(announcementId)` — executes after delay elapses, before expiration
* `cancel(announcementId)` — cancel authority key can cancel any pending announcement
* `cancelAll()` — cancel authority can cancel all pending announcements (emergency)
* Fixed delay of **10 minutes** for all proxy-required operations (variable tiers deferred)
* Announcement expiration: **24 hours** after delay elapses
* Cancel authority as separate EOA with cancel-only permissions

**v1 non-goals (deferred to Phase 4+)**:

* Variable delay tiers based on transaction value
* Dutch auction escalation for unexecuted announcements
* Permissionless executor integration for proxy execution
* Complex delay computation engine

**Rationale**: D-036 (Battering RAM TEE escalation) proves that TEEs provide defense-in-depth, not defense-in-total. A <$50 memory interposer breaks Intel TDX, AMD SEV-SNP, and NVIDIA CC. The time-delayed proxy is the only security primitive that survives hardware-level compromise. Launching without it means accepting a 12% prompt injection bypass rate with no reactive defense layer.

***

### Layers 6-9: Safety Pipeline (Built-in or mcp-server)

All vault write operations (deposit, withdraw, rebalance, collect, register, and CCA bids when CCA is enabled) pass through safety checks. When using a time-delayed proxy, these checks run at both announcement time and execution time. When `@gotts.ai/safe` is installed as an optional peer dependency, the full pipeline is used. Otherwise, the vault's built-in safety provides equivalent protection:

* **Token Allowlist**: Verify vault base asset (USDC) and LP tokens are allowed
* **Spending Limits**: Per-tx and daily limits, configured per tier
* **Rate Limiter**: Max operations per hour, configured per tier
* **Circuit Breaker**: Native balance floor for gas
* **Slippage Guard**: Applied to rebalance swaps and CCA bid exits
* **Pre-Flight Simulation**: `eth_call` every vault transaction before broadcast
* **Nonce Manager**: Prevent duplicate deposits/withdrawals from LLM retries

### Layer 10: Vault Circuit Breaker (Vault-Specific)

Post-execution monitoring specific to vault operations:

* **NAV Drawdown**: If vault NAV drops >10% from high-water mark in 24h, pause all deposits and rebalances. Withdrawals remain enabled.
* **Position IL Monitoring**: If any individual position IL exceeds 25%, flag for review and prevent further capital allocation to that pool.
* **Vault Utilization**: If >95% of vault capital is in active positions (minimal reserves), prevent new deposits until reserves are restored.
* **Max Rebalance Size**: No single rebalance can move more than 20% of vault assets.
* **Predictive Exit Signal (D-031)**: Pre-emptive position closure before loss materialization, computed off-chain by the `vault-strategist` agent.

**Predictive Exit Timing via Optimal Stopping** (D-031):

> **Research basis**: Bergault, Bieber, Sanchez-Betancourt — "Optimal Exit Time for LPs" (arXiv, Sep 2025). Formalizes LP withdrawal as an optimal stopping problem via HJB quasi-variational inequality; proves viscosity solution uniqueness. The **pre-emptive exit** feature — withdrawing before arbitrageurs correct prices — is particularly valuable: vaults can exit positions before loss materialization, not after.

The existing circuit breakers (NAV drawdown, IL monitoring) are **reactive** — they trigger after losses have already occurred. The optimal exit signal adds a **predictive** layer that identifies when positions should be closed *before* the loss materializes.

**Mechanism**: The `vault-strategist` agent continuously computes the optimal exit boundary using the **Longstaff-Schwartz Monte Carlo method** (well-suited for off-chain computation). The boundary is defined as a function of:

* `sigma`: Current realized volatility of the underlying pair
* `t`: Time since position entry
* `oracle_price - pool_reference_price`: Divergence between external oracle and pool state

**Trigger condition**: When the oracle-pool price divergence exceeds the computed exit boundary, the signal fires:

```
exit_signal = |oracle_price - pool_reference_price| > exit_boundary(sigma, t, position_params)
```

The exit boundary tightens as volatility increases and as positions age (longer-held positions accumulate more embedded optionality). The pre-emptive nature means the vault exits positions while arbitrageurs are still computing their optimal trade — capturing the few seconds of lead time that off-chain computation provides over on-chain arbitrage execution.

**Integration with vault operations**:

1. The `vault-strategist` computes the exit boundary and posts it to an on-chain oracle (updated every N blocks)
2. The VaultHook's `beforeSwap` callback checks the current divergence against the posted boundary
3. If the boundary is breached, the hook triggers an automatic position reduction via TWAMM (spreading the exit over time to minimize impact)
4. The `vault-manager` agent is notified and can override the automatic exit if the signal is a false positive

**Parameters**:

| Parameter                     | Default                     | Description                                                                      |
| ----------------------------- | --------------------------- | -------------------------------------------------------------------------------- |
| `predictiveExitEnabled`       | false                       | Enable predictive exit signal (opt-in)                                           |
| `exitBoundaryUpdateFrequency` | 100 blocks (\~200s on Base) | How often the boundary is recomputed                                             |
| `exitBoundaryConfidence`      | 95%                         | Monte Carlo confidence level for the boundary                                    |
| `autoExitEnabled`             | false                       | Whether breached boundary triggers automatic TWAMM exit (vs advisory alert only) |

### NAV Guardrail System (D-062)

NAV-priced share markets (NAVAwareHook) create new failure modes when NAV depends on oracles, async positions, or manipulable state. The guardrail system decouples instantaneous NAV from hook pricing through four mechanisms:

**Discrete NAV Snapshots**: Rather than using raw `convertToAssets(1 share)` at the instant of a swap, the NAVAwareHook drives pricing from a NAV snapshot updated at a configured cadence. Snapshots are computed by the RiskEngine (D-056) and stored on-chain. Rate-limited updates prevent high-frequency manipulation.

**Rate-of-Change Clamp**: NAV per share cannot change by more than `navMaxChangeBps` per snapshot interval. Upward moves already benefit from profit-unlock smoothing (D-018); the clamp adds a symmetric bound preventing both flash-pump and flash-dump manipulation. Override path: Owner + Curator with `longTimelock` (D-059) can increase the clamp for one interval — used for legitimate large strategy realizations.

**Oracle Staleness Gates**: When required price feeds approach staleness thresholds, the hook degrades gracefully:

* At 80% of `oracleMaxStaleness`: spread widens by `stalenessSpreadMultiplier` (default 2x), making manipulation expensive
* At 100% of `oracleMaxStaleness`: NAV pricing disables entirely; pool falls back to standard constant-product V4 pricing until feeds refresh
* This implements a "no spot assumptions" (D-067) posture at the pricing boundary

**Market Safety Mode**: When any Tier 2+ circuit breaker (D-026/D-043) triggers, the NAVAwareHook enters market safety mode automatically:

* NAV pricing disabled (constant-product fallback)
* Rehypothecation paused (no new lending deployments)
* Maximum spread enforced
* Mode exits only when circuit breaker conditions normalize AND a subsequent NAV snapshot passes the rate-of-change clamp

Note on circuit breaker interaction: Market safety mode is deliberately conservative. The "magnet effect" research (D-043) shows that anticipated halts change agent behavior — but market safety mode is not a halt. Trading continues on the share pool at constant-product pricing; only NAV-aware pricing pauses. Depositors retain the secondary market exit path at all times.

| Parameter                   | Default                    | Description                                        |
| --------------------------- | -------------------------- | -------------------------------------------------- |
| `navSnapshotCadence`        | 50 blocks (\~100s on Base) | How often NAV snapshot updates                     |
| `navMaxChangeBps`           | 50                         | Max NAV change per snapshot interval (bps)         |
| `stalenessSpreadMultiplier` | 2x                         | Spread multiplier when oracle approaches staleness |
| `marketSafetyModeEnabled`   | true                       | Auto-enter safety mode on Tier 2+ circuit breaker  |
| `navOverrideTimelock`       | `longTimelock` (3-7d)      | Delay for temporarily increasing the clamp         |

***

### Protocol-Wide No-Spot-Assumptions Policy (D-067)

**Design principle**: No high-value decision in the protocol may depend on spot/instantaneous on-chain state. All pricing, risk evaluation, and trigger conditions must use TWAP, time-windowed observations, or multi-source aggregation.

This principle extends D-021 (multi-oracle with TWAP) and D-030 (fee-implied vol) from specific mechanisms to a protocol-wide constraint. Enforcement points:

| Decision Type                     | Required Input                                | Spot Prohibited          | Reference |
| --------------------------------- | --------------------------------------------- | ------------------------ | --------- |
| NAVAwareHook share pricing        | Discrete NAV snapshots (D-062)                | Raw `convertToAssets()`  | D-062     |
| Circuit breaker triggers          | Time-windowed drawdown (D-026/D-043)          | Single-block price drops | D-043     |
| Oracle-dependent risk evaluation  | Multi-source aggregation with freshness check | Single oracle spot read  | D-021     |
| Adapter force-exit valuation      | TWAP-based conversion (10-30 min window)      | Instantaneous pool price | D-019     |
| CCA bid sizing and exit           | LVF-calibrated bounds (D-034)                 | Spot clearing price      | D-034     |
| Share price rate-of-change bounds | Rolling window (D-018 profit unlock)          | Block-to-block delta     | D-018     |
| Predictive exit boundary          | Multi-block oracle-pool divergence            | Single-block divergence  | D-031     |

**Default TWAP windows**: 10-30 minutes for high-value decisions; 4-24 hours for NAV calculations; longer windows for low-liquidity assets. Minimum liquidity thresholds and minimum historical observation counts enforced per oracle pool before trusting a price feed.

**Audit checkpoint**: Every contract review must verify that no function path depends on a single-block spot value for decisions affecting >$100 of value. This is a hard audit gate — violations fail the review.

***

### Vault-Level Risk Parameters

Each vault is configured with risk parameters set by the creator at deployment. Parameters can be updated with a timelock (default 48 hours) to prevent sudden changes that disadvantage depositors.

| Parameter                  | Default    | Description                                        |
| -------------------------- | ---------- | -------------------------------------------------- |
| `maxSingleAuctionExposure` | 20% of AUM | Maximum capital committed to a single CCA auction  |
| `maxConcurrentAuctions`    | 5          | Maximum number of active CCA bids simultaneously   |
| `maxTotalCCAExposure`      | 50% of AUM | Maximum total capital in CCA positions             |
| `maxRebalanceSize`         | 20% of AUM | Maximum position size change in a single rebalance |
| `reserveRatio`             | 10%        | Minimum idle capital held for instant withdrawals  |
| `drawdownThreshold`        | 10%        | NAV decline that triggers circuit breaker          |
| `ilThreshold`              | 25%        | Impermanent loss that triggers position review     |
| `utilizationCap`           | 95%        | Maximum capital utilization (5% always idle)       |
| `parameterTimelock`        | 48 hours   | Delay for risk parameter changes                   |

***

### CCA-Specific Risk Controls

For vaults with CCA participation enabled, additional safety checks apply:

* **Auction validation**: Before bidding, the vault validates: token contract is verified, auction has reasonable timeframes, `requiredCurrencyRaised` is achievable given current bid velocity, and the token is not on a known scam registry.
* **Bid sizing**: No single bid can exceed `maxSingleAuctionExposure`. Total across all active bids cannot exceed `maxTotalCCAExposure`.
* **Graduation monitoring**: Bids in auctions unlikely to graduate (declining bid velocity) can be proactively exited to reclaim capital.
* **Post-graduation token handling**: Claimed tokens are subject to a freshness discount (5-10%) in `totalAssets()` calculations. The manager must actively decide to hold, LP, or sell -- no default action to prevent stale positions.
* **Checkpoint validation**: The CCA adapter validates checkpoint hints against on-chain state before submitting. Incorrect hints can result in suboptimal exits.

***

### Reputation Tiers (5 Tiers)

| Tier       | Score | Per-Deposit Max | Per-Rebalance Max | Daily Aggregate Max | Max Ops/Hour |
| ---------- | ----- | --------------- | ----------------- | ------------------- | ------------ |
| Unverified | 0     | $1,000          | N/A               | $5,000              | 10           |
| Basic      | 10+   | $10,000         | $5,000            | $50,000             | 50           |
| Verified   | 50+   | $50,000         | $25,000           | $250,000            | 100          |
| Trusted    | 100+  | $100,000        | $50,000           | $1,000,000          | 500          |
| Sovereign  | 500+  | Unlimited       | Unlimited         | Unlimited           | Unlimited    |

The Sovereign tier is reserved for agents with extensive verifiable track records. These agents have no deposit caps and can operate without rate limits, enabling institutional-scale participation.

***

### Reputation Anti-Gaming Measures

The VaultReputationEngine's milestone system is designed to resist manipulation. Every signal requires real capital, real time, and verifiable on-chain outcomes. The following anti-gaming measures are enforced:

**Wash Deposit Detection.** The engine checks whether the depositor's `agentId` matches the vault's `creatorAgentId`. Self-deposits are excluded from all participant milestones. Creator milestones like Capital Attractor count only unique depositors — the creator's own deposit does not count toward the threshold.

**Dust Deposit Prevention.** The Diversifier milestone requires active positions above the Unverified tier deposit minimum ($1,000) in each vault. An agent depositing $1 into 3 vaults to farm Diversifier is rejected.

**Claim Deduplication.** Each milestone is identified by a composite key: `(agentId, milestoneId, qualifier)`. The qualifier scopes the milestone to a specific context:

* Duration milestones (Steady Staker, Diamond Hands): qualifier = vault address (claimable once per vault held)
* Global milestones (First Deposit): qualifier = null (claimable once ever)
* CCA milestones (CCA Lifecycle): qualifier = auction address (claimable once per auction completed)

Duplicate claims revert at the contract level.

**Engine as Trusted Source.** The engine's contract address is a known, verified source. Consuming protocols call `getSummary(agentId, [engineAddress], tag1, tag2)` to isolate protocol-attested milestones from potentially Sybil-generated peer reviews. This two-source model means automated milestones provide a reliable baseline, while peer feedback can accelerate or boost reputation beyond what milestones alone provide.

**Collusion Resistance.** Two agents creating vaults and depositing into each other's vaults is partially mitigated by:

* Time requirements (Diamond Hands needs 90 days of locked capital)
* TVL thresholds (Capital Attractor needs 5 unique depositors)
* Economic cost (real capital locked for real time makes gaming expensive relative to reputation gained)

Full prevention of collusion rings is an open problem, but the `getSummary` `clientAddresses` filter allows consuming protocols to discount feedback from known collusion patterns.

**Intentional Broad Participation.** An agent claiming milestones across many small vaults is intentionally allowed. This requires real capital deployed across real vaults for real time periods. The milestone scores (70-95) are calibrated so that even maximal farming produces a reputation score reflecting genuine, broad ecosystem participation.

***

### Withdrawal Mechanics

Because the vault holds illiquid positions (active CCA bids, unclaimed tokens, concentrated LP), instant full withdrawal is not always guaranteed. The vault implements a tiered withdrawal system:

**Instant withdrawal**: Available up to the amount of idle base currency (respecting `reserveRatio` minimum, default 10%). No delay, no queue. `maxWithdraw()` and `maxRedeem()` return this amount -- not the full theoretical entitlement.

**Queued withdrawal**: If requested amount exceeds available idle currency, the withdrawal enters a FIFO queue. The vault manager is responsible for unwinding positions to service the queue. Maximum queue duration: 7 days, after which the vault may force-unwind at market prices.

**Emergency withdrawal**: Governance-triggered or circuit-breaker-triggered. All positions unwound at market; depositors claim pro-rata immediately. Last resort -- likely results in suboptimal execution.

**ERC-7540 Extension with Withdrawal Receipt NFTs (D-068)**:

For vaults with significant illiquid allocations, the protocol supports ERC-7540 asynchronous deposits and withdrawals with a three-option exit UX designed to be understandable in under 30 seconds:

| Exit Option        | When Available                  | Speed                    | Cost               | Mechanism                                                    |
| ------------------ | ------------------------------- | ------------------------ | ------------------ | ------------------------------------------------------------ |
| **"Withdraw now"** | Idle capital available          | Instant                  | 0 bps              | Standard `withdraw()`/`redeem()` up to `maxWithdraw()`       |
| **"Request exit"** | Withdrawal exceeds idle capital | Queued (hours to 7 days) | 0 bps              | ERC-7540 `requestRedeem()` -> NFT receipt -> `claimRedeem()` |
| **"Force exit"**   | Any time (adapter supports it)  | Instant                  | 50-200 bps penalty | `forceDeallocate()` (D-019) on specific adapters             |

**Withdrawal receipt NFTs** (Lido-style pattern): When a depositor calls `requestRedeem()`, they receive an ERC-721 receipt NFT representing their claim in the FIFO queue. The receipt contains: amount, position in queue, estimated wait time, and current fulfillment rate. Receipt NFTs are **tradeable** — impatient depositors can sell their claim at a discount on secondary markets, creating a price discovery mechanism for withdrawal priority. This reduces panic withdrawal pressure because agents with urgent liquidity needs have an alternative to forcing vault-level emergency unwinds.

**Force exit with penalty disclosure**: The MCP tool `vault_force_exit` and SDK method `vault.forceExit()` both display the exact penalty amount (in base asset terms) before confirmation. The penalty compensates remaining depositors — it must not create a share price pump exploitable by coordinated force-exit/deposit cycles (adapter conservation invariant #3, D-060).

**Crisis UX flow** (for monitoring dashboards and agent decision-making):

```
Depositor wants to exit
         │
         ▼
  ┌─── Check idle capital ────────────────────────────────┐
  │ maxWithdraw() > 0?                                     │
  │   YES → "Withdraw now" (instant, 0 cost)               │
  │   NO  → continue                                       │
  └────────┬───────────────────────────────────────────────┘
           │
           ▼
  ┌─── Check urgency ─────────────────────────────────────┐
  │ Can wait for queue?                                    │
  │   YES → "Request exit" (receipt NFT, queue position)   │
  │         Receipt is tradeable if urgency changes        │
  │   NO  → continue                                       │
  └────────┬───────────────────────────────────────────────┘
           │
           ▼
  ┌─── Force exit available? ──────────────────────────────┐
  │ Adapter supports forceDeallocate()?                    │
  │   YES → "Force exit" (show penalty: X bps = $Y)       │
  │         Confirm → instant exit with penalty            │
  │   NO  → "Request exit" only path (ERC-7540 queue)     │
  └────────────────────────────────────────────────────────┘
```

At every stage, depositors retain the ability to sell vault shares on the auto-created V4 pool — the secondary market exit path is independent of the vault's withdrawal mechanism.

***

### On-Chain Safety (Enforced in Solidity)

On-chain safety cannot be bypassed even by a fully compromised LLM:

* **AgentVaultCore**: `onlyAgent` + `hasReputation` + `withinTierLimit` modifiers on every function
* **AgentVaultFactory**: `onlyRegisteredAgent` modifier on `createVault()`
* **VaultHook**: `_beforeSwap` rejects any address not in the `authorized` mapping
* **VaultHook**: `_beforeAddLiquidity` rejects unauthorized LP additions
* **CCABidAdapter**: `onlyManager` modifier prevents unauthorized bid submission
* **AgentGatedPool**: `onlyVault` modifier prevents unauthorized pool creation
* **FeeModule**: Fee caps enforced by factory (5% management, 50% performance)

***

### Real-World Incident Lessons

Three incidents define the current threat landscape. Each maps directly to a safety layer:

| Incident                    | Loss            | Root Cause                                                    | Layer That Would Prevent                                                             |
| --------------------------- | --------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| **AIXBT hack** (March 2025) | $106K           | No wallet policy -- compromised dashboard sent funds anywhere | Layer 3 (policy) + **Layer 4-5 (proxy + monitoring would auto-cancel)**              |
| **Bybit hack** (2025)       | $1.5B           | Supply chain exploit on Safe signing interface                | Defense-in-depth (multiple layers) + **Layer 4 (delay would provide cancel window)** |
| **SCONE-bench** (Anthropic) | $550M simulated | AI agents exploited 207 of 405 historical smart contracts     | Layer 6 (simulation) + Layer 7 (on-chain guards)                                     |

For detailed incident analysis, see [03-custody.md](/docs/gotts-vaults/vault/03-custody.md) section 5.

***

### Production Security Checklist

Before deploying an agent to interact with vaults in production, verify every item. Each maps to a real-world incident or known vulnerability.

**Identity NFT Security (Prevents Identity Theft)**

* [ ] Identity NFT is held in a smart contract wallet (ERC-4337 or Safe), not an EOA
* [ ] Guardian is enabled on the identity NFT (default for all new identities)
* [ ] Safe Transaction Guard blocks `transferFrom` and `safeTransferFrom` selectors for the Identity Registry contract
* [ ] Module Guard also installed (Safe v1.5+) to prevent module-initiated identity transfers
* [ ] Monitoring alerts configured for Identity Registry `Transfer` events involving the agent's token ID
* [ ] Sudo key (for recovery/rotation) is stored in cold storage, separate from operational keys
* [ ] At least 2-of-3 guardians configured for social recovery
* [ ] Dead man's switch configured if the agent may operate unattended for extended periods
* [ ] Consider burning `CANNOT_TRANSFER` fuse for agents at Trusted tier or above (reputation >= 100)

**Wallet Security (Prevents AIXBT-Class Attacks)**

* [ ] Wallet policy is configured -- agent cannot sign transactions to arbitrary addresses
* [ ] Contract allowlist is minimal -- only vault, USDC, and Identity Registry addresses (or proxy only in proxy-enhanced mode)
* [ ] Method allowlist is minimal -- only `deposit`, `withdraw`, `approve`, `register` (or only `announce()` in proxy-enhanced mode)
* [ ] Per-transaction value cap is set -- limits single-transaction exposure
* [ ] Daily aggregate cap is set -- limits 24-hour cumulative exposure
* [ ] Keys are TEE-isolated -- using Privy (not raw private keys)

**Time-Delayed Proxy Security (Reactive Defense)**

* [ ] Proxy contract is deployed and configured (required for manager/admin operations and high-value participant writes)
* [ ] Cancel authority is a separate EOA from both owner and agent
* [ ] Cancel authority key is stored in KMS (AWS KMS, HashiCorp Vault), not environment variables
* [ ] Monitoring bot is running with redundant RPC connections (2+ providers)
* [ ] Secondary monitoring (Tenderly Web3 Action) is configured as backup
* [ ] Auto-cancel rules are configured for unknown targets and dangerous selectors
* [ ] Variable delay schedule is configured per risk tier
* [ ] Announcement expiration is set (default 24 hours)
* [ ] Multi-channel alerting is active (Telegram, Discord, or PagerDuty)
* [ ] Monitoring bot runs on 2+ cloud providers with restart policies

**Agent Security (Prevents Prompt Injection Exploitation)**

* [ ] System prompt includes vault-specific guardrails -- agent knows its role is limited
* [ ] Agent does not process untrusted external data as instructions
* [ ] Dual-LLM architecture considered for high-AUM agents (>$50K)
* [ ] Transaction simulation enabled -- agent calls `vault_simulate_deposit` before `vault_deposit`

**Protocol Security (Prevents Smart Contract Exploits)**

* [ ] Vault is factory-deployed -- verify via `factory.isVault(address)`
* [ ] Creator reputation is non-zero -- check via `vault_get_agent_reputation`
* [ ] Vault parameters are reasonable -- management fee <=5%, performance fee <=50%
* [ ] ERC-4626 share price is sane -- compare `convertToAssets(1e18)` against recent history
* [ ] Circuit breaker is enabled -- vault has `drawdownThreshold` configured

***

## Cross-Vault Insurance (Factory-Level)

Embedded insurance should be a vault-level feature, not an afterthought. Three models are viable for the factory architecture:

### Hierarchical Tranched Insurance (Recommended for Factory) (D-039)

> **Research basis**: Feng, Liu & Taylor — "A Unified Theory of Decentralized Insurance" (Insurance: Mathematics and Economics, Vol. 119, 2024, pp. 268-297). Proves **hierarchical structures outperform flat pools** under many conditions. Additionally, Nguyen et al. — "Determinants of Funding Liquidity Risk in Decentralized Lending" (Global Finance Journal, Vol. 64, Mar 2025) finds that lower deposit concentration may **exacerbate** rather than mitigate funding liquidity risk — many small depositors are more flighty than fewer large ones.

Vaults in the factory mutually cover each other via a **two-tranche hierarchical structure** rather than flat pro-rata loss sharing. This design outperforms the simpler Ease.org-style uninsurance model because correlated exploit events (which dominate DeFi loss distributions) are better absorbed by tiered structures:

* **Junior Tranche**: Absorbs the first `juniorCoverageBps` (default 300 = 3%) of any single-vault exploit loss. Funded by a portion of vault management fees (default 10% of management fee revenue). Depositors into the junior tranche earn a higher yield premium.
* **Senior Tranche**: Covers residual losses after the junior tranche is exhausted, up to `maxLossShareBps`. Funded by the broader factory vault pool. Pro-rata sharing applies only within this tranche.

This mirrors the proven securitization structure where junior tranches absorb first losses, protecting senior participants. The junior tranche is explicitly sized for **correlated** rather than independent loss events — a critical distinction since DeFi exploits tend to cluster (e.g., oracle manipulation affecting multiple vaults simultaneously).

| Parameter                | Default    | Description                                                                             |
| ------------------------ | ---------- | --------------------------------------------------------------------------------------- |
| `coveragePoolEnabled`    | true       | Opt-in to factory-level mutual coverage                                                 |
| `juniorCoverageBps`      | 300 (3%)   | First-loss absorption by junior tranche                                                 |
| `maxLossShareBps`        | 500 (5%)   | Maximum loss any single vault absorbs from another vault's exploit (senior tranche)     |
| `minParticipatingVaults` | 10         | Coverage only activates when factory has sufficient diversification                     |
| `juniorFundingBps`       | 1000 (10%) | Percentage of management fee revenue directed to junior tranche                         |
| `maxCompositionDepth`    | 2          | Maximum vault nesting depth for meta-vaults (D-046; per Kitzler et al., ACM TWEB, 2024) |

**Withdrawal Run Risk Mitigation**: The Nguyen et al. finding that fragmented deposit bases increase run risk motivates two additional controls:

* **Time-weighted withdrawal dampening**: Deposits held for less than 7 days face a soft withdrawal fee (default 25 bps) that decays linearly to zero over the holding period. This discourages hot-money deposits that amplify run dynamics without penalizing long-term participants.
* **Composition depth limit** (D-046): Meta-vaults (vaults of vaults) are limited to depth 2 based on Kitzler et al.'s empirical contagion analysis. Deeper nesting requires additional insurance scaling enforced at the factory level. Bartoletti et al.'s MEV non-interference framework (arXiv:2309.10781, FC 2024) should be used to formally verify that vault-of-vaults compositions satisfy secure composability before deployment.

### External Reinsurance (Complementary)

For higher coverage tiers, factory-level coverage can be augmented with external reinsurance:

* **Nexus Mutual + Symbiotic**: Capital simultaneously secures PoS networks and underwrites coverage — capital-efficient and scalable. Nexus Mutual's capital pool is **\~$190M** with **$194M in active coverage**.
* **Parametric insurance (Neptune Mutual model)**: Smart contracts auto-pay when predefined events occur (oracle deviations, circuit breaker triggers), eliminating claims assessment. Risk Harbor paid **$2.5M during UST depeg** using this model.

### Reputation-Based Risk Pricing

Agent reputation scores from ERC-8004 feed into dynamic insurance pricing: **lower premiums for agents with higher reputation scores = direct economic incentive for good behavior**. Data sources include:

* ERC-8004 Reputation Registry feedback signals (direct on-chain history)
* Cred Protocol (acquired by RedStone, September 2025) on-chain wallet scoring — generates credit reports with debt-to-collateral ratios
* Credora's Consensus Ratings Protocol — aggregates ratings from Jump Crypto, GSR, and XBTO

Vault creators with higher reputation pay lower insurance premiums, and depositors into higher-reputation vaults face lower socialized risk contributions. Aquilina et al. (BIS Working Paper 1227, 2024) find that **65-85% of Uniswap V3 liquidity is provided by a small professional group** earning significantly more than retail LPs, validating the vault-as-professional-curator model. This supports **performance-based fees** (hurdle rate + carry, D-047) rather than flat management fees as the optimal compensation structure for vault managers.

***

## Monitoring Infrastructure

### Forta Network Integration

**Forta Network** provides decentralized detection bots monitoring on-chain activity in real-time. Attack Detector 2.0 achieves an **83% true positive rate** and is integrated with protocols covering **$36B+ TVL**. Recommended Forta bot configurations for vault monitoring:

* **Unusual withdrawal pattern detection**: Alerts when withdrawal velocity exceeds 3x historical average
* **Oracle deviation monitoring**: Detects when vault NAV calculations diverge from external price feeds
* **Admin action alerts**: Real-time notification of any vault configuration changes or role modifications
* **Cross-vault correlation**: Detects coordinated attacks across multiple factory vaults

### OpenZeppelin Monitor (Self-Hosted)

**OpenZeppelin Defender is sunsetting July 1, 2026.** New deployments should use **OpenZeppelin Monitor** (self-hosted event detection, open-source) and **OpenZeppelin Relayer** (self-hosted key management with nonce handling) as replacements. The monitoring bot for time-delayed proxy cancel authority should run on this stack.

### Canonical Event Schema + On-Chain Health Attestations (D-066) — Normative

> **NORMATIVE REQUIREMENT**: Every vault deployed by the factory MUST emit the standardized events defined below. Dashboards MUST be derivable from on-chain events alone (subgraphs are optional enhancements, not requirements). This is a v1 launch requirement -- contracts that do not emit these events fail the Phase 5 acceptance gate.

Observability is a first-class protocol feature, not an afterthought. All vault contracts emit structured events following a standard taxonomy. Every production monitoring dashboard derives from these on-chain signals — no external SaaS dependency for core health assessment.

**Standard event taxonomy**:

| Event                                                                                           | Emitter                  | Cadence                                                               | Purpose                                                            |
| ----------------------------------------------------------------------------------------------- | ------------------------ | --------------------------------------------------------------------- | ------------------------------------------------------------------ |
| `VaultHealthSnapshot(vault, totalAssets, sharePrice, idleRatio, adapterCount, oracleFresh, ts)` | RiskEngine               | Every `healthSnapshotCadence` blocks (default 300 / \~10 min on Base) | Periodic health summary for composing protocols                    |
| `NAVUpdate(vault, previousNAV, newNAV, snapshotBlock, oracleTimestamp)`                         | NAVAwareHook             | Every `navSnapshotCadence` blocks (D-062)                             | NAV change tracking for share pool pricing                         |
| `RiskWarning(vault, warningType, severity, currentValue, threshold)`                            | RiskEngine               | On threshold crossing                                                 | Risk state changes (oracle stale, exposure cap approach, drawdown) |
| `AdapterStateChange(vault, adapter, action, assetsDelta, newExposureBps)`                       | StrategyAdapter Registry | On allocate/deallocate                                                | Adapter-level capital flow tracking                                |
| `ParameterChanged(vault, paramId, oldValue, newValue, authority, justificationHash)`            | ParameterDecisionTable   | On parameter update                                                   | Governance audit trail                                             |
| `CircuitBreakerTriggered(vault, tier, drawdownBps, cfiLevel, dampedRate)`                       | RiskEngine               | On breaker activation                                                 | Circuit breaker state changes                                      |
| `HookStateChanged(vault, hookAddress, newState, caller, timestamp)`                             | HookKillSwitch           | On enable/disable                                                     | Hook lifecycle tracking                                            |
| `WithdrawalQueued(vault, depositor, amount, receiptTokenId, queuePosition)`                     | AgentVaultCore           | On ERC-7540 request                                                   | Withdrawal queue tracking                                          |

**On-chain health attestations**: Periodic on-chain assertions that key invariants hold, queryable by external protocols:

```solidity
interface IHealthAttestation {
    /// @notice Returns the latest health attestation for a vault
    /// @return healthy True if all invariants pass
    /// @return attestationBlock Block number of the attestation
    /// @return details Bitmask of individual invariant results
    function getHealthAttestation(address vault)
        external view returns (bool healthy, uint256 attestationBlock, uint256 details);
}
```

Invariants verified in each attestation:

1. `totalAssets >= sum(adapterAssets) + idleAssets` (within rounding tolerance)
2. `sharePrice` within `navMaxChangeBps` of last snapshot (D-062)
3. All oracle feeds fresh (below `oracleMaxStaleness`)
4. No adapter above exposure cap (`maxExposureBps`)
5. Idle reserve ratio above minimum (`reserveRatio`)
6. No active circuit breaker at Tier 2+

External protocols (Morpho, Pendle) call `riskEngine.getHealthAttestation(vault)` before accepting vault shares as collateral or listing them for yield tokenization. A failed attestation signals degraded vault state — consuming protocols can reduce LTV ratios, pause new collateral acceptance, or halt PT/YT minting accordingly.

### Production Monitoring Dashboards

The monitoring stack must be organized around four questions: **"Can users exit safely?"**, **"Is NAV coherent?"**, **"Are modules behaving?"**, and **"Is governance behaving?"**. Every production vault deployment requires dashboards covering these four categories.

**Vault Health Dashboard**:

* TVL (absolute and trend), `totalAssets()`, share price, share price velocity (bps/min)
* Drawdown from high-water mark (absolute and rolling 24h)
* Realized vs expected volatility
* Idle liquidity ratio vs target reserve (`reserveRatio`)
* Withdrawal queue depth and oldest pending request age

**Share Pool Integrity Dashboard**:

* Share pool price vs NAV (continuous, with 75 bps deviation highlight)
* NAV TWAP vs spot deviation
* Hook error rates and callback invocation counts (per block)
* Reverted operations count and revert reason distribution

**Strategy/Adapter Dashboard**:

* Exposure per adapter and per venue as percentage of cap (visual gauge)
* Utilization depth per adapter (where measurable from underlying protocol)
* Realized PnL per adapter (rolling 7d, 30d)
* "Unexplained PnL" — PnL not attributable to observable market moves (alert signal)
* In-kind exit (`forceDeallocate`) usage rate, penalty paid, exit latency
* Adapter health score (composite: utilization ratio, NAV accuracy, exit success rate, gas efficiency)

**Governance Dashboard**:

* Scheduled operations queue: what changes are pending, timelock remaining per op
* Guardian veto events (count, recency)
* Emergency pause/unpause history
* Parameter change frequency and drift from initial values

### Alert Thresholds

Thresholds are calibrated to catch real exploits while avoiding constant false positives. All thresholds apply to the RiskEngine (D-056) on-chain and to the off-chain monitoring stack in parallel.

| Signal                                    | Warning                       | Critical                      | Action                                                                                                                                                                           |
| ----------------------------------------- | ----------------------------- | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Share price change (15 min window)        | >150 bps                      | >200 bps                      | Investigate; critical triggers Tier 1 slow mode (exception: scheduled profit unlock windows)                                                                                     |
| Share pool price vs NAV deviation         | >50 bps sustained 5 min       | >75 bps sustained 10 min      | Critical triggers arbitrage alert + potential share pool pause                                                                                                                   |
| Oracle staleness                          | 80% of `oracleMaxStaleness`   | 100% of `oracleMaxStaleness`  | Warning notifies; critical pauses risky adapters                                                                                                                                 |
| Adapter exposure vs cap                   | 90% of `maxExposureBps`       | 100% of `maxExposureBps`      | Warning notifies curator; critical auto-throttles new allocations                                                                                                                |
| Adapter NAV discrepancy vs reference      | >20 bps sustained 15 min      | >30 bps sustained 30 min      | Investigate adapter accounting; critical triggers adapter pause                                                                                                                  |
| In-kind exit (`forceDeallocate`) usage    | >3% of exits/day              | >5% of exits/day              | Warning signals illiquidity; critical may indicate griefing                                                                                                                      |
| Hook callback from unexpected context     | --                            | Any occurrence                | Critical: possible exploit probing; triggers immediate investigation                                                                                                             |
| Executor concentration (HHI)              | Top-3 executors >60% of jobs  | Top-3 executors >75% of jobs  | Warning signals centralization risk; critical triggers executor diversity incentive. Applies to all `IExecutable` operations (D-061).                                            |
| Job execution latency (p95)               | >3x target frequency          | >5x target frequency          | Warning signals insufficient executor competition; critical means Dutch auction escalation is reaching high reward levels consistently. See Section 10.1b escalation monitoring. |
| Reward escalation frequency               | >30% of jobs reach escalation | >50% of jobs reach escalation | Base reward may be too low; recalibrate `baseRewardBps`. D-061.                                                                                                                  |
| Governance: scheduled adapter/hook change | Any occurrence                | --                            | Always notify all depositor agents via MCP event stream                                                                                                                          |

### Adapter Conservation Invariants

Every strategy adapter in the adapter registry (D-019) must satisfy the following invariants, verified through property-based testing and differential testing against a reference "hold adapter" implementation.

**Mandatory invariants**:

1. **`totalAssets` monotonicity**: `totalAssets()` must not decrease except through realized losses attributable to observable market moves. Unexplained `totalAssets` decreases trigger an immediate adapter pause via the RiskEngine.
2. **Balance conservation**: For every adapter lifecycle, `assetsIn == assetsOut + unrealizedPnL + fees`. The sum of all assets deposited into an adapter minus all assets withdrawn must equal the adapter's current position value plus accumulated fees. Tested via differential comparison against a "hold adapter" that simply holds assets without deploying them.
3. **In-kind exit safety**: A `forceDeallocate()` call must not increase the vault's share price. The penalty mechanism (default 50-200 bps per D-019) compensates remaining depositors but must not create a share price pump exploitable by coordinated force-exit/deposit cycles.
4. **Data attestation**: All `allocate()` and `deallocate()` calls pass through the adapter registry's data attestation check (D-060). Only calldata matching a pre-registered `dataHash` (committed by the Curator with timelock) is accepted. Arbitrary `data` blobs are rejected.

**Testing requirements**:

* **Property-based (always on)**: Foundry invariant tests asserting all four invariants across randomized deposit/withdraw/force-exit sequences
* **Differential**: Every adapter tested against a hold-adapter reference implementation with identical deposit/withdraw sequences; final `totalAssets` difference must be explainable by strategy returns
* **Stress simulation**: 90% withdrawal in a congested block window measuring: (i) fraction of exits satisfied, (ii) penalty paid, (iii) slippage, (iv) time-to-exit distribution
* **Adversarial**: Sandwiching around in-kind exits with per-block volume limits and TWAP-based valuation

### Tiered Circuit Breakers (ERC-7265, Adaptive, Continuous Dampening) (D-043)

> **Research basis**: "Systemic Risk in DeFi: A Network-Based Fragility Analysis" (arXiv:2601.08540, Jan 2026) — DeFi Correlation Fragility Indicator (CFI); "Circuit Breakers and Market Runs" (Bongaerts, De Luca, Van Achter; Review of Finance, 28(6), 2024) — magnet effect and randomized halts; ASRI framework (arXiv:2602.03874, Jan 2026) — aggregate systemic risk index; "The Dark Side of Circuit Breakers" (Chen, Petukhov, Wang, Xing; Journal of Finance, 79(2), 2024) — magnet effect volatility escalation; "When Do Circuit Breakers Stabilize Markets?" (Hu & Ming; Annals of Economics and Finance, 26(2), 2025) — regime-dependent amplification; "Stablecoin Runs and the Centralization of Arbitrage" (Ma, Zeng, Zhang; NBER Working Paper 33882, May 2025) — withdrawal dampening reduces strategic complementarity.

Circuit breakers follow the ERC-7265 rate-limited token outflow pattern (which would have prevented the $195M Euler Finance exploit) with three escalation tiers. **Thresholds are adaptive**, scaling with the DeFi Correlation Fragility Indicator (CFI) and incorporating randomized trigger bands to prevent the "magnet effect" where sophisticated agents front-run anticipated halts.

**Fundamental Rule: Circuit breakers MUST use continuous dampening curves. Binary halt/resume cliffs are prohibited (D-043).**

Three traditional finance papers provide overwhelming evidence for this rule:

* Chen et al. (Journal of Finance, 2024): As price approaches a circuit breaker threshold, **volatility rises drastically, returns exhibit increasing negative skewness, and trading spikes**. This magnet effect is worse near known thresholds.
* Bongaerts et al. (Review of Finance, 2024): Too-tight breakers can **create** rather than mitigate runs — improperly calibrated binary halts limit losses from upfront trading and paradoxically incentivize more of it. **DeFi circuit breakers should never impose hard binary halts.**
* Hu & Ming (2025): Under mild shocks, circuit breakers dampen volatility effectively; under **severe crises, they amplify fluctuations**. This motivates regime-aware breaker shapes that change behavior under stress.

Ma et al. (NBER, 2025) provide the strongest academic justification for withdrawal dampening in DeFi vaults: concentrated arbitrage improves secondary price stability but **amplifies run risks**, and rate-limiting redemptions reduces strategic complementarity in exit decisions.

**Adaptive Thresholds** (CFI-Driven):

The CFI measures cross-protocol correlation concentration. When DeFi protocols move in lockstep, the same drawdown is far more dangerous. Thresholds tighten during high-CFI periods:

| Tier                    | Low CFI (normal) | Medium CFI      | High CFI (systemic stress) |
| ----------------------- | ---------------- | --------------- | -------------------------- |
| **Tier 1: Slow Mode**   | 5% drawdown/1h   | 3% drawdown/1h  | 2% drawdown/1h             |
| **Tier 2: Agent Pause** | 8% drawdown/1h   | 5% drawdown/1h  | 3% drawdown/1h             |
| **Tier 3: Full Pause**  | 15% drawdown/1h  | 10% drawdown/1h | 7% drawdown/1h             |

CFI is read from an oracle (updated hourly) or computed from on-chain TVL correlation data across major DeFi protocols.

**Randomized Trigger Bands** (Anti-Magnet Effect):

Instead of triggering at exactly N%, the breaker fires randomly within **\[N-0.5%, N+0.5%]**. The randomization seed is `keccak256(blockhash, vaultAddress)`, making it unpredictable per-vault per-block. Agents cannot predict the exact trigger point, removing the front-running incentive. The Chen et al. magnet effect finding makes this randomization essential — without it, sophisticated agents accelerate trading as drawdown approaches known thresholds.

**Withdrawal Velocity Dampening** (Smooth Degradation — Mandatory):

Instead of a hard halt/resume cliff, implement exponential dampening of the maximum withdrawal rate as drawdown approaches the threshold: `maxWithdrawalRate = baseRate × e^(-α × (drawdown / threshold))`. This provides smooth degradation rather than a cliff that agents can game.

**Regime-Aware Breaker Shape** (Hu & Ming): The dampening curve `α` parameter itself adapts to market regime:

* **Normal regime** (low CFI): `α = 3.0` — gentle dampening, minimal friction
* **Stress regime** (medium CFI): `α = 5.0` — steeper dampening as conditions deteriorate
* **Crisis regime** (high CFI): `α = 8.0` — aggressive dampening but never a binary halt

This ensures the breaker shape changes under severe stress rather than applying uniform curves that Hu & Ming show amplify fluctuations in crisis conditions.

**Tier Actions**:

| Tier                    | Action                                                                          | Depositor Impact                     | Detection Time                       |
| ----------------------- | ------------------------------------------------------------------------------- | ------------------------------------ | ------------------------------------ |
| **Tier 1: Slow Mode**   | Reduce rate limits, cap individual withdrawal size, throttle strategy execution | Delayed but still possible           | 30-60 seconds (off-chain monitoring) |
| **Tier 2: Agent Pause** | Disable all agent operations. Manual withdrawals still enabled.                 | Withdrawals enabled for idle capital | 30-60 seconds (off-chain) + on-chain |
| **Tier 3: Full Pause**  | Pause all deposits AND strategy execution. Force-unwind if exploit confirmed.   | Pro-rata claims on remaining assets  | Immediate on-chain circuit breaker   |

**Off-chain monitoring** (30-60 second detection) complements on-chain circuit breakers (10+ minutes for manual detection). The monitoring stack (Forta + OpenZeppelin Monitor) detects anomalies and triggers Tier 1/2 via the Sentinel role before on-chain conditions fully deteriorate.

At every stage, depositors retain the ability to sell vault shares on the auto-created V4 pool -- the secondary market exit path is independent of vault-level circuit breakers.

### Endgame Defection as Monitored Threat Class

> **Research basis**: "Understanding LLM Agent Behaviours via Game Theory" (arXiv:2512.07462, Dec 2025); "Multi-Agent Risks from Advanced AI" (arXiv:2502.14143, Feb 2025).

Alongside identity theft, **endgame defection** is a monitored threat class. LLM agents exhibit cooperative behavior during normal operation but shift toward value extraction before exiting — with strategy signatures classifiable at >90% confidence. Detection mechanisms (withdrawal acceleration, behavioral regime classification, decay-weighted scoring, exit bonds) are implemented in the `VaultReputationEngine` — see [06-contracts.md](/docs/gotts-vaults/vault/06-contracts.md) Section 10.19. The monitoring infrastructure includes defection-specific rules:

* **Cross-vault exit correlation**: Agent accelerates withdrawals across 3+ vaults simultaneously → elevated monitoring
* **Deposit-to-withdrawal ratio inversion**: Agent's 7-day ratio flips from net-positive to net-negative with AUM > $50K → alert
* **Tier-downgrade cascade**: Defection classification triggers automatic tier downgrade, reducing withdrawal caps — a natural brake on extraction speed

***

## Multi-Agent Isolation and Cascading Failure Protection

Galileo AI research (December 2025) demonstrated that a single compromised agent can poison **87% of downstream decision-making within 4 hours** in multi-agent systems. A real-world procurement agent compromise led to $3.2M in fraudulent orders. Lakera AI research (November 2025) documented attacks where poisoned data corrupts agent long-term memory, creating persistent false beliefs about security policies — "sleeper agent" attacks that prime agents over weeks before a trigger activates the exploit.

These findings require explicit isolation boundaries and anomaly detection for multi-agent vault operations.

### Cross-Vault Agent Isolation

An agent managing Vault A MUST NOT share session keys, memory context, or signing credentials with its role in Vault B. This prevents a compromised vault from cascading into other vaults managed by the same agent:

* **Session key scoping**: Each vault operation uses a session key scoped to that specific vault contract address (enforced by ERC-7579 AllowedTargetsHook). A session key for Vault A cannot sign transactions targeting Vault B.
* **Memory isolation**: Agent memory/context for Vault A strategy decisions is separated from Vault B. Memory from one vault cannot influence decisions in another (mitigates Lakera's cross-context memory injection).
* **Credential separation**: Each vault role uses a distinct signing key. Compromise of Vault A's hot key does not expose Vault B's credentials.

### Anomaly-Driven Escalation

When an agent's behavior deviates from its historical pattern, the system auto-escalates to more defensive execution modes:

| Anomaly                                                    | Detection Method                        | Response                                                     |
| ---------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------ |
| 10x increase in rebalance frequency                        | Rolling window comparison (7d baseline) | Auto-escalate to time-delayed proxy mode                     |
| Sudden change in adapter allocation > 30% of AUM           | Delta vs previous `report()`            | Require Owner+Curator approval (two-man rule)                |
| Withdrawal acceleration (2nd derivative positive)          | D-028 endgame defection detection       | Tier downgrade + alert to depositors                         |
| Unexpected contract interaction (target not on allowlist)  | TEE policy enforcement (Layer 3)        | Transaction rejected at signing layer                        |
| Agent attempts to modify its own policy or security config | PolicyCage bounds check                 | Rejected — policy cage boundaries are immutable to the agent |

### Periodic Policy Re-Verification

To mitigate memory injection and sleeper agent attacks, agents re-validate their security policy configuration from a trusted, immutable source at regular intervals:

* **Cadence**: Every 6 hours (configurable per vault via `policyRefreshInterval`)
* **Mechanism**: Agent re-reads its PolicyCage constraints, session key bounds, and allowlist from on-chain state (not from its own memory). Any divergence between the agent's believed policy and the on-chain policy triggers an alert and operation suspension.
* **Hash verification**: The agent's security configuration is hashed at initialization. If the hash of the current perceived configuration does not match the on-chain policy hash, the agent enters a fail-safe mode (read-only operations only, no writes) until manually re-initialized.

This prevents the attack pattern where poisoned memory gradually shifts an agent's understanding of its own security boundaries, enabling actions that the real on-chain policy would block.

***

## Vault Memory Safety (DeFi Brain)

When the `learning` profile is active alongside the `vault` profile (`TOOL_PROFILE=vault,learning`), additional memory safety constraints apply beyond the base memory safety layer ([09-safety.md § 6.16](/docs/gotts-safe-mcp-server/mcp-server/09-safety.md)).

### Vault-Specific Confidence Thresholds

Vault operations require **higher minimum confidence** for memory insights to influence execution, reflecting the higher stakes of vault management:

| Tool                        | Min Confidence | Rationale                                                                                          |
| --------------------------- | -------------- | -------------------------------------------------------------------------------------------------- |
| `vault_rebalance`           | 0.7            | Rebalancing moves significant capital; only well-validated insights should influence timing/params |
| `vault_emergency_exit`      | 0.9            | Emergency exits are irreversible; only near-certain insights qualify                               |
| `vault_deposit`             | 0.5 (default)  | Deposits are lower-risk (no capital loss); default threshold applies                               |
| `vault_collect_fees`        | 0.5 (default)  | Fee collection is routine; default threshold applies                                               |
| All other vault write tools | 0.6            | Moderate threshold for general vault operations                                                    |

These thresholds are configurable via `VAULT_MEMORY_REBALANCE_MIN_CONFIDENCE` and `VAULT_MEMORY_EMERGENCY_MIN_CONFIDENCE`.

### Memory Bounded by PolicyCage (D-053)

On-chain PolicyCage constraints **cannot be exceeded** regardless of memory suggestions. The memory layer operates strictly within the PolicyCage envelope:

* **Approved asset list**: Memory cannot suggest allocation to assets not on the vault's approved list
* **Max position sizes**: Memory-suggested position sizing is bounded by `maxSingleAssetBps` and `maxAdapterExposureBps`
* **Strategy whitelists**: Memory cannot recommend strategies outside the vault's whitelisted strategy adapters
* **Max drawdown tolerance**: Memory cannot relax drawdown monitoring thresholds
* **Rebalance frequency limits**: Memory-suggested rebalance timing is bounded by `minRebalanceInterval`

### Emergency Memory Persistence

Emergency exits, circuit breaker activations, and exploit-related events receive maximum stability in the memory system:

| Event Type                 | Stability (half-life) | Pruning        |
| -------------------------- | --------------------- | -------------- |
| Emergency exit             | 180+ days             | Never pruned   |
| Circuit breaker activation | 180+ days             | Never pruned   |
| Oracle failure / staleness | 90 days               | Standard decay |
| Significant loss (>5% NAV) | 90 days               | Standard decay |
| Routine operations         | 7-14 days (default)   | Standard decay |

These serve as permanent safety knowledge — the system never forgets catastrophic events.

### Cross-Vault Memory Isolation

Per the multi-agent isolation requirements (above), memory context for Vault A strategy decisions is separated from Vault B. However, **anonymized, aggregate insights** may be shared across vaults of the same type when both are managed by the same agent and both are at Trusted tier or above. For example, a general insight like "VPIN > 0.7 correlates with 2-3x higher rebalance slippage on Base" may be shared, but vault-specific performance data, position sizes, and strategy parameters remain isolated.

***

## V4 Hook Security Requirements

Uniswap V4 launched January 30, 2025, across 10+ chains with 2,500+ hook-enabled pools and $1B+ TVL by mid-2025. The hook ecosystem has already suffered two major exploits that directly inform the Gotts Vaults VaultHook design:

* **Cork Protocol lost $11M** (May 2025) because hook callback functions lacked `onlyPoolManager` access control -- attackers called hook functions directly without routing through PoolManager.
* **Bunni v2 lost \~$8.4M** across Ethereum and Unichain due to precision/rounding bugs in custom LDF rebalancing math.
* A **BlockSec study** found 36% of community hooks in the awesome-uniswap-hooks repository were potentially vulnerable.

### Five Non-Negotiable Requirements for VaultHook

Every hook contract deployed by the vault factory MUST satisfy all five:

1. **Inherit from `BaseHook`** (v4-periphery) or OpenZeppelin's equivalent. Never implement hook interfaces from scratch. BaseHook provides built-in permission validation and standardized callback signatures.
2. **Apply `onlyPoolManager` modifier on every callback function without exception.** This includes `beforeSwap`, `afterSwap`, `beforeAddLiquidity`, `afterAddLiquidity`, `beforeRemoveLiquidity`, and all other hook entry points. The Cork Protocol exploit would have been prevented by this single modifier.
3. **Validate all pool keys and currency addresses in every hook entry point.** Check that the pool key matches an expected configuration. Reject calls for unexpected pool/currency combinations to prevent cross-pool confusion attacks.
4. **Use property-based fuzzing and formal verification on all value-flow invariants.** Unit tests are insufficient -- the Bunni exploit involved precision edge cases that unit tests missed. Require:
   * Foundry invariant testing with `forge test --invariant`
   * Certora or Halmos formal verification on share accounting invariants
   * Echidna property-based fuzzing for boundary conditions
   * **Pool Favor Property (K' >= K)**: Verify that integer-arithmetic rounding in every swap always favors the pool (Tranquilli & Gupta, "Formal State-Machine Models for Uniswap v3", arXiv, Dec 2025). Their PTA and FST formalisms prove `K' >= K` for constant-product pools — this invariant must hold for all VaultHook swap paths. The FST formulation provides a formal interface specification for agent action spaces.
   * **Fee monotonicity and output-boundedness**: Verify using the Lean 4 AMM fee library (Dessalvi et al., arXiv, Jan 2026; DTU/Cagliari; 3,500 lines of machine-checked proofs) that fee introduction preserves monotonicity and output-boundedness. The library provides verified proofs that single large swaps dominate split swaps under fees — use as a verification baseline for all hook fee logic.
   * **Absence of rounding arbitrage**: Verify that no sequence of swaps can extract value through rounding alone. The formal PTA model from Tranquilli & Gupta provides UPPAAL/TLA+ templates for checking this property.
5. **Get audited by V4-specialized firms** before any mainnet deployment. Recommended: Dedaub (whitelisted by Uniswap Foundation), Cyfrin, or Trail of Bits.

### Sixth Requirement: Hook Break-Glass Kill-Switch (D-058)

In addition to the five pre-deployment requirements above, every hook deployed by the vault factory MUST implement a runtime kill-switch for emergency response.

**Rationale**: Cork Protocol's $11M loss took hours to mitigate because there was no mechanism to disable the vulnerable hook at runtime. Pre-deployment audits are necessary but insufficient — exploits may involve edge cases that audits miss (as Bunni's $8.4M loss demonstrated). A kill-switch provides seconds-to-minutes response time instead of hours.

**Specification**:

* `disableHook()`: Callable only by the Sentinel role (D-020, never delegated to an AI agent). When called, sets `hookDisabled = true` and emits `HookDisabled(caller, timestamp)`. All hook callback functions (`beforeSwap`, `afterSwap`, `beforeAddLiquidity`, etc.) check `hookDisabled` and return early (no-op) when true. The pool continues to function as a standard V4 pool without custom logic.
* `enableHook()`: Requires both Owner and Curator roles (two-man rule) and is subject to `longTimelock` (3-7 days, per D-059). Emits `HookEnabled(caller, timestamp)`. The delay ensures that re-enabling a hook after an incident cannot happen before a thorough investigation.
* **Monitoring integration**: `HookDisabled` and `HookEnabled` events are critical-priority alerts in the monitoring dashboard. All depositor agents receive immediate notification via MCP event stream when a hook is disabled.
* **Impact on depositors**: When a hook is disabled, the vault's share pool operates as a standard constant-product V4 pool. NAV-aware pricing, dynamic fees, and rehypothecation all cease. Depositors can still trade shares and withdraw, but without the custom pricing logic. This is a deliberately conservative posture — it is safer to operate without hook logic than to operate with potentially compromised hook logic.

### Identity Cache as Gas-Security Optimization

Checking ERC-8004 agent identity in `beforeSwap` hooks adds an external call per swap, increasing gas and creating a potential DoS vector if the registry is slow or congested. The VaultHook uses a **local cache bitmap** (see [06-contracts.md](/docs/gotts-vaults/vault/06-contracts.md) Section 10.3) to eliminate this overhead:

* **Hot path** (cache hit): single warm SLOAD (\~200 gas) — no external call
* **Cold path** (cache miss): live registry lookup + cache update (\~2,800 gas) — first swap only
* **Periodic refresh**: `refreshAgentCache()` is permissionless and callable every `CACHE_REFRESH_INTERVAL` blocks (\~10 min on Base)
* **Reactive invalidation**: ERC-8004 `IdentityRevoked` event listeners immediately invalidate compromised agents from cache
* **Fail-safe**: if cache refresh and event listeners both fail, the `CACHE_REFRESH_INTERVAL` ensures entries expire and force a live registry check

This eliminates the per-swap gas penalty and the registry DoS vector while maintaining identity enforcement within a bounded staleness window. The Cork Protocol exploit ($11M) demonstrated that every gas optimization in hook callbacks must be weighed against security — the cache preserves the security guarantee (all swappers are verified agents) while removing the gas penalty.

### Yield Wrapping Strategy

Two patterns exist for ERC-4626 yield wrapping in V4 hooks:

| Pattern             | Mechanism                                                                                                    | Risk                                                                    | Recommended For                                |
| ------------------- | ------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------- | ---------------------------------------------- |
| **Wrap-and-donate** | Separates principal from interest in yield-bearing tokens, donates accrued interest to pool via `beforeSwap` | Lower -- funds stay in the hook                                         | Default for all vaults                         |
| **Rehypothecation** | Routes idle out-of-range liquidity to external ERC-4626 vaults (Morpho, Aave, Seamless)                      | Higher -- funds leave the hook. Bunni's exploit funds ended up in Aave. | Opt-in, gated behind Verified+ reputation tier |

The protocol defaults to wrap-and-donate. Rehypothecation requires `rehypothecationEnabled=true` in VaultConfig and is only available to vaults created by agents with Verified tier (50+ reputation) or higher.

***

## Required Invariants (Must Pass in CI)

The following invariants are **normative acceptance criteria**. All MUST pass in CI before any merge to main. Failure of any invariant blocks deployment. See [05-local-dev.md](/docs/gotts-vaults/vault/05-local-dev.md) for the `pnpm test:invariant` command.

### ERC-4626 Vault Accounting Invariants

* Donation/inflation attack is not profitable under configured `_decimalsOffset()` (3-6): depositing 1 wei after a large donation MUST NOT mint disproportionate shares
* `previewDeposit` and `previewRedeem` are monotonic and consistent with `convertToShares` / `convertToAssets`
* Share price changes ONLY through authorized profit reporting (via `reportProfit()` or equivalent) — never via direct token transfers to the vault
* `totalAssets` uses internal bookkeeping exclusively — never raw `balanceOf` on the vault address
* Virtual shares offset is applied at construction and cannot be modified post-deployment

### Uniswap V4 Hook Invariants

* All hook callbacks reject callers that are not the PoolManager contract (`onlyPoolManager` modifier)
* `unlockCallback` follows the `SafeCallback` pattern and cannot be spoofed or called outside the unlock flow
* Hook permission bitmap matches the set of actually implemented callbacks — no phantom permissions
* Pool Favor Property: integer-arithmetic rounding in every swap always favors the pool (`K' >= K`)
* Hook break-glass kill-switch (`disableHook()`) is callable by Sentinel role and disables all custom logic within one transaction

### Oracle / NAV Invariants

* Staleness gating is tested and fails closed: if all oracle sources are stale beyond the configured threshold, vault operations pause
* NAV updates are rate-limited (`navRateClampBps` per `navSnapshotCadence`) and cannot be manipulated in a single block
* Primary/fallback oracle divergence >2% triggers auto-pause (D-021)
* TWAP observations use the configured window (4-24h) — no spot price reads for NAV calculation (D-067)

### Adapter Conservation Invariants

* `totalAssets` is monotonic modulo realized losses: no adapter operation can silently decrease total assets without an explicit loss event
* Adapter balance conservation: `assetsIn == assetsOut + unrealizedPnL` for every adapter lifecycle
* In-kind exit (`forceDeallocate()`) does not increase share price
* Adapter `allocate()` and `deallocate()` only accept pre-registered `dataHash` values (D-060)

***

## Security Audit Checklist (Template)

This checklist MUST be completed before any mainnet deployment. Reference from the Review Gate in [prd/README.md](/docs/prd-product-requirements/prd.md).

### Hook Security

* [ ] Confirm hook permission bitmap matches intended callback set
* [ ] All callbacks enforce `onlyPoolManager` call-context
* [ ] `unlockCallback` implemented via `SafeCallback` pattern
* [ ] No external call in hook without strict allowlist + reentrancy protections
* [ ] Kill-switch (`disableHook`) tested and Sentinel role correctly assigned
* [ ] Pool Favor Property verified via formal methods or exhaustive fuzzing

### ERC-4626 Vault Safety

* [ ] Virtual shares / decimals offset configured and tested (inflation attack)
* [ ] `totalAssets` accounting verified under donation and rounding edge cases
* [ ] Profit reporting cannot be sandwiched to steal value (linear unlock buffer active)
* [ ] No path where `balanceOf` is used instead of internal accounting
* [ ] a16z ERC-4626 property test suite passes (mandatory Phase 5 gate)

### Role / Policy

* [ ] Manager actions bounded by parameter envelopes (RiskEngine)
* [ ] Emergency pause path tested and documented
* [ ] Upgrade paths timelocked and cancelable (D-059 per-parameter governance table)
* [ ] Sovereign tier agents have daily aggregate cap (configurable, not infinite)

***

## Testing Checklist (Template)

### Unit Tests

* [ ] Vault accounting: `deposit` / `withdraw` / `redeem` / all `preview*` functions
* [ ] Adapter boundaries and failure modes (each adapter individually)
* [ ] Hook callback gating and permissioning
* [ ] Oracle staleness and fail-closed behavior
* [ ] Reputation tier enforcement and deposit cap limits

### Property / Invariant Tests

* [ ] No free-share minting via donations (>=10,000 runs per invariant)
* [ ] No unauthorized state changes via reentrancy
* [ ] Shares supply and asset accounting consistent across rounding
* [ ] Handler-based invariant tests per the a16z suite
* [ ] Adapter conservation invariants under random allocate/deallocate sequences

### Simulation Tests

* [ ] Multi-agent scenario: normal ops (rebalance, harvest, deposit, withdraw)
* [ ] Adversary scenario: sandwich / MEV stress
* [ ] Emergency scenario: circuit breakers and exits
* [ ] Manager-offline scenario: withdrawal queue grows, 7-day force-unwind triggers

***

## Release Checklist (Template)

### Documentation

* [ ] PRD updated + implementation docs updated
* [ ] Tool schemas versioned; changelog entry added
* [ ] Chain capabilities validated and published (see [shared/chains.md](/docs/prd-shared/chains.md))

### Security

* [ ] Audit findings addressed or risk-accepted with sign-off
* [ ] Monitoring alerts configured (NAV delta, risk flags, job failures)
* [ ] Emergency pause / runbook drill performed
* [ ] Slither static analysis: zero high/critical findings

### Operations

* [ ] Backward compatibility verified (N-1 tool versions remain for >=90 days)
* [ ] Rollback plan written (what to do if deployment fails)
* [ ] On-call rotation established for monitoring alerts

***

## v1 Monitoring Requirements (Normative)

> **OpenZeppelin Defender is sunsetting July 1, 2026.** All v1 monitoring must use open-source replacements: **OpenZeppelin Monitor** (self-hosted event detection) and **OpenZeppelin Relayer** (self-hosted key management with nonce handling). No production dependency on Defender.

### Required Monitored Events

| Event                        | Source Contract        | Threshold               | Severity     | Response Time |
| ---------------------------- | ---------------------- | ----------------------- | ------------ | ------------- |
| `CircuitBreakerTriggered`    | RiskEngine             | Any trigger             | **Critical** | < 5 minutes   |
| `HookDisabled`               | VaultHook              | Any trigger             | **Critical** | < 5 minutes   |
| `AdapterExposureBreach`      | RiskEngine             | Current > max           | **Critical** | < 5 minutes   |
| `RiskWarning`                | Any vault              | severity >= 2           | **High**     | < 15 minutes  |
| `OracleStale`                | RiskEngine             | Any feed                | **High**     | < 15 minutes  |
| `VaultPaused`                | Factory/Vault          | Any                     | **Medium**   | < 30 minutes  |
| `VaultCreated`               | Factory                | Any                     | **Info**     | < 1 hour      |
| `NAVUpdate` with large delta | NAVAwareHook           | delta > navMaxChangeBps | **High**     | < 15 minutes  |
| `TransactionCancelled`       | AgentProxy             | Any                     | **Medium**   | < 30 minutes  |
| `ParameterChanged`           | ParameterDecisionTable | Any                     | **Medium**   | < 30 minutes  |

### Alerting Chain

```
Event detected by OpenZeppelin Monitor
    |
    v
Severity routing:
    Critical -> PagerDuty (on-call) + Telegram (ops channel) + Discord (#vault-alerts)
    High     -> Telegram (ops channel) + Discord (#vault-alerts)
    Medium   -> Discord (#vault-alerts)
    Info     -> Discord (#vault-info)
```

### v1 Monitoring Stack

| Component        | Technology                                        | Purpose                                             |
| ---------------- | ------------------------------------------------- | --------------------------------------------------- |
| Event detection  | OpenZeppelin Monitor (self-hosted)                | Watch contract events against threshold rules       |
| Proxy monitoring | Custom MonitorBot (packages/agent-proxy/monitor/) | Evaluate pending proxy announcements                |
| Key management   | OpenZeppelin Relayer (self-hosted)                | Cancel authority key isolation and nonce management |
| Dashboards       | Grafana + custom metrics exporter                 | Real-time vault health visualization                |
| Alerting         | PagerDuty + Telegram + Discord webhooks           | Multi-channel severity-routed alerts                |

### Response Procedures

| Severity     | Required Response                                                                     | Escalation                                           |
| ------------ | ------------------------------------------------------------------------------------- | ---------------------------------------------------- |
| **Critical** | On-call acknowledges within 5 min; Sentinel evaluates pause/kill-switch within 15 min | Escalate to full team if unresolved in 30 min        |
| **High**     | On-call acknowledges within 15 min; investigates root cause                           | Escalate to engineering lead if unresolved in 1 hour |
| **Medium**   | Reviewed in next business-hours window                                                | No escalation unless pattern detected                |
| **Info**     | Logged for analysis; no immediate action                                              | --                                                   |

***

## Required Invariants (Normative)

The following invariants MUST hold after any sequence of valid operations. They are derived from the formal invariant properties in [17-testing.md](/docs/gotts-vaults/vault/17-testing.md) and extended to cover V4 hook-specific and upgrade-specific requirements identified by audit review. Invariant tests MUST run in CI as acceptance gates (see [17-testing.md](/docs/gotts-vaults/vault/17-testing.md) Section 5 for CI gate requirements per phase).

### ERC-4626 Invariants

| ID        | Invariant                                           | Formal Statement                                                                                                                                                                                                                                         | Test Reference                |
| --------- | --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
| INV-ERC-1 | No profitable vault inflation via donation/rounding | `deposit(1 wei)` MUST mint > 0 shares for any vault state. Virtual shares/assets offset (`_decimalsOffset`) MUST prevent first-depositor inflation attacks.                                                                                              | INV-2 in 17-testing.md        |
| INV-ERC-2 | Preview functions MUST be conservative              | `previewDeposit(assets)` MUST return <= actual shares minted. `previewWithdraw(assets)` MUST return >= actual shares burned. `previewMint(shares)` MUST return >= actual assets required. `previewRedeem(shares)` MUST return <= actual assets received. | New                           |
| INV-ERC-3 | Total assets and supply coherence                   | `totalAssets() >= sum(adapterAssets[i]) + idleCapital - accruedFees` within rounding tolerance of `_decimalsOffset`. `totalSupply() == sum(agentShares[agentId])` for all registered agents.                                                             | INV-5, INV-6 in 17-testing.md |
| INV-ERC-4 | Fee-on-transfer and rebasing token safety           | Total assets and total supply accounting MUST remain coherent under fee-on-transfer and rebasing token behavior, OR such tokens MUST be disallowed at the factory level with `UnsupportedTokenBehavior` revert.                                          | New                           |
| INV-ERC-5 | Deposit-withdraw roundtrip                          | For any deposit `d`, `withdraw(deposit(d))` returns `>= d - maxFeeImpact - roundingError`.                                                                                                                                                               | INV-7 in 17-testing.md        |

### Uniswap V4 Hook Invariants

These invariants address the risk classes identified in the Uniswap V4 hook security framework and are informed by production exploits (Cork Protocol $11M loss from missing `onlyPoolManager`, Bunni v2 \~$8.4M loss from precision/rounding bugs).

| ID         | Invariant              | Formal Statement                                                                                                                                                                                                                | Risk Class                             |
| ---------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------- |
| INV-HOOK-1 | Caller validation      | Hook callbacks (`beforeSwap`, `afterSwap`, `beforeAddLiquidity`, `afterAddLiquidity`, etc.) MUST reject any caller that is not the V4 PoolManager contract.                                                                     | Access control (Cork Protocol exploit) |
| INV-HOOK-2 | Reentrancy safety      | If a hook makes any external call during a callback, reentrancy and state drift MUST be tested with adversarial call sequences. The hook MUST use reentrancy guards or demonstrate reentrancy-safe design via review.           | External calls / reentrancy            |
| INV-HOOK-3 | Transient state safety | Any logic using PoolManager deltas or transient storage MUST be covered by scenario tests that verify correct behavior across multi-step atomic operations (swap + liquidity add in single tx).                                 | Transient state assumptions            |
| INV-HOOK-4 | Precision and rounding | All hook arithmetic MUST round in favor of the pool (Pool Favor Property). Cumulative rounding drift MUST be bounded and tested over long operation sequences (1000+ swaps).                                                    | Precision (Bunni v2 exploit)           |
| INV-HOOK-5 | Hook immutability      | Once deployed, hook logic MUST NOT be upgradeable via proxy or delegatecall unless the vault explicitly declares upgradeability and satisfies upgrade invariants below. Hook kill-switch (D-058) is the only emergency control. | Upgradeability risk                    |

### Upgrade Invariants

| ID        | Invariant                 | Formal Statement                                                                                                                                                                                                                                                                          |
| --------- | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| INV-UPG-1 | Storage layout safety     | If any contract is upgradeable, storage layout checks (`forge inspect --storage-layout` diff) and upgrade simulations MUST run in CI before any upgrade is approved.                                                                                                                      |
| INV-UPG-2 | Non-upgradeable migration | If a contract is not upgradeable (the default for vaults), a versioned redeploy + migration plan MUST exist. The migration plan MUST specify: how to deploy the new version, how to migrate user state (withdraw-and-redeposit), and how to handle in-flight operations during migration. |
| INV-UPG-3 | Factory template upgrade  | Factory `setImplementation()` MUST enforce `longTimelock` (3-7 days, D-059). Existing vaults MUST NOT be affected by template upgrades.                                                                                                                                                   |

### Observability Requirements (Normative)

Contracts MUST emit standardized events sufficient to build monitoring dashboards without proprietary services:

| Event               | Parameters                                               | Emitter        |
| ------------------- | -------------------------------------------------------- | -------------- |
| `VaultStateUpdated` | `totalAssets`, `totalSupply`, `navPerShare`, `timestamp` | AgentVaultCore |
| `RiskFlagChanged`   | `flag`, `enabled`, `timestamp`                           | RiskEngine     |
| `HookStateChanged`  | `poolId`, `enabled`, `reason`                            | VaultHook      |
| `OperationExecuted` | `opType`, `actor`, `success`, `gasUsed`                  | AgentVaultCore |

The SDK MUST expose a single "vault health" view that reports:

* Share price vs NAV delta
* Last successful rebalance/harvest time
* Active risk flags
* Oracle freshness (if applicable)
* Queue depth for async exits (if enabled)

> **References**: [17-testing.md](/docs/gotts-vaults/vault/17-testing.md) for formal invariant IDs (INV-1 through INV-14); Uniswap V4 hook security framework; OpenZeppelin ERC-4626 virtual shares offset; Cork Protocol $11M exploit post-mortem; Bunni v2 $8.4M exploit post-mortem.

***

## MEV-Aware Operations (Normative)

MEV and transaction ordering dependence are endemic in DEX execution. Vault operations that are large, predictable, or time-based (rebalance, harvest, NAV updates, hook toggles) are natural MEV targets. This section consolidates MEV protection requirements that apply across all vault operations.

### Requirements

Any action that is predictable and price-impacting MUST satisfy all of the following:

1. **Pre-trade simulation**: Run `eth_call` simulation against real-time blockchain state before broadcast. Reject if simulation shows unexpected balance changes or value leakage exceeding tolerance.
2. **Bounded slippage / minOut**: Enforce slippage bounds on every swap and liquidity operation. The SDK MUST compute and apply `minAmountOut` based on current oracle prices with configurable tolerance (default: 50 bps).
3. **Cooldown and rate limit**: Implement minimum intervals between successive operations of the same type. Default cooldowns:
   * Rebalance: 1 block minimum, 10 minutes recommended
   * Harvest/fee collection: 1 hour minimum
   * NAV snapshot update: cadence defined by `navSnapshotCadence` parameter
   * Hook enable/disable: `longTimelock` (D-059)
4. **Event emission**: Emit monitoring-suitable events for every price-impacting operation (see Observability Requirements above). Events MUST include enough data for post-hoc MEV impact analysis.

### Default Execution Path

The default execution path for vault operations is the **public mempool** (standard `eth_sendRawTransaction`). Private routing (MEV Blocker or equivalent) is RECOMMENDED for:

* Rebalance operations exceeding 1% of pool TVL
* Harvest operations where fee accrual is publicly observable
* Any operation identified as sandwich-vulnerable by the `assess_mev_risk` tool

### Existing MEV Protections

The following mechanisms already satisfy MEV-aware operation requirements for their respective scopes:

* **LaunchFeeHook** (Section 10.8 in [06-contracts.md](/docs/gotts-vaults/vault/06-contracts.md)): Descending fee curve protects the initial share pool trading window from sandwich attacks
* **TWAMM Rebalancing** (Section 10.10 in [06-contracts.md](/docs/gotts-vaults/vault/06-contracts.md)): Time-weighted execution reduces price impact for large rebalances
* **NAVAwareHook** (Section 10.7 in [06-contracts.md](/docs/gotts-vaults/vault/06-contracts.md)): Spread-based pricing anchored to NAV limits arbitrage extraction

> **References**: [19-threat-model.md](/docs/gotts-vaults/vault/19-threat-model.md) adversary type "External MEV bot"; Flash Boys 2.0 (Daian et al.); "Transparent Dishonesty" front-running survey; LVR research (Milionis et al.).

***

## Risk Parameter Taxonomy (Normative)

Risk parameters are currently distributed across contracts (RiskEngine D-056, ParameterDecisionTable D-059, PolicyCage D-053). This section defines a unified taxonomy that all vault templates MUST implement. The `ParameterDecisionTable` contract (D-059, see [06-contracts.md](/docs/gotts-vaults/vault/06-contracts.md)) is the on-chain enforcement mechanism.

### Required Parameters

Every vault template MUST define the following risk parameters at creation time:

| Category            | Parameter                      | Unit                      | Default   | Min | Max    | Who Can Change | Change Delay       |
| ------------------- | ------------------------------ | ------------------------- | --------- | --- | ------ | -------------- | ------------------ |
| **Exposure caps**   | `maxAdapterExposureBps`        | bps per adapter           | 5000      | 100 | 10000  | Creator        | `longTimelock`     |
| **Exposure caps**   | `maxSingleAssetBps`            | bps per asset             | 3000      | 100 | 10000  | Creator        | `longTimelock`     |
| **Rate limits**     | `navMaxChangeBps`              | bps per snapshot interval | 50        | 5   | 500    | Creator        | `longTimelock`     |
| **Rate limits**     | `maxStrategyWeightChangeBps`   | bps per rebalance         | 1000      | 100 | 5000   | Manager        | `standardTimelock` |
| **Cooldowns**       | `minRebalanceInterval`         | seconds                   | 600       | 1   | 86400  | Creator        | `longTimelock`     |
| **Cooldowns**       | `minHarvestInterval`           | seconds                   | 3600      | 60  | 604800 | Creator        | `longTimelock`     |
| **Emergency modes** | `circuitBreakerThresholdBps`   | bps drawdown              | 500       | 100 | 2000   | Creator        | `longTimelock`     |
| **Emergency modes** | `pauseMode`                    | enum                      | `gradual` | --  | --     | Sentinel       | immediate          |
| **Oracle**          | `oracleMaxStalenessSeconds`    | seconds                   | 3600      | 60  | 86400  | Creator        | `longTimelock`     |
| **Oracle**          | `oracleDivergenceThresholdBps` | bps                       | 200       | 50  | 1000   | Creator        | `longTimelock`     |

### Emergency Mode Levels (Normative)

Vaults MUST support three emergency modes, activated progressively:

| Mode              | Trigger                                        | Effect                                                                                | Who Can Activate                   |
| ----------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------- | ---------------------------------- |
| **Slow mode**     | Drawdown > 50% of `circuitBreakerThresholdBps` | Deposits disabled; withdrawals subject to dampening curve; rebalance frequency halved | Automatic (RiskEngine)             |
| **Partial pause** | Drawdown > `circuitBreakerThresholdBps`        | All agent operations paused except withdrawals; manager-only emergency withdraw       | Automatic (RiskEngine) or Sentinel |
| **Full pause**    | Critical exploit or oracle failure             | All operations paused including withdrawals; requires multi-sig unpause               | Sentinel only                      |

No single operation MUST transition a vault from "fully operational" to "fully halted" -- the transition MUST always be gradual through slow mode first (INV-13 in [17-testing.md](/docs/gotts-vaults/vault/17-testing.md)).

### Parameter Change Governance

Each parameter MUST specify:

1. **Authority role**: Who can propose a change (creator, manager, governance)
2. **Timelock duration**: How long the change is delayed before taking effect (see delay tiers in Layer 4 above)
3. **Valid bounds**: Min and max values (enforced on-chain by `ParameterDecisionTable`)
4. **Justification hash**: IPFS hash of rationale document (required for `longTimelock` changes, D-059)

> **References**: Aave V3 supply/borrow caps and admin-controlled risk configuration; LVR research (Milionis et al.) on risk-adjusted LP returns; ERC-7265 circuit breaker standard; `ParameterDecisionTable` (D-059) in [06-contracts.md](/docs/gotts-vaults/vault/06-contracts.md).
