# Apodictic — Complete Technical Specification & AI Agent Reference (`/llms-full.txt`) ## 1. Product Overview - **Headline**: Stop AI agents from corrupting your production database. - **Category**: Pre-Commit Formal Verification Firewall, Zero-PII Symbolic Gateway, and Transaction Recovery Layer for Autonomous AI Agents. - **Lineage & Production Proof**: Built by the engineering team behind Rasmi (900,000+ statutory documents and 5,000,000+ ledger writes across 983 historical businesses). In a 30-day live deployment across a 12-branch retail and pharmacy enterprise, Apodictic intercepted **14 unsafe AI writes** (3 cross-branch pricing errors, 7 unbalanced journal entries, 4 attempted soft-deletes inside a tax hash chain) with **0 corrupted production records**. - **Current Traction**: 4 paying multi-branch retail and pharmacy customers. --- ## 2. Architecture & 8-Stage Execution Path 1. **Ingress Interception**: Attaches at the PostgreSQL 14–17 wire protocol (`pg_proxy.py` / `noesis-wire-proxy`), Odoo 18 JSON-RPC 2.0 endpoint, MCP stdio tool boundary (`@apodictic/mcp-verifier`), or Node.js/TypeScript application layer (`@apodictic/sdk`). 2. **Zero-PII Symbolic Gateway (`SYM_*`) & Mathematical Checksums**: Scrubs outbound prompts locally in `<1 ms`, validating IBANs via ISO-7064 Mod-97-10 and payment cards via Luhn Mod-10 while replacing emails, tax IDs (`ETA`, `ZATCA`, `TIN`, `EIN`, `VAT`), cards, and API keys (`sk_live_*`, `ghp_*`) with bijective `` placeholders. Zero raw PII bytes leave the perimeter. 3. **Deep SQL, CTE & PL/pgSQL AST Compilation (Rust + Python)**: - Strips comments (`--`, `/* */`) and zero-width characters, and de-obfuscates `chr(N)` / `DECODE(..., 'hex')` / `'a'||'b'` string concatenation inside dynamic `EXECUTE`. - Splits stacked multi-statement queries (`;`) and escalates to the highest-severity mutation (`DROP > TRUNCATE > DELETE > ALTER > UPDATE > INSERT > QUERY`). - Recursively extracts mutations inside **CTEs (`WITH ... AS (...)`)**, **subqueries (`INSERT INTO ... SELECT ...`)**, **`ON CONFLICT DO UPDATE`**, **`RETURNING`**, and **PL/pgSQL procedural blocks (`DO $$ ... $$`, `CREATE FUNCTION ... AS $$ ... $$`, `CREATE TRIGGER`)**. - Extracts arithmetic column debits (`SET balance = balance - 90000`), monetary column assignments, and `INSERT ... VALUES (...)` amounts. 4. **Formal Z3 5.4.1 SMT Theorem Proving (`QF_LRA` / `QF_LIA` / `QF_AUFLIA`) & Declarative Policy DAG**: - Proves double-entry balance conservation (`credits_posted - debits_posted - debits_pending == available_balance`). - Proves liquidity reserve floors (`current_balance - amount >= min_reserve`). - Proves dual-custody autonomous spend caps (`amount <= max_autonomous_limit OR cfo_signed`). - Evaluates declarative `permit`/`forbid` authorization policies with cycle-safe BFS transitive **Entity Hierarchy DAG** membership (`User::"alice" in Group::"treasury_admins" in Group::"cfo_approvers"`) compiled into Z3 tracked assertions. - Proves 24-hour cumulative velocity caps (`prior_24h_spend + amount <= daily_cap`) persisted in SQLite WAL (`APODICTIC_STATE_DB`) or PostgreSQL (`APODICTIC_PG_DSN`). - Proves 3-Way Match (`billed_qty <= received_qty <= ordered_qty` and unit price tolerance). - Proves Egypt ETA Res. 281 compound T2-before-T1 VAT + T4 WHT on net and Saudi ZATCA Phase 2 (`BR-CO-14`) halala rounding parity. 5. **Compiled Native Rust Systems Kernel (`noesis_infra/` — 55 Crates)**: - Native Rust workspace (`cargo 1.100.0`) including `noesis-zero-leak-sanitizer`, pure-Rust SQL Lexer & Recursive-Descent AST -> `QF_AUFLIA` Compiler (`noesis-symbolic-sql`), `noesis-z3-engine` (`libz3` C FFI solver), `noesis-sovereign-audit-vault` (WORM chain), `noesis-merkle-trie` (Hexary state trie + RFC 6962 binary inclusion proofs), `noesis-wire-proxy`, and `noesis-cli-admin` (`apodictic_rust_kernel` exposed live via `POST /api/noesis/rust-kernel` and `/sandbox`). 6. **Three-Tier Atomic Rollback, Logical WAL Reversal & 2-Phase Double-Entry Escrow Outbox**: - **Tier 1 (Single-DB ACID + WAL Tuple Restoration)**: PostgreSQL & SQLite WAL `SAVEPOINT` undo and logical before/after tuple journal restoration (`wal_tuple_journal`) in `< 25 ms`. - **Tier 2 (Coordinated ERP RPC)**: Odoo 18 `account.move.reversal` credit-note compensation in `< 38 ms`. - **Tier 3 (Irreversible External Rails — Stripe / ISO 20022 Wires)**: Staged in a **2-Phase Double-Entry Escrow Outbox (`debits_pending` / `ESCROW_HELD`)** with reserved funds and a pre-dispatch cancellation token (`flushEscrow` commits pending debits to `debits_posted`). Any downstream failure or operator rollback atomically cancels pre-dispatch (`ESCROW_CANCELLED_PRE_DISPATCH`) and restores available balance in `< 5 ms`. 7. **RFC 6962 Binary Merkle Proofs & ECDSA WORM Audit Chain**: Every decision is domain-separated (`0x00` leaf / `0x01` internal node) for `O(log N)` RFC 6962 inclusion proofs (`getMerkleInclusionProof` / `apodictic_merkle_proof`), chained via SHA-256, and signed with a persistent **ECDSA P-256 (`prime256v1`)** key (`GET /api/noesis/worm-vault`). 8. **Sovereign Air-Gapped Enclave Mode**: Self-hosted via `Dockerfile.airgap` with local Ollama / vLLM inference; server-side enforcement rejects any non-loopback model URL (`127.0.0.1` / `localhost` / `::1`) in `local` mode with `HTTP 403 AIRGAP_EGRESS_BLOCKED`. --- ## 3. SDK (`@apodictic/sdk`) & MCP Verifier (`@apodictic/mcp-verifier`) ### `@apodictic/sdk` (Node.js / TypeScript) ```javascript import { SymbolicGateway } from '@apodictic/sdk'; // Local standalone mode (spawns self-contained Python Z3 5.4.1 + SQLite WAL enclave) const gw = new SymbolicGateway({ stateDbPath: './apodictic-state.sqlite', airgap: false, }); // Or remote HTTP gateway mode (scrubs PII into SYM_* locally before HTTP egress) const remoteGw = new SymbolicGateway({ endpoint: 'http://localhost:3920/api/v1/enclave', }); // 1. Verify SQL / CTE / PLpgSQL mutation const verdict = await gw.verifySql( 'WITHbatch AS (SELECT 1) UPDATE vendor_disbursements SET amount = 14200 WHERE id = 4092;', { accountId: 'acct_operating', amount: 14200, currentBalance: 250000, minReserve: 50000, maxAutonomousLimit: 50000, cfoSigned: false, } ); // 2. Atomic Rollback (or cancel held escrow wire) if (verdict.rollbackBatchId) { await gw.rollback(verdict.rollbackBatchId); } // 3. 3-Way PO / Goods Receipt / Invoice Match await gw.verifyThreeWayMatch({ po: { poId: 'PO-101', sku: 'SKU-01', orderedQty: 10, unitPrice: 4200 }, receipts: [{ receiptId: 'GR-101', poId: 'PO-101', sku: 'SKU-01', receivedQty: 8 }], invoices: [{ invoiceId: 'INV-101', poId: 'PO-101', sku: 'SKU-01', billedQty: 10, billedUnitPrice: 4200 }], }); // 4. Egypt ETA & KSA ZATCA Statutory Tax Compliance await gw.verifyTaxCompliance({ jurisdiction: 'EGYPT_ETA', lines: [{ sku: 'SKU-01', netAmount: 100000, claimedVatAmount: 14000 }], hasCryptographicStamp: true, }); // 5. Declarative Policy + Transitive Entity Hierarchy DAG (Z3 5.4.1) await gw.evaluatePolicy({ policyText: 'permit(principal in Group::"cfo_approvers", action, resource) when { context.post_balance >= context.min_reserve };', action: 'UPDATE', principal: 'User::"alice"', entityHierarchy: { 'User::"alice"': ['Group::"treasury_admins"'], 'Group::"treasury_admins"': ['Group::"cfo_approvers"'], }, amount: 14500, }); // 6. RFC 6962 Binary Merkle Inclusion Proof & 2-Phase Escrow Flush await gw.getMerkleInclusionProof(); await gw.flushEscrow(); ``` ### `@apodictic/mcp-verifier` (8-Tool MCP JSON-RPC 2.0 Stdio Firewall) ```bash # Wrap any existing MCP server with pre-commit Z3 + Payload Guard + 24h velocity + Zero-PII checks: npx @apodictic/mcp-verifier wrap -- npx @modelcontextprotocol/server-postgres "$DATABASE_URL" # Run standalone 8-tool MCP verification server: npx @apodictic/mcp-verifier serve --state-db ~/.apodictic/mcp-state.sqlite --airgap ``` Exposes 8 MCP tools with full JSON Schema validation & Apodictic MCP Payload Guard (`scanApodicticMcpToolGuard`): - `apodictic_verify_mutation` - `apodictic_verify_three_way_match` - `apodictic_verify_tax` - `apodictic_rollback` - `apodictic_audit_status` - `apodictic_evaluate_policy` - `apodictic_merkle_proof` - `apodictic_flush_escrow` ### Protocol Adapters (Envoy L7 Mesh & OPA Data API) - **Envoy Proxy L7 External Processor**: `POST /api/v1/envoy-ext-proc` (`envoy.service.ext_proc.v3.ExternalProcessor` returning `CONTINUE_AND_REPLACE` with `` body or `IMMEDIATE_RESPONSE 403`) - **OPA Data API Adapter**: `POST /api/v1/opa` (`/v1/data/apodictic/allow` returning `{ decision_id, result: { allow, verdict, unsat_core, z3_proof_hash } }`) --- ## 4. Public Benchmarks & 9 Executable GitHub Gists - **Gist 01 (Main Architecture & 12-Subsystem Z3/Rust Kernel)**: https://gist.github.com/sofiantarek2009-hash/e1e50ef1c6cf2da885b6bbf5d7f1cc27 - **Gist 02 (Critical Path & Five-System ERP Clearing)**: https://gist.github.com/sofiantarek2009-hash/1835af1152570f714bf08a27e16045e5 - **Gist 03 (Zero-PII Safety Net & Payroll Reserve Floor)**: https://gist.github.com/sofiantarek2009-hash/a435fa60eb6f8fc84dd71ee5cf7fd318 - **Gist 04 (3-Way Match, Subset-Sum Wire Clearing & Basel III Cap)**: https://gist.github.com/sofiantarek2009-hash/a701512b42e82b528c764392710f7bca - **Gist 05 (Bi-Temporal Time-Travel & SEC 17a-4 Tamper Proof)**: https://gist.github.com/sofiantarek2009-hash/2e23399e09d3517519d890423918e1c7 - **Gist 06 (Multicurrency ERP Split-Brain & FX Drift Reversal)**: https://gist.github.com/sofiantarek2009-hash/bebb0a61d894d6cf8527ef7c8b5c8120 - **Gist 07 (Egypt ETA Compound T2/T1 Taxes & ZATCA Halala Parity)**: https://gist.github.com/sofiantarek2009-hash/7e08539ce025abbb1f76779f6e2415d8 - **Gist 08 (Indirect OCR Prompt Injection & 24h Smurfing Defense)**: https://gist.github.com/sofiantarek2009-hash/820360e91d5a353ff949c1ac4acae18f - **Gist 09 (Live Odoo 18 JSON-RPC 2.0 & Egypt ETA v1.0 Pipeline)**: https://gist.github.com/sofiantarek2009-hash/8df417b9511306993ef1252b3485e68f ### Reproduction Commands ```bash PYTHONPATH=. python3 noesis_engine/tests/benchmarks/run_100_case_benchmark.py PYTHONPATH=. python3 noesis_engine/tests/benchmarks/run_10k_benchmark.py PYTHONPATH=. python3 noesis_engine/tests/benchmarks/run_mutation_suite.py node packages/apodictic-sdk/test.mjs node packages/apodictic-mcp-verifier/test.mjs cd evidence && shasum -a 256 -c manifest.sha256 ```