Covenant Architecture Write-Up
Autonomous options trading on SPY and QQQ governed by mathematical proofs, compile-time policy validation, and cryptographically signed authority permits before any order touches Alpaca.
1. AI Logic Implementation
Natural language mandate compilation, strict authority boundaries & candidate ranking
Covenant treats AI models as untrusted analytical components operating under a strict capability fence: draft | veto | shrink | explain. Models can never activate policies, sign permits, submit orders, widen risk, or author OCC option symbols.
Traders declare mandates in unconstrained natural language. The AI Copilot (lib/ai/client.ts) drafts structured parameters, which Covenant's compiler (lib/mandates/compile.ts) transforms into typed, versioned Policy JSON. Contradictions (e.g. forced trade frequency vs. fail-closed abstention) are blocked at compile time.
Rather than letting an LLM hallucinate option legs, a deterministic factory (lib/alpha/) constructs valid vertical spreads (bull call / bear put debit & credit spreads) from live chains. Spreads are evaluated using Black-Scholes Greeks, liquidity bands, and 1,000-scenario Monte Carlo simulations to rank candidates by risk-adjusted expectancy net of slippage.
Candidate spreads are audited by secondary LLM passes (auditCandidateRisk) that evaluate macroeconomic catalysts and volatility regime shifts, while an explanation generator (explainCandidate) renders quantitative trade rationale into transparent English for the operator.
Prior to policy activation, a dedicated fuzzing engine (lib/break-me/) bombards policies with 318 generated hostile market scenarios (flash crashes, stale quotes, zero-bid anomalies, volatility spikes) to mathematically verify that invariant boundaries hold under stress.
2. Risk Gates & Mathematical Invariants
The eight runtime invariants (COV-01 – COV-08) & cryptographic authority permits
Every candidate intent must pass an isolated Safety Kernel (lib/safety/kernel.ts) that re-fetches authoritative account equity and option market data directly before evaluation.
| Invariant | Formal Name | Enforced Rule & Mechanism | Stage |
|---|---|---|---|
| COV-01 | Valid Permit Binding | Order must match an unexpired, unused Ed25519 cryptographic permit. | Permit Executor |
| COV-02 | Defined-Risk Max Loss | Max loss mathematically bounded before entry; naked options rejected at compile time. | Safety Kernel |
| COV-03 | Portfolio Heat Cap | Aggregate open dollar risk across all positions cannot exceed mandate heat limit. | Safety Kernel |
| COV-04 | Daily Halt Lockout | Breaching daily loss trips irreversible halt (ACTIVE → HALTED) cleared only on new session. | Session Monitor |
| COV-05 | Market Hygiene Bands | Enforces fresh quotes (<15s), maximum bid-ask spread width, and delta bounds (0.15–0.45). | Safety Kernel |
| COV-06 | Duplicate Cooldown | Blocks duplicate or correlated spread entries within specified cooldown intervals. | Safety Kernel |
| COV-07 | Exit Escalation Order | Initiates automated exit workflows prior to expiration deadlines to prevent assignment. | Position Monitor |
| COV-08 | Fail-Closed State | Any missing, stale, or inconsistent state deterministically triggers ABSTAIN. Never guess. | All Stages |
Approved trades receive a 60-second TTL Ed25519-signed permit (lib/permits/sign.ts) bound to exact OCC option legs, quantities, limit price bands, account equity snapshot hash, and policy hash. Single-use nonces prevent replay attacks; any alteration to order parameters invalidates the signature.
3. Alpaca Infrastructure Implementation
Physical capability isolation, paper trading enforcement & multi-leg execution
Physical Capability Isolation
ALPACA_API_SECRET_KEY is isolated strictly to lib/execution/executor.ts (order writes) and lib/alpaca/client.ts (read-only data). Strategy/alpha modules and the browser have zero access to broker keys or signing secrets, continuously verified by 27 automated capability audit checks (npm run audit).
Paper-Trading Only by Construction
Transport endpoints are hard-locked to https://paper-api.alpaca.markets and https://data.alpaca.markets. Live endpoints are not configured, not allowlisted, and structurally unreachable. Any non-paper endpoint causes immediate fail-closed termination.
Market Data & Multi-Leg Order Flow
Ingests real-time SPY/QQQ option chain snapshots, quotes, and bars via Alpaca Market Data v2. Executes atomic multi-leg vertical spreads using Alpaca’s order_class: "mleg" with exact OCC leg ratios, limit prices, and deterministic client order IDs derived from permit nonces.
Deterministic Replay & Shadow Ledger
Every quote snapshot, intent, permit, and Alpaca fill is SHA-256 hash-chained in an append-only event journal. Allows offline verification without network or credentials (npm run verify). A counterfactual Shadow Ledger tracks vetoed intents to quantify the exact dollar P&L saved or foregone by each invariant.