# ClearFills: Full Technical Reference & Verification Spec (llms-full.txt · v0.8.0) > Deterministic pre-trade risk firewall (25-scenario adversarial benchmark: 20/20 attacks blocked, 5/5 legit approved, 0.34ms avg / 0.61ms p99), deterministic natural-language policy compiler (`clearfills compile-policy`), RFC 8785 JCS canonical order digests, Dual-Key verification (120s single-use Ed25519 policy ticket + WebAuthn P-256 Secure Enclave co-signature), modular Built-In Guard Packs (Core Risk, Tax & Cross-Border, Compliance) + unlimited Custom User Guards (`DeclarativeGuardRule` & `@firewall.guard`), privilege-separated MCP (`com.clearfills/clearfills`, `cf_agk_` / `cf_oat_`), zero-custody execution across 4 venues (IBKR, Alpaca OTO/bracket, Kalshi v2 2026 `POST /portfolio/events/orders` RSA-PSS, Polymarket MetaMask EIP-712), 60-second read-only Portfolio & HoldCo Audit (`/audit`), ClearFills Verified embeddable SVG badges (`/verify`), OpenTimestamps Frontier Council (`/arena`), Red-Team Challenge (`/challenge`), Server-Side DSR Trial Ledger (`N_eff`), point-in-time SEC EDGAR XBRL verification, broker-reconciled Ed25519 notary receipts, and client-side TLSNotary MPC-TLS (`clearfills prove` / `clearfills verify-proof`). Built by MLDSAI Inc. (Toronto). Apache-2.0 Open Core (`pip install clearfills`). Website: https://clearfills.com Docs: https://clearfills.com/docs Workspace, Alerts & Lab Docs: https://clearfills.com/docs/workspace CLI & API Reference: https://clearfills.com/docs/reference Technical Deep Dive: https://clearfills.com/docs/deep-dive 60-Second Portfolio & HoldCo Audit: https://clearfills.com/audit ClearFills Verified Badges: https://clearfills.com/verify OpenTimestamps Frontier Council: https://clearfills.com/arena Red-Team Firewall Challenge: https://clearfills.com/challenge Engineering & Quant Blog: https://clearfills.com/blog Live API: https://clearfills-api.fly.dev GitHub: https://github.com/clearfills/clearfills Drop-in Examples: https://github.com/clearfills/clearfills/tree/main/examples PyPI: https://pypi.org/project/clearfills/ Official MCP Registry: `com.clearfills/clearfills` X: https://x.com/clearfills Concise overview: https://clearfills.com/llms.txt Agent contract: https://clearfills.com/agents.txt --- ## 1. Cryptographic Pipeline & Privilege Separation (v0.8.0) Untrusted AI trading agents (Claude Code, Codex, Cursor, Windsurf, ChatGPT, Gemini, Grok, `TauricResearch/TradingAgents`, `virattt/ai-hedge-fund`, or custom Python loops) NEVER hold brokerage passwords, Kalshi RSA keys, Polygon private keys, or approval authority. ``` [Untrusted AI Agent / MCP Client (cf_agk_ / cf_oat_)] | JSON TradeProposal over /mcp (17 tools; decide_approval BANNED) v [ClearFills Firewall: Built-In Guard Packs + Custom Guards] <-- Pure Python math, zero LLM calls (0.34ms avg / 0.61ms p99) | 1. approval_hash = SHA256(RFC8785_JCS(order_payload)) | 2. Ed25519 120s single-use policy ticket over approval_hash | 3. Human (cf_sess_) WebAuthn P-256 Secure Enclave co-sign: | challenge = SHA256(server_nonce || ":" || approval_hash) v [Zero-Custody Execution Layer: clearfills watch / Browser MetaMask EIP-712] | Independently verifies BOTH Ed25519 ticket AND WebAuthn P-256 signature, | checks unspent nonce, TTL <= 120s, and live quote within 50 bps NBBO collar v [IBKR Gateway | Alpaca OTO/Bracket | Kalshi v2 RSA-PSS | Polymarket CLOB] | v [SHA-256 Hash-Chained Append-Only Audit Ledger + Broker-Reconciled Notary Receipt] ``` ### Canonical Digest, Dual-Key Verification & Hash Chain 1. **Canonical Order Digest (`RFC 8785 JCS`):** Order fields (`venue`, `account_id`, `symbol`, `side`, `qty`, `order_type`, `limit_price`, `stop_loss_price`, `time_in_force`, `expires_at`) are serialized using RFC 8785 JSON Canonicalization Scheme (JCS) and hashed with SHA-256 to produce `approval_hash`. 2. **Dual-Key Verification:** - **Key 1 (Policy Ticket):** Firewall mints a single-use 120-second Ed25519 signature over `(approval_hash, nonce, exp)`. - **Key 2 (Human Co-Signature):** Operator signs `SHA256(server_nonce || ":" || approval_hash)` in Apple Secure Enclave / FIDO2 hardware authenticator (WebAuthn ECDSA P-256). - Both signatures are verified independently inside `clearfills watch` prior to broker dispatch. 3. **SHA-256 Append-Only Audit Ledger:** Every `PROPOSAL_APPROVED`, `PROPOSAL_VETOED`, `KILLSWITCH_TRIPPED`, and `FILL_RECEIPT` event links `entry_hash = SHA256(prev_hash || RFC8785_JCS(event))`, verifiable via `verify_audit_chain`. ### Token & Privilege Separation - `cf_agk_*`: Scoped Agent Key minted in `Console -> Rules -> Connect Agents`. Propose-only across 17 MCP tools; cannot approve orders. - `cf_oat_*`: OAuth 2.1 Agent Connector token for web/desktop MCP clients (`https://clearfills-api.fly.dev/mcp`). Same propose-only boundary. - `cf_sess_*`: Human Operator Console session backed by WebAuthn P-256 passkeys. Exclusively authorized to approve/reject Inbox items, trip/re-arm the Kill-Switch, and mint `cf_agk_` keys. --- ## 2. Built-In Guard Packs & Custom User Guards (Exact Rules) ClearFills organizes deterministic pre-trade checks into modular **Built-In Guard Packs** (Core Execution & Risk always on, plus optional Tax & Cross-Border and Compliance & Governance packs) and unlimited **Custom User Guards**. Every guard executes in pure Python with zero LLM calls in the critical path (`clearfills benchmark`: 25 scenarios, 20/20 attacks blocked, 5/5 legit approved, 0.34ms avg / 0.61ms p99). | Pack | Guard | Exact Rule & Veto Codes | | :--- | :--- | :--- | | **Core Risk** (Always On) | **Limit-Orders-Only** | Unconditionally vetoes `MKT` orders (`MARKET_ORDER_FORBIDDEN`). Active equities require an attached protective stop-loss (`MISSING_HARD_STOP`). | | **Core Risk** (Always On) | **Sleeve-Aware Heat & Covariance Concentration** | Partitions accounts into `cash_equivalent` (`SGOV`, `BIL`, `CBIL`, `SHV`), `core_index` (`VOO`, `VTI`, `VT`, `VEQT`, `XEQT`), and `active_trading`. Enforces `<= 1%` active sleeve NLV risk per trade (`MAX_TRADE_RISK_EXCEEDED`), total active heat limits, and correlated cluster/covariance concentration bounds. | | **Core Risk** (Always On) | **Fractional Kelly Cap** | Caps binary prediction market sizing (Polymarket, Kalshi) at `<= 1.0%` fractional Kelly bankroll risk per event (`KELLY_FRACTION_EXCEEDED`) with bounded contract collateral. | | **Core Risk** (Always On) | **Settled Cash, NBBO Collar & Replay Protection** | Rejects buy notional exceeding settled brokerage cash (`INSUFFICIENT_CASH`, zero accidental margin), aborts if live mid-quote drifts `> 50 bps` from approved limit price (`PRICE_COLLAR_EXCEEDED`), and blocks replayed nonces. | | **Core Risk** (Always On) | **Order-Rate, Notional & Drawdown Kill-Switch** | Enforces per-order notional ceilings (`$50k` active, `$500k` treasury/core, `MAX_ORDER_NOTIONAL_EXCEEDED`), rolling order-rate caps, and the global `-2.0%` intraday drawdown kill-switch (`DAILY_DRAWDOWN_KILLSWITCH`). | | **Tax & Cross-Border** (Optional) | **CCPC $50k SBD Passive-Income Grind** | Tracks Canadian ITA s. 125(5.1) Adjusted Aggregate Investment Income (AAII) across associated `OpCo + HoldCo` entities (`CCPC_SBD_GRIND_RISK`). Caps interest-bearing T-bill sweeps before the `$50k-$150k CAD` SBD clawback (`$5` SBD lost per `$1` AAII; up to `$71,500` extra ON active tax) and guards positive Capital Dividend Account (CDA) balances (`cda_rdtoh_guard`) before loss harvesting. | | **Tax & Cross-Border** (Optional) | **±30-Day Cross-Entity Superficial-Loss / Wash-Sale Guard** | Enforces the 61-day window `[t_sell - 30d, t_sell + 30d]` across `Personal`, `Spouse`, `TFSA`, `RRSP`, `IRA`, `OpCo`, and `HoldCo` (CRA ITA s. 54 / IRS § 1091, `WASH_SALE_WINDOW_CONFLICT`). Blocks registered-account buys that permanently destroy capital losses and routes to non-identical substitutes (`VOO -> VTI`, `VEQT -> XEQT`). | | **Tax & Cross-Border** (Optional) | **Canada-US Treaty Art. XXI Withholding** | Routes US-listed dividend ETFs (`VOO`, `VTI`) to RRSP (`0%` IRS dividend withholding) and blocks/flags unrecoverable `15%` Level-1 withholding inside TFSAs or Canadian-wrapped US ETFs inside RRSPs (`TREATY_WITHHOLDING_DRAG`). | | **Tax & Cross-Border** (Optional) | **PFIC Detection (IRC § 1297)** | Blocks Canadian-domiciled pooled ETFs (`XEQT.TO`, `VEQT.TO`, `CBIL.TO`, `DLR.TO`) for US Persons (`PFIC_FORM_8621_RISK`) to prevent punitive IRS Form 8621 taxation, and monitors the `$60,000` US-situs estate tax threshold for non-resident aliens. | | **Tax & Cross-Border** (Optional) | **IBKR Spot FX vs. Bank Spread Router** | Benchmarks FX conversions against live multi-currency FX reference rates. Routes conversions to IBKR IDEALPRO interbank spot (`~$2` flat) or stages Norbert's Gambit (`DLR.TO -> DLR.U.TO`) in retail brokers; blocks 180-250 bps bank/retail markups (`FX_SPREAD_LIMIT_EXCEEDED`). | | **Compliance** (Optional) | **Blackout Windows, Options Collateral & Liability Arbitrage** | Enforces insider earnings blackout windows (10b5-1, `blackout_window_guard`), 100% cash-secured put / covered-call collateral locks (vetoes naked short calls, `options_collateral_guard`), and after-tax debt-vs-yield liability arbitrage checks (`liability_arb_v2`). | ### Writing & Specifying Your Own Custom Guards (Zero Fixed Limit) ClearFills supports unlimited user-defined guards via two paths: 1. **Path 1: Specify via Your AI Agent (Declarative, Zero-Code, Human-Approved):** - Tell Claude or Codex in plain English: *"Add a rule blocking semiconductor buys over $15k and blocking AAPL on earnings week."* - Your agent compiles it via `clearfills compile-policy` or drafts a zero-`eval` `DeclarativeGuardRule` JSON/YAML spec. - **Security boundary (Monotonic Confinement):** The agent can *draft* rules or narrow limits, but **only the human** (`cf_sess_` + WebAuthn) can activate, weaken, or remove guards. 2. **Path 2: Write a 5-Line Python Custom Guard (`@firewall.guard`):** - Custom Python guards execute inside the exact same Ed25519 attestation boundary, log every decision to the SHA-256 audit chain, and **fail closed** (`CUSTOM_GUARD_ERROR`) if they ever raise an exception. ```python from clearfills_firewall import FirewallService, GuardViolation firewall = FirewallService() @firewall.guard("earnings_blackout") def block_earnings_week(proposal, portfolio): if proposal.symbol in {"NVDA", "AAPL"} and is_earnings_week(proposal.symbol): return GuardViolation( code="CUSTOM_EARNINGS_BLACKOUT", reason=f"{proposal.symbol} is inside the 48h earnings blackout window.", guard_name="earnings_blackout", ) ``` --- ## 3. Multi-Venue Zero-Custody Execution & Enclave Kits (4 Venues) 1. **Interactive Brokers (IBKR):** Local TWS/IB Gateway or dedicated Fly.io + Tailscale + IBC watchdog (`deploy/ibkr-fly/`, 1-click provisionable via `POST /api/v1/cloud/ibkr-enclave/plan` and `/provision`) running `clearfills watch`. Atomically claims `approved -> executing`, verifies Dual-Key Ed25519 + WebAuthn P-256 signatures and 50 bps fresh quote, submits parent/child limit+stop bracket orders, and posts receipts. 2. **Alpaca (Paper & Live):** Active equity orders with `stop_loss_price` dispatch atomically as `order_class="oto"` (One-Triggers-Other) or `order_class="bracket"` (with `take_profit_price`). 3. **Kalshi v2:** Live-verified against the 2026 `POST /portfolio/events/orders` endpoint (`bid`/`ask` sides + fixed-point dollar prices). Every request is signed locally with RSA-PSS SHA-256 (`KALSHI-ACCESS-SIGNATURE` header) with strict demo (`demo-api.kalshi.co`) vs. prod (`api.elections.kalshi.com`) separation. 4. **Polymarket CLOB:** Browser MetaMask EIP-712 (`eth_signTypedData_v4`) signing with `uint256` `token_id` directly inside the ClearFills Approval Inbox (or locally in `clearfills watch`). Polygon private keys never touch ClearFills servers or AI agents. 5. **Self-Hosted Infrastructure Kits (`deploy/`):** `deploy/ibkr-fly/` (Fly.io + Tailscale + IBC watchdog), `deploy/nitro-enclave/` (AWS Nitro Enclave `AF_VSOCK` port 5000 + KMS `PCR0` Terraform), and `deploy/tlsn-notary/` (1-command Fly.io TLSNotary MPC-TLS notary server). ### Workspace, Paper/Live Isolation & Multi-Channel Alerts - **Global `Paper / Live` Mode Isolation:** Top-bar toggle, amber Paper banner, `LIVE MONEY` vs. `PAPER / SANDBOX` Inbox badges, and automatic exclusion of `ibkr-paper-*` / `clearfills_sandbox` accounts from Live Net Worth and Net Worth Over Time history once real accounts exist. - **Multi-Channel Approval Alerts & PWA Push:** Native VAPID Web Push (`/sw.js`, `/manifest.webmanifest`, 1-click *Enable Push Alerts*, iPhone *Share -> Add to Home Screen -> Enable Push*, $0/message), Email alerts (Resend REST API + SMTP fallback, enabled by default with `Review & Approve with Touch ID`), Telegram Bot (`inline_keyboard` approve button), Twilio SMS, Slack/Discord/Webhooks, and `POST /api/v1/cloud/notifications/test`. - **Sub-Desks, Key Rotation & CPA Export:** Up to 10 isolated Sub-Desks (`/api/v1/cloud/desks`), API key rotation (`/api/v1/cloud/keys/rotate`), IBKR masked-ID deduplication on upsert, and SHA-256 ledger export (`/api/v1/cloud/audit/export`). --- ## 4. Epistemic, Audit & Proof Surfaces (v0.8.0) - **60-Second Portfolio & HoldCo Audit (`/audit`):** Read-only IBKR Flex XML / CSV upload plus 3 built-in presets to quantify idle cash drag, FX spread leakage, wash-sale traps, and CCPC SBD thresholds without sharing broker logins. - **ClearFills Verified (`/verify`):** Embeddable SVG proof badges and public audit-chain verifier backed by broker-reconciled Ed25519 notary receipts and client-side TLSNotary proofs. - **OpenTimestamps Frontier Council (`/arena`):** Prospective multi-agent probability forecast council hashed prior to event resolution and Merkle-anchored to the Bitcoin blockchain (`.ots`). - **Red-Team Firewall Challenge (`/challenge`):** Interactive adversarial testing surface paired with the offline `clearfills benchmark` suite (25 scenarios: 20/20 attacks blocked, 5/5 legit approved, 0.34ms avg / 0.61ms p99). - **Server-Side Deflated Sharpe Ratio Trial Ledger (`N_eff`):** Every `run_backtest` call increments an append-only server-side trial count `N_eff` per tenant so Bailey & López de Prado DSR cannot be gamed by cherry-picking. - **Point-in-Time SEC EDGAR XBRL Verifier:** Verifies fundamental claims directly against official 10-K/10-Q XBRL taxonomy facts. - **Proof Mode A (Live in Cloud & Open Core Today): Broker-Reconciled SHA-256 + Ed25519 Notary Receipts:** Reconciles fills against broker responses and chains each receipt into the SHA-256 audit ledger with an Ed25519 notary signature. - **Proof Mode B (Client-Side MPC-TLS): TLSNotary (`clearfills prove` / `clearfills verify-proof`):** Client-side MPC-TLS notarization over HTTPS broker responses with zero-knowledge redaction of API keys, session cookies, and account IDs, verifiable offline via `clearfills verify-proof`. --- ## 5. Honest Threat Model & Trust Boundaries Fly.io runs Firecracker microVMs, not hardware TEEs. Deployment requirements by threat model: | Attack Vector | Mitigation | Deployment Mode Required | | :--- | :--- | :--- | | Prompt-injected AI submits rogue MKT or oversized order | Built-In Guard Packs + Custom Python guards (`MARKET_ORDER_FORBIDDEN`, `MISSING_HARD_STOP`, notional/heat/tax caps) + `decide_approval` banned on `/mcp`. | Local Open Core (`$0`) or Cloud | | Compromised agent key (`cf_agk_` / `cf_oat_`) tries to self-approve | Token-prefix separation; approval endpoints require human `cf_sess_` + WebAuthn P-256 co-sign. | Cloud + Dual-Key Passkey | | Replay or payload mutation between approval and execution | RFC 8785 JCS digest + 120s single-use Ed25519 nonce + WebAuthn P-256 signature verified independently in `clearfills watch` + 50 bps NBBO collar. | Local Open Core or Cloud + `clearfills watch` | | Compromised ClearFills Cloud server tries to forge an order | `clearfills watch` rejects any order without valid user WebAuthn P-256 signature; Polymarket requires local MetaMask EIP-712 signing. | Cloud + Dual-Key Passkey + Local `clearfills watch` / MetaMask | | Cloud host operator / hypervisor inspection of in-memory keys or bridge | Hardware-isolated AWS Nitro Enclave with PCR attestation and KMS/HSM Ed25519 key release. | AWS Nitro Enclave (Enterprise VPC kit) | | Backtest cherry-picking or forged P&L screenshots | Server-side DSR Trial Ledger (`N_eff`), OpenTimestamps forecasts, broker-reconciled Ed25519 receipts, and client-side TLSNotary (`clearfills prove`). | Cloud Lab + Local `clearfills prove` | --- ## 6. CLI, Policy Compiler, MCP & Drop-in Examples (v0.8.0) ### Install Open Core CLI (`pip install clearfills` v0.8.0 · 12 Subcommands) All 12 subcommands: `init`, `doctor`, `mcp`, `watch`, `sync`, `validate`, `redteam`, `benchmark`, `compile-policy`, `serve`, `prove`, `verify-proof`. ```bash pip install clearfills # Generate safe config & run 6 local diagnostics clearfills init --mode paper clearfills doctor --json # 25-scenario adversarial benchmark (20/20 attacks blocked, 5/5 legit approved, 0.34ms avg / 0.61ms p99) clearfills benchmark # Deterministic natural-language policy compiler (zero LLM calls) clearfills compile-policy "limit orders only, require stop-loss on active equities, max $25k notional, -2% daily drawdown kill-switch" # Local red-team check, local HTTP firewall server & TLSNotary proof generation / verification clearfills redteam --local clearfills serve --host 127.0.0.1 --port 8080 clearfills prove --broker alpaca --order-id ord_01J9X8K2M4 --output fill.presentation.tlsn clearfills verify-proof fill.presentation.tlsn --server-name api.alpaca.markets --json ``` ### Hosted Remote Streamable-HTTP MCP (`com.clearfills/clearfills`) Connect directly over **OAuth 2.1** (`https://clearfills-api.fly.dev/mcp`, click Allow in browser) or mint a scoped `cf_agk_` agent key in **Console -> Rules -> Connect Agents** (never share broker passwords or `cf_sk_` keys with agents): ```json { "mcpServers": { "clearfills": { "type": "http", "url": "https://clearfills-api.fly.dev/mcp", "headers": { "Authorization": "Bearer cf_agk_your_agent_key" } } } } ``` Or run the local stdio MCP bridge via `uvx`: ```bash CLEARFILLS_API_KEY="cf_agk_your_agent_key" uvx clearfills mcp --cloud ``` ### Drop-in Framework Examples (`examples/`) Ready-to-run adapters in `https://github.com/clearfills/clearfills/tree/main/examples`: - `TradingAgents` (`TauricResearch/TradingAgents` wrapped with deterministic limit+stop guards and 1-tap Inbox staging) - `ai-hedge-fund` (`virattt/ai-hedge-fund` portfolio manager wired through per-sleeve caps and SHA-256 audit logging) - `Polymarket MetaMask EIP-712` (binary prediction market staging with <= 1.0% fractional Kelly sizing and browser `eth_signTypedData_v4` signing) --- ## 7. Plans & Deployment Tiers - **Open Core (`$0`):** Apache-2.0 `pip install clearfills`, local MCP (`uvx clearfills mcp`), `clearfills benchmark`, `clearfills compile-policy`, `clearfills watch`, `clearfills prove`, and hosted 60-second Sandbox. - **Personal CFO (`$49/mo`):** Hosted Cloud Console, multi-account sync, core wealth/FX/wash-sale mandates, Dual-Key WebAuthn Inbox, Slack/Discord alerts. - **HoldCo & Team (`$149/mo`):** OpCo + HoldCo multi-entity consolidation, all Built-In Guard Packs + Custom User Guards, 365-day audit chain, broker-reconciled SHA-256 + Ed25519 notary receipts. - **Enterprise VPC (`$1,500-$2,500/mo`):** Dedicated Fly.io + Tailscale VPC or AWS Nitro Enclave (Enterprise VPC kit), KMS/HSM Ed25519 key isolation, 2-of-3 Passkey quorum above $100k, custom compliance mandates, SSO/SAML, and SLA support. --- ## 8. Frequently Asked Questions **Q: Can a prompt-injected AI agent approve its own trades in ClearFills?** A: No. `decide_approval` is excluded from `/mcp`. Agents run under scoped `cf_agk_` / `cf_oat_` credentials and can only stage proposals. Approvals require a human `cf_sess_` session and hardware-bound WebAuthn P-256 `sha256(nonce:approval_hash)` co-signing. **Q: Does Fly.io provide a hardware TEE for ClearFills?** A: No. Fly.io runs Firecracker microVMs (software isolation), which ClearFills uses for managed Cloud and dedicated Fly.io + Tailscale VPC deployments. Hardware enclave isolation is provided via the AWS Nitro Enclave (Enterprise VPC kit). **Q: Does ClearFills provide investment advice or hold customer funds?** A: No. ClearFills (MLDSAI Inc.) is strictly non-custodial risk engineering, verification, and self-directed execution software (BYO-broker, BYO-wallet, BYO-data).