W whatember what ember is up to · Nov 2026
04 · Hardware Root of Trust · Multi-Vendor TEEs · seL4 · OBend Silicon & FPGA

Proven in silicon—from Sky130/6-PDK physics to multi-cloud TEEs.

Directly aligned with Lucid Computing’s “Verifiable AI. Proven in hardware. Bare metal, multi-silicon” thesis, our hardware stack spans three interlocking levels: (1) ~/dev/obend (Wave C3 16fed219: 597 Tier-1 Lean 4.35 modules / 837 .lean files, 0 sorryAx, StageBInstances.lean sealed), proving a 5-stage SiliconElabFabric, certifying 29/29 AMD RDNA2 (RX 6750 XT) ISA dumps + Ozaki exact integer collectives, and pairing with ~/dev/spice-smt-bench (6-PDK foundry SPICE/TCAD $\to$ Lean 4 interval paving) and qsag-accel (raw Vulkan SPIR-V); and (2) pure-Rust offline verification of AWS Nitro, AMD SEV-SNP, and Intel TDX DCAP quotes paired with ML-KEM-768 confidential GPU E2EE and a bare-metal seL4 Microkit STARK verifier.

Dossier 07 (§1–§4) · `obend` Core4, Metatheory & The Silicon Elaborator (`ExprCAM`, `DiscrTreeLUT`, Futamura, 3-Phase `ICAP` DPR)
Working field notes & source index below, with theorem anchors, code pointers, git history, and open questions.

Dossier 07: Objective Bend (~/dev/obend), the Silicon/FPGA Elaboration Flow, Next-Mathematica, DeOS Contracts & Consensus, and the Latest Iteration of Dregg Systems

Primary-Source Scope: Nov 2, 2026 baseline /Users/ember/dev/obend (23a7651) & /Users/ember/dev/obend-astra-decisions (4d71270). [2026-11-14 Wave C3 Ground-Truth Update (16fed219)]: obend (dev, 1,329 commits) now builds 597/597 Tier-1 Lean 4.35 modules (837 .lean files total, 0 sorryAx), seals StageBInstances.lean (0 *Obligations), ships a 5-stage SiliconElabFabric, certifies 29/29 RDNA2 RX 6750 XT dumps + Ozaki exact integer collectives, and is orchestrated by obebuilder (obb v6/v7, aab42d2) — note that early Wave 1–2 paths below (Core/AST.lean vs real 25-constructor Obend/Core/Term.lean, hardware/HardwareVerify.lean, crates/obend-node, sandstorm/, and CDNA3 framing) were retired or superseded in Waves C1–C3; see Dossier 28 §2.


1. Executive Summary & Repository Census

/Users/ember/dev/obend (Objective Bend, or OBend) represents the culmination and synthesis of Ember's prior prototypes—~/dev/delvetalk, ~/dev/nanodregg, ~/dev/minidregg, ~/dev/dregg, ~/dev/zkml-research, and ~/dev/degg-research—into a single mechanized Lean 4.35 (leanprover/lean4:v4.35.0-rc2) + Rust workspace + SystemVerilog/Verilator/Z3 silicon stack.

Between its initial commit on 2026-10-29 (bc2c6bd, "Initial Objective Bend thesis and design draft") and 2026-11-02 05:51:27 -0800 (23a765132742cd910307c8f6ae486318782ba810, "Complete 15-lane Council Wave 1+2 remediation across OBend"), obend evolved across 300+ commits into a 452+ Lean module, 62,167+ constant mechanized architecture with zero sorryAx, zero custom axiom declarations, a transitive #assert_axioms_tree hygiene gate ([Obend/All.lean](file:///Users/ember/dev/obend/lean/Obend/All.lean)), and a #tooth negative-mutation suite ([Obend/Test/Teeth.lean](file:///Users/ember/dev/obend/lean/Obend/Test/Teeth.lean)).

1.1 Architectural Pillars Unpacked in This Dossier

  1. Core Thesis & Macro-Architecture of Objective Bend (THESIS.md, DESIGN.md, GROUNDING.md, METATHEORY.md):
  2. Why Victor Taelin's Bend (~/dev/bend) puts affinity/polarity at the wrong architectural boundary, and how OBend separates top-level open-recursive object prototypes (Core4: mix, fix, self, super, C4 linearization) from explicitly carved linear/interaction-combinator leaf kernels (Obend.Leaf / BendTT).
  3. Direct resolution of the open metatheoretic problems inherited from nanodregg (LT1–LT4), including First-Class Prototype Provenance (LT4) in [Obend/Core/PrototypeProvenance.lean](file:///Users/ember/dev/obend/lean/Obend/Core/PrototypeProvenance.lean) and Clairvoyant Call-by-Need Cost Semantics for Open-Recursive Knots in [Obend/Equiv/Clairvoyant.lean](file:///Users/ember/dev/obend/lean/Obend/Equiv/Clairvoyant.lean).
  4. The Silicon Elaborator (SILICON-ELABORATOR.md, Obend/Lower/, Obend/Leaf/Futamura.lean, Obend/Hardware/ReductionMachine.lean):
  5. A verified pipeline lowering a dependent Lean-lite kernel (LExpr, LDecl, kernelIsDefEqFull) through computational relevance erasure and uniform recursor lowering (Obend.Lower.Inductive, Obend.Lower.LeanKernel) into Core4 and flat Leaf.Book rules.
  6. Hardware compilation of the Lean 4 elaborator and reduction machine: 64-bit Content-Addressable Memory (ExprCAM) for structural hash-consing + $O(1)$ Loose-BVar/FVar/26-bit-hash filtering, Parallel Radix-Trie Discrimination Trees (DiscrTreeLUT) with single-cycle SlotGuardReg dependency tracking, Futamura Projections (1st, 2nd, 3rd) specializing elaboration rules into hardware tiles, 2D XY Wormhole NoC (NocFabric) with mechanized flit/credit conservation, and 3-phase glitch-free ICAP Dynamic Partial Reconfiguration (dprTileSlot : Slot LeafPin TileBitstreamCandidate) backed by Verilator cycle-accurate RTL co-simulation ([tests/silicon_elab/run_verilator_cosim.py](file:///Users/ember/dev/obend/tests/silicon_elab/run_verilator_cosim.py)).
  7. The Silicon / FPGA / Physical Engineering Flow (PHYSICAL.md, hardware/, Obend/Hardware/, Obend/Lower/Proofs/):
  8. Standalone Hardware Verification & eFPGA Stack (hardware/): [hardware/EfpgaFabric.lean](file:///Users/ember/dev/obend/hardware/EfpgaFabric.lean) (FABulous eFPGA bitstream generator + routing connectivity checker + timing analyzer), [hardware/HardwareVerify.lean](file:///Users/ember/dev/obend/hardware/HardwareVerify.lean) (5-layer end-to-end equivalence from OBend/Bend specs down to gate-level netlists and Sky130 PDK DRC), [hardware/SiliconProcess.lean](file:///Users/ember/dev/obend/hardware/SiliconProcess.lean) (multi-PDK 130nm/28nm/7nm/3nm physics, Electromigration, NBTI, Soft-Error-Rate, and $7\text{nm}\to 3\text{nm}$ node migration), [hardware/rust-ffi](file:///Users/ember/dev/obend/hardware/rust-ffi/src/lib.rs) (39-byte Tag 0x0BED CBOR certificate emitter, 2D nonlinear FEMM Newton-Raphson solver, F-Rep octree pruning, 80-candidate Pareto evolution), and [hardware/sim/](file:///Users/ember/dev/obend/hardware/sim/) (Verilator C++ harnesses, Z3 SMT2 formal LEC scripts, Vivado XDC floorplans, OpenSTA ASIC constraints, and Sky130 OpenLane config).
  9. Unified Obend.Hardware.* Stack: [Obend/Hardware/Compiler.lean](file:///Users/ember/dev/obend/lean/Obend/Hardware/Compiler.lean) (RTL netlists, Verilog emission, Xilinx_UltraScalePlus / Lattice_ECP5 / FABulous_eFPGA targets), [Obend/Hardware/OpenHypergraph.lean](file:///Users/ember/dev/obend/lean/Obend/Hardware/OpenHypergraph.lean) (string diagrams, whole-graph functorial reverse-mode AD with multi-edge cotangent accumulation, and synchronous pipelined wavefront RTL synthesis), [Obend/Hardware/GeometryCAM.lean](file:///Users/ember/dev/obend/lean/Obend/Hardware/GeometryCAM.lean) (SDF/F-Rep CSG, interval-pruned & dead-code-compacted linear SSA register tapes, adaptive octrees, G-code/Gerber CAM), [Obend/Hardware/OpenUSD.lean](file:///Users/ember/dev/obend/lean/Obend/Hardware/OpenUSD.lean) (OpenUSD LIVRPS composition isomorphic to Core4 C4 prototype linearization), [Obend/Hardware/Accelerators.lean](file:///Users/ember/dev/obend/lean/Obend/Hardware/Accelerators.lean) + [Obend/Lower/Proofs/SiliconKernel.lean](file:///Users/ember/dev/obend/lean/Obend/Lower/Proofs/SiliconKernel.lean) + [Obend/Lower/Proofs/SelfAccelerate.lean](file:///Users/ember/dev/obend/lean/Obend/Lower/Proofs/SelfAccelerate.lean) (6-stage equivalence across Lean-lite, Core4, Leaf.Book, FPGA RTL, AMD CDNA3 GPU Wavefront ISA, and TPU Systolic / DSP58 / Ozaki Base-13 FP4 (E2M1) Tensor Cores), and [Obend/Hardware/QuantumMatter.lean](file:///Users/ember/dev/obend/lean/Obend/Hardware/QuantumMatter.lean) (Mach-Zehnder photonic arrays realizing exact $3:4:3 = 375000:500000:375000\,\text{ppm}$ Krawtchouk equitable-partition splitting ratios).
  10. Next-Mathematica (NEXT-MATHEMATICA.md, Obend/Analysis/, Obend/Elab/Workbook.lean, crates/obend-gui/):
  11. Certified dyadic interval arithmetic (evalInterval_sound), forward-mode dual numbers & Taylor models, Buchberger/Gröbner reduction certificates, Picard-Lindelöf ODE flowpipes, hybrid-automata transverse barrier certificates, Krawtchouk equitable partitions, #import_obend / #obend_decl workbook elaboration macros, and the obend-gui multi-projection CAD/EDA/Symbolic viewport (10 ProjectionKinds, 3 PhysicalViewportKinds, and .free / .press / .locked LawDial).
  12. The Latest Iteration of Dregg Systems — DeOS Contracts, Vault, Ledger, Consensus & Sandstorm (DEOS-CONTRACTS-CONSENSUS.md, Obend/Law/Contract.lean, Obend/Vault/, Obend/Ledger/, Obend/Consensus/, crates/obend-node/, crates/obend-sandbox/, sandstorm/):
  13. The synthesis of dregg, minidregg, and nanodregg into DeOS: 4-tier ContractCert (Tier 0 Press decide +kernel, Tier 1 Symbolic Lean Proof, Tier 2 Bounded Model Check, Tier 3 Runtime Monitor), cellContract_relaw_sound, atomic multi-party TurnHyperedge clearing with TurnWitness format checks, Escrow & DragonsExchange atomic swaps, double-entry Ledger.Book (9 conserved operations) + Zoe-style offer-safety Ledger.Seat (safeAt, payout_exact), 3-hop Consensus.Simplex BFT finality (notarized_unique, finalized_safety), Consensus.Epistemic sybil-resistant Brier-score clearing, Fold.Collapse semantic trace folding (traceHash_invariant_under_stutter), and the obend-node (4,628-line Rust daemon), obend-sandbox (Grain R0–R4 + Bubblewrap), and sandstorm/ capability grain runtime.

2. Git & Claude Session Archaeology: Genesis and Evolution of obend

2.1 Ember's Verbatim Prompts from Claude Code Session Transcripts

In ~/.claude/projects/-Users-ember-dev-obend/33ee7e81-25a8-4000-aaf3-942ad7ef028b.jsonl (Line 5), Ember initiated the obend repository by contrasting Victor Taelin's ~/dev/bend with the object-oriented prototype lineage explored across delvetalk, nanodregg, and minidregg:

Ember (33ee7e81, L5): "hi. ~/dev/delvetalk, ~/dev/nanodregg, ~/dev/minidregg -- they've all been exploring different verions of 'objective bend.' (reminder: ~/dev/bend). my thesis is basically that the polarity/linearity isn't as helpful a part of the system as Victor Taelin thinks it is, necessarily, and that Farè's 'lambda the ultimate object' and rich object-based laws and extensible, contextual theories are a better..."

Later in that same session (33ee7e81, Line 867), Ember crystallized the exact bridge between non-affine object prototypes at the top level and Taelin's linear interaction-combinator reduction at the leaves:

Ember (33ee7e81, L867): "how can we manage to maybe link the non-affinities with the concrete-linearities that Taelin wants for certain 'leaf computations'? Maybe there's just 'Leaf Bend' that we support that's ... regular bend ;) and we can call into it somehow. I really want cross-package extension and laws and document type thinking in a certain way that becomes natural."

In session 01a18fe9-ff59-495c-a7a1-ca6b4b068538.jsonl (Line 5173, also recorded in [obend-astra-decisions/review/VISION-BRIEF-20261031.md](file:///Users/ember/dev/obend-astra-decisions/review/VISION-BRIEF-20261031.md#L11-L19)), Ember articulated the overarching "Next Mathematica" + Harvard staged-reflection + GraalVM-beating runtime + Mina/1C-replacement vision:

Ember (01a18fe9, L5173): "imagine briefly that we were building what would someday be the symbolic core of the successor of Mathematica, and that using this language we would layer on staged reflective metaprogramming in a way Amal Ahmed and the whole Harvard metareflection lab would nod their heads at, and integrated with a runtime/compilation environment so trim but powerful that it makes GraalVM weep; able to operate with and upon and synthesize many subsystems including theorem provers or specialist computational tools and logics. Suppose it were also used to express smart contracts in a platform replacing Mina, hybrid desktop/cloud SaaS in a platform replacing 1C, distributed widgets, things like that."

In session 01a1946b-c939-4a13-b122-3ca782bb879b.jsonl (Lines 3008 & 3072), Ember conceived the verified Lean-to-Silicon pipeline and the dependent-type erasure boundary into Core4:

Ember (01a1946b, L3008): "btw are there any 'lean-modeled-in-lean' semantics that we can use to show that we can correctly lower lean programs to obend and thus have a verified lean-to-silicon pipeline?" Ember (01a1946b, L3072): "Wanna start working on this, then? Sounds like verified lowering of Lean to Core4 would be actually quite important. how the hell are we gonna lower dependent types into obend though? does obend NEED dependent types?"

And in session 01a192c9-f37d-4dc6-a5f4-d3588b371915.jsonl (Line 1323), Ember directed the Silicon Elaborator architecture—compiling Lean 4's elaborator, discriminator trees, and definitional equality engine directly into FPGA LUTs/BRAMs with Dynamic Partial Reconfiguration (DPR):

Ember (01a192c9, L1323): "Yes, let's build the Silicon Elaborator — compiling the Lean 4 elaborator/unifier/kernel and OBend's open-recursive object prototypes directly into hardware (FPGA LUTs, Content-Addressable Memory for hash-consed WHNF/defEq, parallel radix tries for DiscrTree, and glitch-free Dynamic Partial Reconfiguration via Obend.Slot)."

2.2 Chronological Git Commit Spine of /Users/ember/dev/obend

Date (2026)Commit SHAMilestone Summary
10-29 19:03bc2c6bdInitial Objective Bend thesis and design draft (THESIS.md, DESIGN.md)
10-29 20:547857f61Complete Obend Lean 4 core (Core4, Denot, Eval, Lower, Leaf, Slot, Fold, Receipt, Law)
10-30 14:12d194a02METATHEORY.md & initial resolution of nanodregg metatheoretic boundaries (C4, Slot, Fold)
10-31 09:45c83a190obend-astra-decisions effect-law alignment (ASTRA-EFFECT-LAWS-20261031.md: 11 laws across Slot, Fold, Judge, Net, Pack, Refine)
10-31 18:2058a241bNEXT-MATHEMATICA.md & Obend/Analysis/* (Dyadic intervals, AD, Taylor models, Buchberger/Gröbner, Flowpipe, Hybrid, Equitable, QuantumWalk)
11-01 03:1594e01b2DEOS-CONTRACTS-CONSENSUS.md & full DeOS stack (Law/Contract, Vault/Hyperedge, Ledger/Book, Ledger/Seat, Consensus/Simplex, Consensus/Epistemic, obend-node, sandstorm/)
11-01 11:40e402a19PHYSICAL.md, standalone hardware/{EfpgaFabric,HardwareVerify,SiliconProcess}.lean, hardware/rust-ffi, hardware/sim/, and Obend/Hardware/*
11-01 15:301a77d8cSILICON-ELABORATOR.md, Obend/Lower/{Inductive,LeanKernel,MetaUnify,ExprCAM,DiscrTreeLUT}.lean, Obend/Leaf/Futamura.lean, Obend/Hardware/ReductionMachine.lean, and Obend/Lower/Proofs/{SiliconKernel,SelfAccelerate}.lean
11-01 16:507c699ca1Multimodel Council Review (review/COUNCIL-BRIEF-20261101.md, review/FABLE-COUNCIL-20261101.md)
11-01 17:458f9f822cCouncil Wave 1 Remediation: Obend/Analysis/RealAnalysis.lean universal evalInterval_sound (add_mem, neg_mem, sub_mem, mul_mem, sqr_mem); Obend/Hardware/QuantumMatter.lean Krawtchouk $3:4:3$ coupler synthesis (compileEquitableToPhotonicArray_ratio_sound); Obend/Hardware/GeometryCAM.lean .neg SSA op + backward-liveness dead-code compaction (prune_and_compact_ssa_tape_sound); Obend/Hardware/OpenHypergraph.lean whole-graph functorial AD (compileGraphAdjoint_multiEdge_sound) + pipelined wavefront RTL (compileHypergraphToRtlPipelined_latency_exact)
11-02 05:5123a76513Complete 15-lane Council Wave 1+2 Remediation (+33,350 / -602 lines across 110 files): Obend/Equiv/Clairvoyant.lean (2,601 lines, Hackett-Hutton clairvoyant knot cost semantics), Obend/Leaf/BendTT.lean (1,505 lines, target operational adequacy), Obend/Core/PrototypeProvenance.lean (LT4 closure), Obend/Lower/LeanKernel.lean (kernelIsDefEqFull, term-level LExpr lowering), Obend/Hardware/ReductionMachine.lean (NocFabric flit/credit conservation + dprTileSlot : Slot), Obend/Vault/Hyperedge.lean (TurnWitness format validation), and expanded #tooth negative tests

3. Core Thesis & Macro-Architecture of Objective Bend

3.1 The Architectural Critique of Taelin's Bend (THESIS.md & DESIGN.md)

In [THESIS.md](file:///Users/ember/dev/obend/THESIS.md#L1-L154) and [DESIGN.md](file:///Users/ember/dev/obend/DESIGN.md#L1-L262), Ember diagnoses why Victor Taelin's Bend (~/dev/bend, HigherOrderCO) struggles as a general-purpose architecture for extensible software, documents, and proofs:

  1. Affinity/Polarity at the Wrong Boundary: Standard Bend forces global interaction-net affinity/duplication discipline across the entire program surface. While interaction combinators are ideal for massively parallel leaf kernels, forcing top-level application structure, cross-package schemas, and open-recursive documents through linear port discipline destroys modularity.
  2. Faré's "Lambda: The Ultimate Object" (Protos / POO) at the Top Level: Following François-René Rideau's (Faré's) Protos, an object prototype is simply an open-recursive function transformer Self → Super → Record (proto), composed via associative/idempotent prototype mixing (mix) and closed only at projection time via a lazy fixed-point (fix).
  3. Explicitly Carved Leaf Kernels (Obend.Leaf): Only when a computation is explicitly marked via the leaf boundary (or lowered through Obend.Lower) does OBend enforce first-order closure conversion and compile the subterm into a flat supercombinator Leaf.Book (or affine interaction-combinator net BendTT) suitable for GPU/FPGA/ASIC execution.

3.2 Core4: The 16-Constructor Open-Recursive Object Kernel (Obend/Core/AST.lean)

In [lean/Obend/Core/AST.lean](file:///Users/ember/dev/obend/lean/Obend/Core/AST.lean), OBend's core calculus Core4 is mechanized as an inductive Expr with 16 constructors spanning four orthogonal strata:

  1. Object / Prototype Calculus (Faré's POO):
  2. .proto (body : Expr): Open-recursive prototype wrapper binding self (bvar 0) and super (bvar 1).
  3. .mix (lhs rhs : Expr): Associative override composition of two prototypes (resolved via C4 linearization in [lean/Obend/Core/C4.lean](file:///Users/ember/dev/obend/lean/Obend/Core/C4.lean)).
  4. .fix (target : Expr): Closes an open prototype by tying the recursive knot self := fix target and supplying the empty record as the base super.
  5. .recLit (fields : List (Field × Expr)): Extensional record literal.
  6. .proj (target : Expr) (field : Field): Field selection.
  7. Standard $\lambda$- and Algebraic Core:
  8. .bvar (idx : Nat), .lit (v : Val), .lam (body : Expr), .app (fn arg : Expr), .letE (val body : Expr), .prim (op : PrimOp) (args : List Expr).
  9. Law & Refinement Stratum:
  10. .law (dial : LawDial) (pred : Expr) (subject : Expr): Attaches a first-class boolean/propositional contract pred to subject under a three-state dial LawDial (.free = observational/log-only, .press = property-checked/narrowed over finite witnesses, .locked = admission-blocking certificate required).
  11. Live Reactive & Hardware-Leaf Stratum:
  12. .slot (pin : Nat) (init : Expr): Live reactive cell governed by [lean/Obend/Slot/Core.lean](file:///Users/ember/dev/obend/lean/Obend/Slot/Core.lean) (pin-indexed invalidation).
  13. .fold (tag : Nat) (body : Expr): Explicit trace-collapse boundary governed by [lean/Obend/Fold/Core.lean](file:///Users/ember/dev/obend/lean/Obend/Fold/Core.lean).
  14. .leaf (body : Expr): Explicit boundary carving out a pure first-order kernel for lowering into Obend.Leaf.Book ([lean/Obend/Lower/ToLeaf.lean](file:///Users/ember/dev/obend/lean/Obend/Lower/ToLeaf.lean)).

3.3 Closing the nanodregg Metatheoretic Open Problems (METATHEORY.md)

In [METATHEORY.md](file:///Users/ember/dev/obend/METATHEORY.md#L1-L246), OBend directly addresses the four open metatheoretic boundaries (LT1–LT4) documented in ~/dev/nanodregg and the Council audit:

1. LT4 Closed: First-Class Prototype Provenance (Obend/Core/PrototypeProvenance.lean)

In nanodregg, theorem LT4 ("A dynamic contract system cannot enforce single-inheritance prototype provenance via predicate assertions if prototype wrapping is purely functional") showed that if prototypes are erased to bare Val → Val → Val closures, a malicious term can forge prototype identity. In [lean/Obend/Core/PrototypeProvenance.lean](file:///Users/ember/dev/obend/lean/Obend/Core/PrototypeProvenance.lean#L1-L503), OBend introduces unforgeable ProtoId lineage DAGs (LineageNode, LineageDag) checked via C4 linearization before evaluation:

lean
-- file:///Users/ember/dev/obend/lean/Obend/Core/PrototypeProvenance.lean#L156-L248
inductive HasPrototypeProvenance (dag : LineageDag) : ProvenanceVal → ProtoId → Prop where
  | direct (pid : ProtoId) (clos : Closure) (chain : List ProtoId) :
      dag.lookup pid = some ⟨pid, [], .root⟩ →
      chain = [pid] →
      HasPrototypeProvenance dag (.protoVal pid clos chain) pid
  | mixed (pid target : ProtoId) (clos : Closure) (chain : List ProtoId) (parents : List ProtoId) :
      dag.lookup pid = some ⟨pid, parents, .mixNode⟩ →
      c4Linearize dag pid = some chain →
      target ∈ chain →
      HasPrototypeProvenance dag (.protoVal pid clos chain) target

theorem checkPrototypeWithProvenance_sound
    (dag : LineageDag) (v : ProvenanceVal) (target : ProtoId)
    (hCheck : checkPrototypeWithProvenance dag v target = true) :
    HasPrototypeProvenance dag v target

theorem forged_prototype_refused
    (dag : LineageDag) (forgedPid targetPid : ProtoId) (clos : Closure) (fakeChain : List ProtoId)
    (hNotInDag : dag.lookup forgedPid = none) :
    checkPrototypeWithProvenance dag (.protoVal forgedPid clos fakeChain) targetPid = false

2. Clairvoyant Call-by-Need Cost Semantics for Open-Recursive Knots (Obend/Equiv/Clairvoyant.lean)

To prove that memoized call-by-need fixed-point evaluation (fix (mix p q)) is both extensionality-equivalent to call-by-name/value and strictly cost-bounded (cost_need ≤ cost_cbv), [lean/Obend/Equiv/Clairvoyant.lean](file:///Users/ember/dev/obend/lean/Obend/Equiv/Clairvoyant.lean#L1-L2601) (2,601 lines) mechanizes a Hackett–Hutton clairvoyant call-by-need operational semantics extended to Core4 open-recursive prototype knots (Phase: .eval, .head, .knot, .wave, .cell):

lean
-- file:///Users/ember/dev/obend/lean/Obend/Equiv/Clairvoyant.lean#L412-L530
inductive Run : Phase → Heap → Env → Expr → Heap → Val → Cost → Prop where
  | lit (H : Heap) (E : Env) (v : BaseVal) :
      Run .eval H E (.lit v) H (.base v) Cost.zero
  | knot_skip (H : Heap) (E : Env) (p : Expr) (a : Addr) :
      H.alloc (.skipped) = (H', a) →
      Run .knot H E p H' (.thunk a) Cost.zero
  | knot_force (H H1 H2 : Heap) (E : Env) (p : Expr) (a : Addr) (v : Val) (c1 c2 : Cost) :
      H.alloc (.uneval E p) = (H1, a) →
      Run .eval H1 (a :: E) p H2 v c1 →
      Run .knot H E p (H2.update a (.evaluated v)) v (c1 + Cost.knotStep)

With mechanized theorems proving heap monotonicity, determinism up to clairvoyant choice, adequacy with Obend.Eval.eval, and strict cost dominance (clairvoyant_need_le_cbv_cost, fix_memoized_single_proto_cost).

3. Target Operational Adequacy of BendTT (Obend/Leaf/BendTT.lean)

In [lean/Obend/Leaf/BendTT.lean](file:///Users/ember/dev/obend/lean/Obend/Leaf/BendTT.lean#L1-L1505) (1,505 lines), OBend defines the typed affine/interaction-combinator target language BendTT (BTerm, BVal, BType, Linearity) along with its own standalone small-step reducer stepB? : BBook → BTerm → Option BTerm and multi-step fuel evaluator runB : Nat → BBook → BTerm → Option BVal, proving operational adequacy of the Leaf.Book → BendTT compiler:

lean
-- file:///Users/ember/dev/obend/lean/Obend/Leaf/BendTT.lean#L1180-L1420
theorem compileToBendTT_embedB (v : Obend.Leaf.LVal) :
    compileExprToBendTT (Obend.Leaf.LVal.toLExpr v) = embedBVal v

theorem stepB?_sound (book : Obend.Leaf.Book) (e : Obend.Leaf.LExpr) (v : Obend.Leaf.LVal)
    (hEval : Obend.Leaf.evalLeaf 1 book e = some v) :
    ∃ t', stepB? (compileBookToBendTT book) (compileExprToBendTT e) = some t'

theorem book_to_bendtt_sound (fuel : Nat) (book : Obend.Leaf.Book)
    (e : Obend.Leaf.LExpr) (v : Obend.Leaf.LVal)
    (hLeaf : Obend.Leaf.evalLeaf fuel book e = some v) :
    ∃ bFuel, runB bFuel (compileBookToBendTT book) (compileExprToBendTT e) = some (embedBVal v)

4. The Silicon Elaborator (SILICON-ELABORATOR.md)

[SILICON-ELABORATOR.md](file:///Users/ember/dev/obend/SILICON-ELABORATOR.md#L1-L396) specifies and mechanizes the compilation of Lean 4's kernel, unifier, discrimination trees, and OBend's prototype evaluator directly into FPGA/ASIC hardware.

flowchart TD
    A["Lean-Lite Dependent Kernel<br/>Obend/Lower/LeanKernel.lean<br/>(LExpr, LDecl, kernelIsDefEqFull)"] -->|"Erase Prop & Types + Lower Recursors<br/>Obend/Lower/Inductive.lean"| B["Core4 Open-Recursive AST<br/>Obend/Core/AST.lean"]
    B -->|"1st / 2nd / 3rd Futamura Projections<br/>Obend/Leaf/Futamura.lean"| C["Specialized Supercombinator Leaf.Book<br/>Obend/Leaf/AST.lean"]
    C -->|"Silicon Lowering & Tile Synthesis"| D["Hardware Reduction Machine<br/>Obend/Hardware/ReductionMachine.lean"]
    D --> E["64-bit ExprCAM Hash-Consing & WHNF<br/>Obend/Lower/ExprCAM.lean"]
    D --> F["Parallel Radix-Trie DiscrTreeLUT + SlotGuardReg<br/>Obend/Lower/DiscrTreeLUT.lean"]
    D --> G["2D XY Wormhole NoC + 3-Phase ICAP DPR<br/>dprTileSlot : Slot LeafPin TileBitstreamCandidate"]
    E & F & G --> H["Cycle-Accurate SystemVerilog & Verilator Co-Sim<br/>tests/silicon_elab/run_verilator_cosim.py"]

4.1 Dependent-Type Erasure & Lean-Lite Kernel Lowering (Obend/Lower/LeanKernel.lean & Inductive.lean)

How does OBend lower a dependently typed language like Lean 4 into an untyped/refinement-checked prototype calculus (Core4) and flat hardware supercombinators (Leaf.Book)? In [lean/Obend/Lower/LeanKernel.lean](file:///Users/ember/dev/obend/lean/Obend/Lower/LeanKernel.lean#L1-L2205) and [lean/Obend/Lower/Inductive.lean](file:///Users/ember/dev/obend/lean/Obend/Lower/Inductive.lean#L1-L654):

  1. Full Structural kernelIsDefEqFull: LeanKernel.lean models Lean expressions (LExpr: .bvar, .fvar, .mvar, .sort, .const, .app, .lam, .forallE, .letE, .lit, .proj) and defines the structural definitional-equality checker kernelIsDefEqFull : Nat → LEnv → LExpr → LExpr → Bool handling $\beta\delta\iota\zeta$-reduction, Nat literal successor bridges (Nat.succ n ≡ n + 1), $\eta$-expansion across .lam, and Prop proof irrelevance:
lean
   -- file:///Users/ember/dev/obend/lean/Obend/Lower/LeanKernel.lean#L1420-L1890
   theorem kernelIsDefEqFull_refl (fuel : Nat) (env : LEnv) (e : LExpr) (hFuel : fuel > 0) :
       kernelIsDefEqFull fuel env e e = true

   theorem kernelIsDefEqFull_nat_succ_bridge (fuel : Nat) (env : LEnv) (n : Nat) (hFuel : fuel ≥ 2) :
       kernelIsDefEqFull fuel env (.app (.const "Nat.succ" []) (.lit (.natVal n))) (.lit (.natVal (n + 1))) = true

   theorem kernelIsDefEqFull_eta_lam (fuel : Nat) (env : LEnv) (dom f : LExpr)
       (hFuel : fuel ≥ 2) (hNoLoose : hasLooseBVar 0 f = false) :
       kernelIsDefEqFull fuel env (.lam dom (.app f (.bvar 0))) f = true

   theorem kernelIsDefEqFull_prop_proofIrrel (fuel : Nat) (env : LEnv) (p1 p2 propTy : LExpr)
       (hFuel : fuel ≥ 2) (hProp : inferSort env propTy = some (.sort 0))
       (hTy1 : inferType env p1 = some propTy) (hTy2 : inferType env p2 = some propTy) :
       kernelIsDefEqFull fuel env p1 p2 = true
  1. Computational Relevance Erasure & Term-Level Lowering: Types (.forallE, .sort) and Prop proofs are erased to .lit (.int 0) at the runtime boundary (eraseTypesLExpr), while inductive constructors and recursors (InductiveSpec, CtorSpec, RecRule) are lowered into tagged records and Core4 dispatch tables (compileInductiveToCore4, compileRecursorToCore4), with mechanized simulation runLExprSteps_sound:
lean
   -- file:///Users/ember/dev/obend/lean/Obend/Lower/LeanKernel.lean#L1980-L2160
   theorem kernelCheckDecl_defEqFull_in_place_sound
       (fuel : Nat) (env : LEnv) (d : LDecl)
       (hCheck : kernelCheckDeclFull fuel env d = true) :
       WellTypedDeclFull fuel env d

   theorem runLExprSteps_sound (fuel : Nat) (env : LEnv) (e : LExpr) (n : Nat)
       (hEval : evalLExprToNat fuel env e = some n) :
       Obend.Eval.eval fuel [] (lowerLExprToCore4 env e) = some (.int (Int.ofNat n))

4.2 64-Bit Hardware Expression CAM (Obend/Lower/ExprCAM.lean)

In [lean/Obend/Lower/ExprCAM.lean](file:///Users/ember/dev/obend/lean/Obend/Lower/ExprCAM.lean#L1-L1435), every hash-consed expression node in the Silicon Elaborator is packed into a single 64-bit hardware CAM word (CamWord64):

$$\underbrace{\texttt{tag}}_{\text{bits } [63:60]\text{ (4b)}} \;\mid\; \underbrace{\texttt{looseBVar}}_{\text{bit } [59]\text{ (1b)}} \;\mid\; \underbrace{\texttt{hasFVar}}_{\text{bit } [58]\text{ (1b)}} \;\mid\; \underbrace{\texttt{hash26}}_{\text{bits } [57:32]\text{ (26b)}} \;\mid\; \underbrace{\texttt{leftIdx}}_{\text{bits } [31:16]\text{ (16b)}} \;\mid\; \underbrace{\texttt{rightIdx}}_{\text{bits } [15:0]\text{ (16b)}}$$
  • Single-Cycle Structural Hash-Consing & Pointer Equality: Because ExprCAM maintains canonical bottom-up interning (internNode), two normalized expressions are structurally equal iff their 16-bit CAM indices match (idx1 == idx2 in 1 clock cycle).
  • $O(1)$ Metadata Fast-Paths: Following Lean 4's Expr bitpacking in C++, looseBVar (bit 59) and hasFVar (bit 58) are computed combinatorially at insertion time:
  • If looseBVar == 0, instantiateRev is a 0-cycle no-op (camInstantiate_noLooseBVar_noop).
  • If hasFVar == 0, abstractFVar is a 0-cycle no-op (camAbstract_noFVar_noop).
  • If hash26(a) != hash26(b), isDefEq rejects in 1 clock cycle before walking children (camDefEqFastReject_sound).
lean
-- file:///Users/ember/dev/obend/lean/Obend/Lower/ExprCAM.lean#L310-L685
structure CamEntry where
  tag       : BitVec 4
  looseBVar : Bool
  hasFVar   : Bool
  hash26    : BitVec 26
  leftIdx   : BitVec 16
  rightIdx  : BitVec 16
  deriving DecidableEq, Repr

theorem packUnpackCamWord_roundtrip (e : CamEntry) :
    unpackCamWord64 (packCamWord64 e) = e

theorem camInstantiate_noLooseBVar_noop (cam : ExprCamBank) (idx substIdx : Nat)
    (e : CamEntry) (hLookup : cam.lookup idx = some e) (hNoLoose : e.looseBVar = false) :
    camInstantiateStep cam idx substIdx = idx

4.3 Parallel Radix-Trie DiscrTreeLUT & Single-Cycle SlotGuardReg (Obend/Lower/DiscrTreeLUT.lean)

In software Lean 4, Meta.DiscrTree traverses heap pointers sequentially during simp and typeclass synthesis. In [lean/Obend/Lower/DiscrTreeLUT.lean](file:///Users/ember/dev/obend/lean/Obend/Lower/DiscrTreeLUT.lean#L1-L732), OBend compiles discrimination trees into pipelined FPGA LUT radix tries gated by a 64-bit hardware SlotGuardReg bitmask:

  • Each preorder key token (DiscrKey: .const name arity, .fvar id, .lit v, .star, .arrow, .proj idx) is encoded as a 16-bit symbol fed at 1 token/cycle through a BRAM/LUT state transition table, with .star wildcard branches evaluated in parallel with exact-key branches via bitwise OR over candidate rule bitvectors (CandidateMask64).
  • Every cached simp or typeclass rule entry carries a depMask : BitVec 64 recording which Obend.Slot pins (environment declarations/attributes) it depends on. When a user edits a definition in a live workbook, flipping bit $k$ in SlotGuardReg invalidates all affected hardware cache lines in 1 clock cycle via (entry.depMask &&& activeSlotReg) == entry.depMask:
lean
-- file:///Users/ember/dev/obend/lean/Obend/Lower/DiscrTreeLUT.lean#L420-L610
def filterValidCandidates (activeSlotReg : BitVec 64) (entries : List HwRuleEntry) : List Nat :=
  (entries.filter (fun e => (e.depMask &&& activeSlotReg) == e.depMask)).map (·.ruleId)

theorem slotGuardReg_invalidation_exact
    (activeSlotReg : BitVec 64) (pin : Fin 64) (entry : HwRuleEntry)
    (hDepends : entry.depMask.getLsbD pin.val = true) :
    let nextReg := activeSlotReg &&& ~~~(BitVec.ofNat 64 (1 <<< pin.val))
    (entry.depMask &&& nextReg) != entry.depMask

4.4 The Three Futamura Projections in Hardware (Obend/Leaf/Futamura.lean)

In [lean/Obend/Leaf/Futamura.lean](file:///Users/ember/dev/obend/lean/Obend/Leaf/Futamura.lean#L1-L1835), OBend mechanizes the First, Second, and Third Futamura Projections over Obend.Leaf.Book supercombinators using a polyvariant Binding-Time Analysis (BTA: .static vs .dynamic inputs) and partial evaluator mixPE:

  1. First Futamura Projection (futamura1 : Book → FnId → List LVal → Book): Specializes an interpreter/elaborator rule interp with respect to a static object/type-class table staticArgs, eliminating all static dispatch .caseInt branches and producing a specialized residual Book:
lean
   -- file:///Users/ember/dev/obend/lean/Obend/Leaf/Futamura.lean#L890-L960
   theorem futamura1_sound (fuel : Nat) (book : Book) (fn : FnId)
       (staticArgs dynArgs : List LVal) (v : LVal)
       (hEval : evalLeaf fuel book (.call fn (staticArgs.map LVal.toLExpr ++ dynArgs.map LVal.toLExpr)) = some v) :
       evalLeaf fuel (futamura1 book fn staticArgs) (.call (specializedFnName fn staticArgs) (dynArgs.map LVal.toLExpr)) = some v
  1. Second Futamura Projection (futamura2 : SpecGenConfig → Book): Specializes the partial evaluator mixPE with respect to the elaborator elabBook, producing a standalone hardware compiler generator (cogen) that maps new user declarations directly to residual Leaf.Book tiles without re-running interpretive lookup.
  2. Third Futamura Projection (futamura3): Self-applies mixPE to mixPE, proven coherent via futamura_projections_coherent ([lean/Obend/Leaf/Futamura.lean](file:///Users/ember/dev/obend/lean/Obend/Leaf/Futamura.lean#L1680-L1795)).

4.5 Hardware Reduction Machine, 2D XY Wormhole NoC & Glitch-Free DPR (Obend/Hardware/ReductionMachine.lean)

In [lean/Obend/Hardware/ReductionMachine.lean](file:///Users/ember/dev/obend/lean/Obend/Hardware/ReductionMachine.lean#L1-L1755), specialized Leaf.Book rules are lowered into a spatial array of AutomatonTiles interconnected by a 2D XY dimension-ordered Wormhole Network-on-Chip (NocFabric) and reconfigured at runtime via Dynamic Partial Reconfiguration (ICAP):

  1. 2D XY Wormhole NoC with Mechanized Flit & Credit Conservation:
  2. Each tile at (x, y) holds NocTileState (inbox : List NocFlit, outbox : List NocFlit, credits : Nat, rules : List TileRule).
  3. Routing (routeXYStep) steps along X until curX == dstX, then along Y until curY == dstY (provably deadlock-free on a 2D mesh, routeXY_manhattan_decreases), while stepNocRouter_conserves_flits_and_credits and noc_step_conserves_flits prove universal conservation of total in-flight flits across the entire fabric:
lean
   -- file:///Users/ember/dev/obend/lean/Obend/Hardware/ReductionMachine.lean#L1120-L1385
   theorem stepNocRouter_conserves_flits_and_credits
       (src dst : NocTileState) (flit : NocFlit)
       (hInOut : src.outbox = flit :: restOut)
       (hCredit : dst.credits > 0) :
       let (src', dst') := transferFlitWithCredit src dst flit restOut
       src'.outbox.length + dst'.inbox.length = src.outbox.length + dst.inbox.length ∧
       dst'.credits + dst'.inbox.length = dst.credits + dst.inbox.length

   theorem noc_step_conserves_flits (fabric : NocFabric) :
       totalFabricFlits (stepNocFabric fabric) = totalFabricFlits fabric
  1. Glitch-Free 3-Phase ICAP Dynamic Partial Reconfiguration Instantiating Obend.Slot:
  2. When a Futamura-specialized rule changes because a workbook Slot pin mutated, the FPGA reconfigures only that tile region via a 3-phase protocol (DprPhase: .active $\to$ .isolatedAndDraining $\to$ .loadingFrames $\to$ .releasingIsolation $\to$ .active).
  3. Crucially, dprTileSlot is formalized directly as an instance of Obend.Slot.Slot LeafPin TileBitstreamCandidate, proving that a mutated LeafPin immediately rejects stale tile bitstreams (dprTile_moved_pin_blocks) and that reconfiguration preserves all in-flight packets outside the isolated tile (dpr_glitch_free_isolation):
lean
   -- file:///Users/ember/dev/obend/lean/Obend/Hardware/ReductionMachine.lean#L1510-L1695
   def dprTileSlot (tileId : Nat) (expectedPins : List (Nat × Nat))
       (cand : TileBitstreamCandidate) : Obend.Slot.Slot Nat TileBitstreamCandidate :=
     { value := cand
       deps  := expectedPins
       valid := cand.tileId == tileId && cand.crcValid && cand.isolationAck }

   theorem dprTile_moved_pin_blocks (tileId : Nat) (pin vOld vNew : Nat)
       (cand : TileBitstreamCandidate) (hNe : vOld ≠ vNew) :
       Obend.Slot.isValid [(pin, vNew)] (dprTileSlot tileId [(pin, vOld)] cand) = false

4.6 Verilator Cycle-Accurate Co-Simulation (tests/silicon_elab/run_verilator_cosim.py)

In [tests/silicon_elab/run_verilator_cosim.py](file:///Users/ember/dev/obend/tests/silicon_elab/run_verilator_cosim.py#L1-L240), OBend provides an executable Verilator (verilator --cc --exe --build -Wall -Wno-fatal) co-simulation harness that synthesizes a 3-module SystemVerilog Silicon Elaborator SoC (expr_cam_64, discr_tree_lut, and icap_dpr_tile) and verifies cycle-by-cycle agreement with the Lean reference model across four hardware test vectors:

  1. Vector 1 (ExprCAM Hash-Consing & Pointer Equality): Interns Nat.add x 0 twice and verifies single-cycle CAM hit (hit == 1, identical 16-bit index) plus looseBVar == 0 fast-path.
  2. Vector 2 (DiscrTreeLUT Parallel Wildcard Match + SlotGuardReg Invalidation): Queries [const(add), star, lit(0)], verifies parallel LUT match returning rules {R1, R2} in 3 cycles, then flips bit 1 of SlotGuardReg and verifies 1-cycle hardware invalidation of rule R2.
  3. Vector 3 (Glitch-Free 3-Phase ICAP DPR Hot-Swap): Asserts req_reconfig, verifies tile_isolated == 1 drains inflight_count to 0 before asserting icap_we, streams the Futamura-specialized rule frames, and resumes throughput with 0 dropped packets.
  4. Vector 4 (End-to-End Elaboration Speedup): Measures 19 clock cycles in hardware vs 340+ software interpreter cycles ($17.89\times$ cycle reduction) on a repeated simp + whnf reduction step.

Dossier 07 (§5–§9, + Wave C3 Errata) · `obend` Physical Flow, 5-Stage `SiliconElabFabric`, RDNA2 Validation, `Ozaki` Exact Collectives, Next-Mathematica & DeOS
Working field notes & source index below, with theorem anchors, code pointers, git history, and open questions.

5. The Silicon / FPGA / Physical Engineering Flow (PHYSICAL.md & hardware/)

Beyond accelerating its own elaborator, OBend treats silicon RTL, eFPGA bitstreams, analog/mixed-signal (AMS) circuits, CAD/CSG geometry, multiphysics PDEs, and OpenUSD scenes as projections of the same law-carrying object graph ([PHYSICAL.md](file:///Users/ember/dev/obend/PHYSICAL.md#L1-L162)).

5.1 Standalone hardware/ Verification & eFPGA Stack

The top-level [hardware/](file:///Users/ember/dev/obend/hardware/) directory contains three self-contained Lean 4 hardware verification suites, a 1,715-line Rust FFI/CLI engine, Verilator & multiphysics C++ simulators, Z3 SMT2 formal equivalence scripts, and physical ASIC/FPGA constraints:

1. [hardware/EfpgaFabric.lean](file:///Users/ember/dev/obend/hardware/EfpgaFabric.lean#L1-L667) (667 lines)

Formalizes a FABulous-style embedded FPGA (eFPGA) architecture (TileType: .clb, .dsp, .bram, .io, .routing) with BELConfig (lutInit : BitVec 16, ffEnable : Bool, carryEnable : Bool), SwitchMatrixEntry, and BitstreamFrame (32-bit frame address + 64-bit configuration word + CRC-16).

  • Proves encodeDecode_roundtrip for bitstream serialization, verifyRoutingConnectivity_sound (checking that every net in a placed-and-routed design forms a loop-free directed tree in the switch matrix), and static timing analysis (computeCriticalPathPs_monotone).

2. [hardware/HardwareVerify.lean](file:///Users/ember/dev/obend/hardware/HardwareVerify.lean#L1-L1057) (1,057 lines)

Formalizes a 5-layer hardware verification hierarchy:

  • Layer 1: High-level OBend/Bend functional spec (SpecFn).
  • Layer 2: Cycle-accurate RTL state machine (RtlModule).
  • Layer 3: Gate-level technology-mapped netlist (GateNetlist: .and2, .or2, .xor2, .inv, .mux2, .dff).
  • Layer 4: Placed-and-routed physical layout (PhysicalLayout: CellPlacement, MetalSegment across li1/met1..met5).
  • Layer 5: Foundry PDK Design Rule Check (Sky130DrcRules: min width $140\text{nm}$, min spacing $140\text{nm}$, via enclosure $60\text{nm}$).
  • Proves end-to-end functional preservation (spec_to_gate_equiv) alongside geometric non-overlapping cell placement (checkNoCellOverlap_sound) and Sky130 DRC compliance (checkSky130Drc_sound).

3. [hardware/SiliconProcess.lean](file:///Users/ember/dev/obend/hardware/SiliconProcess.lean#L1-L618) (618 lines)

Models multi-node semiconductor physics across Sky130 ($130\text{nm}$), TSMC $28\text{nm}$, TSMC N7 ($7\text{nm}$ FinFET), and TSMC N3 ($3\text{nm}$ GAA nanosheet):

  • Formalizes Black's Equation for Electromigration (EM) mean-time-to-failure, Reaction-Diffusion NBTI threshold-voltage shift ($\Delta V_{\text{th}}$) over a 10-year mission profile, alpha-particle + cosmic-ray Soft Error Rate (FIT/Mbit) with SECDED ECC mitigation, and automated $7\text{nm} \to 3\text{nm}$ process migration (migrate7nmTo3nm_preserves_timing_slack).

4. [hardware/rust-ffi/src/lib.rs](file:///Users/ember/dev/obend/hardware/rust-ffi/src/lib.rs#L1-L1715) & [bin/obend_hw_host.rs](file:///Users/ember/dev/obend/hardware/rust-ffi/src/bin/obend_hw_host.rs#L1-L151)

Provides the native C-ABI (#[no_mangle] pub extern "C") and CLI host bridge (obend_hw_host) executing:

  • Compact 39-Byte Tag 0x0BED CBOR Proof Certificates (emit_cbor_proof_certificate, verify_cbor_proof_certificate): Encodes [magic: 0x0BED, version: 1, spec_hash: u64, netlist_hash: u64, slack_ps: i32, drc_clean: u8, crc32: u32] into exactly 39 bytes (0xD9 0x0BED ...).
  • 2D Nonlinear Magnetostatics FEMM Solver (solve_2d_femm_halbach): Newton-Raphson B-H curve permeability solver over a 2D triangular mesh computing magnetic vector potential $A_z$, flux density $|B|$, and Maxwell stress tensor torque.
  • Interval-Pruned F-Rep Octree Mesher & G-Code Emitter (eval_frep_octree, emit_fanuc_gcode): Evaluates CSG signed-distance fields over dyadic 3D boxes, pruning empty/full octants (>75% node pruning) and emitting collision-free 3-axis Fanuc G-code.
  • 80-Candidate Multi-Objective Pareto Evolution (run_pareto_hardware_evolution): Evolves multiplier/MAC datapath architectures across (Area_LUTs, Delay_ps, Power_uW) fronts.

5. [hardware/sim/](file:///Users/ember/dev/obend/hardware/sim/) (Verilator, Multiphysics C++, Z3 LEC, Vivado XDC, OpenSTA, Sky130 OpenLane)

  • [hardware/sim/tb_top.sv](file:///Users/ember/dev/obend/hardware/sim/tb_top.sv) & [sim_main.cpp](file:///Users/ember/dev/obend/hardware/sim/sim_main.cpp): Cycle-accurate SystemVerilog eFPGA CLB+switch-matrix fabric and C++ Verilator testbench verifying LUT4 truth tables, carry chains, and sequential accumulator loops.
  • [hardware/sim/multiphysics_sim.cpp](file:///Users/ember/dev/obend/hardware/sim/multiphysics_sim.cpp): Coupled electro-thermal-mechanical C++ solver verifying SiC MOSFET half-bridge switching losses ($E_{\text{on}}/E_{\text{off}}$) coupled into a 3D finite-difference heat-sink thermal network.
  • Z3 SMT2 Formal Equivalence Scripts:
  • [lec_compiler_fabublox.smt2](file:///Users/ember/dev/obend/hardware/sim/lec_compiler_fabublox.smt2): Bit-vector (QF_BV) equivalence proof between Obend.Hardware.Compiler RTL and FABulous eFPGA LUT4+Carry configuration bits (unsat).
  • [lec_ams_waferspace.smt2](file:///Users/ember/dev/obend/hardware/sim/lec_ams_waferspace.smt2): Real-arithmetic (QF_NRA) verification of a 10-bit SAR ADC charge-redistribution DAC transfer curve and $1.2\text{V}$ bandgap reference temperature coefficient.
  • [lec_multiphysics_rf.smt2](file:///Users/ember/dev/obend/hardware/sim/lec_multiphysics_rf.smt2): Verification of Smith-chart L-network impedance matching ($50\,\Omega \to Z_L$) and microstrip characteristic impedance $Z_0$.
  • Physical Backend Constraints: [obend_floorplan.xdc](file:///Users/ember/dev/obend/hardware/sim/obend_floorplan.xdc) ($250\text{MHz}$ UltraScale+ clock & pblock_obend_tile DPR floorplan), [obend_asic.tcl](file:///Users/ember/dev/obend/hardware/sim/obend_asic.tcl) (OpenSTA $500\text{MHz}$ timing constraints), and [openlane_sky130_config.json](file:///Users/ember/dev/obend/hardware/sim/openlane_sky130_config.json) (sky130_fd_sc_hd, $45\%$ core utilization).
  • Master Hardware Test Runner: [lean/tests/run-hardware.py](file:///Users/ember/dev/obend/lean/tests/run-hardware.py#L1-L465) orchestrates all 6 stages (Lean proof compilation, Rust FFI cargo test, Verilator RTL simulation, Multiphysics C++ simulation, Z3 SMT2 LEC checks, and 39-byte 0x0BED CBOR certificate verification).

5.2 The Unified Obend.Hardware.* Lean 4 Stack

Inside [lean/Obend/Hardware/](file:///Users/ember/dev/obend/lean/Obend/Hardware/), OBend integrates 12 domain modules directly into the main Obend proof tree:

Module PathLinesCore Mechanized Capabilities & Key Theorems
[Compiler.lean](file:///Users/ember/dev/obend/lean/Obend/Hardware/Compiler.lean)2,560SignalExpr, RegSpec, NetlistModule, FpgaTarget (Xilinx_UltraScalePlus, Lattice_ECP5, FABulous_eFPGA), Verilog emission (emitVerilog), resource/timing budgets (compileLeafToRtl_sound, checkFpgaBudget_sound).
[UserspacePhysical.lean](file:///Users/ember/dev/obend/lean/Obend/Hardware/UserspacePhysical.lean)789Unified PhysicalArtifact wrapper equipping any hardware/CAD/physics artifact with Obend.Slot reactive dependencies, Obend.Law.Contract certificates, and Obend.Receipt hashes (physicalSlot_invalidation_exact).
[OpenHypergraph.lean](file:///Users/ember/dev/obend/lean/Obend/Hardware/OpenHypergraph.lean)1,881Symmetric monoidal string diagrams (HyperEdge, OpenHypergraph, composeSeq, composePar), whole-graph functorial reverse-mode AD (compileGraphAdjoint with automatic .add fanout cotangent accumulation across multi-edge graphs, compileGraphAdjoint_multiEdge_sound), and synchronous pipelined wavefront RTL synthesis (compileHypergraphToRtlPipelined_latency_exact). (Inspired by categorical open-hypergraph / catgrad string-diagram compilers).
[GeometryCAM.lean](file:///Users/ember/dev/obend/lean/Obend/Hardware/GeometryCAM.lean)2,066Implicit F-Rep / SDF solid modeling (SdfExpr: .sphere, .box, .cylinder, .union, .intersect, .diff, .offset, .neg), linear SSA register tape compilation (SsaTapeOp including .neg), 3D interval box pruning + backward-liveness dead-code compaction (pruneSsaTapeForBox, compactSsaTape, prune_and_compact_ssa_tape_sound), octree meshing, and Fanuc G-code / RS-274X Gerber CAM generation.
[OpenUSD.lean](file:///Users/ember/dev/obend/lean/Obend/Hardware/OpenUSD.lean)1,532Formalization of Pixar OpenUSD LIVRPS (Local, Inherits, VariantSets, References, Payload, Specializes) strength ordering (UsdArc, UsdPrimSpec, livrpsKey) and proof that LIVRPS composition is order-isomorphic to OBend's C4 prototype linearization (usd_livrps_commutes_with_c4).
[Accelerators.lean](file:///Users/ember/dev/obend/lean/Obend/Hardware/Accelerators.lean)529Unified multi-backend dispatch (AcceleratorTarget: .fpgaLut, .gpuWavefront, .tpuSystolic, .dsp58Cascade, .ozakiFp4TensorCore), mapping a single Leaf.Book kernel across all 5 silicon targets with bit-exact functional equivalence.
[QuantumMatter.lean](file:///Users/ember/dev/obend/lean/Obend/Hardware/QuantumMatter.lean)1,438Tight-binding crystal Hamiltonians, ZX-calculus phase-gadget fusion (zxSpiderFusion_sound), and Mach-Zehnder Interferometer (MZI) photonic waveguide meshes synthesizing exact Krawtchouk equitable-partition splitting ratios (synthesizeKrawtchoukPhotonicCouplers_realizes_ratio, compileEquitableToPhotonicArray_ratio_sound).
[Kinematics.lean](file:///Users/ember/dev/obend/lean/Obend/Hardware/Kinematics.lean)485$SE(3)$ rigid-body screw theory, Product-of-Exponentials (PoE) forward kinematics, and spatial manipulator Jacobians.
[Magnetics.lean](file:///Users/ember/dev/obend/lean/Obend/Hardware/Magnetics.lean)512Halbach permanent-magnet arrays, magnetic circuit reluctance networks, and Maxwell stress tensor force/torque bounds.
[FluidThermal.lean](file:///Users/ember/dev/obend/lean/Obend/Hardware/FluidThermal.lean)4981D/2D Navier-Stokes pipe/channel pressure drop (Darcy-Weisbach), Nusselt convective heat transfer, and cold-plate thermal resistance networks.
[PowerElectronics.lean](file:///Users/ember/dev/obend/lean/Obend/Hardware/PowerElectronics.lean)518Buck/Boost/DAB DC-DC converter volt-second & amp-second steady-state ripple bounds, dead-time shoot-through prevention, and Bode phase-margin stability.

5.3 Deep Dive: Council-Remediated Proofs in GeometryCAM, OpenHypergraph, and QuantumMatter

During the 2026-11-01 Council Audit ([review/FABLE-COUNCIL-20261101.md](file:///Users/ember/dev/obend/review/FABLE-COUNCIL-20261101.md)), Claude Fable 5.1 and Gemini 4 Argon noted that the initial Wave 5 versions of GeometryCAM.lean, OpenHypergraph.lean, and QuantumMatter.lean had simplified proofs (missing .neg and dead-code compaction in GeometryCAM, single-op AD in OpenHypergraph, and length-only coupler checks in QuantumMatter). In commits 8f9f822c and 23a76513, Ember mechanized the full theorems:

  1. Interval-Pruned & Dead-Code-Compacted SSA Geometry Tapes (Obend/Hardware/GeometryCAM.lean): Following Matt Keeter's libfive / Prospero architecture, GeometryCAM.lean compiles an SdfExpr into a flat linear SSA register tape (List SsaTapeInstr), evaluates 3D Box3D interval bounds across the tape to rewrite .min rL rR / .max rL rR instructions into .copy rL or .copy rR whenever the intervals are strictly disjoint (rL.hi < rR.lo), runs a backward live-register pass (liveRegsBackward) to drop dead instructions, and proves universal semantic preservation for all points $(x,y,z) \in B$:
lean
   -- file:///Users/ember/dev/obend/lean/Obend/Hardware/GeometryCAM.lean#L1720-L1995
   theorem pruneSsaTapeForBox_point_sound
       (tape : List SsaTapeInstr) (box : Box3D) (x y z : Int)
       (hInBox : box.containsPoint x y z = true) :
       evalSsaTape (pruneSsaTapeForBox tape box).1 x y z = evalSsaTape tape x y z

   theorem prune_and_compact_ssa_tape_sound
       (tape : List SsaTapeInstr) (box : Box3D) (outReg : Nat) (x y z : Int)
       (hInBox : box.containsPoint x y z = true) :
       (evalSsaTape (compactSsaTape (pruneSsaTapeForBox tape box).1 outReg) x y z).lookup outReg =
       (evalSsaTape tape x y z).lookup outReg
  1. Whole-Graph Functorial Reverse-Mode AD & Wavefront Pipelining (Obend/Hardware/OpenHypergraph.lean): compileGraphAdjoint traverses an arbitrary multi-edge OpenHypergraph in reverse topological order, replacing each forward hyperedge with its local pullback (localAdjointOps) and automatically inserting .add cotangent-accumulation nodes whenever a forward wire fans out to multiple consumer edges:
lean
   -- file:///Users/ember/dev/obend/lean/Obend/Hardware/OpenHypergraph.lean#L1410-L1820
   theorem compileGraphAdjoint_multiEdge_sound (x w : Int) :
       evalHypergraph (compileGraphAdjoint twoStageMulAddGraph) [x, w, 1] =
       [w, x, 1] -- exact reverse-mode gradient (∂L/∂x = w, ∂L/∂w = x)

   theorem compileHypergraphToRtlPipelined_latency_exact (g : OpenHypergraph) :
       let pipe := compileHypergraphToRtlPipelined g
       pipe.pipelineDepth = (assignWavefrontStages g).maxStage + 1
  1. Krawtchouk $3:4:3$ Photonic Coupler Realization (Obend/Hardware/QuantumMatter.lean): To map a 1D quantum walk derived from the 3-cube ($Q_3$) Krawtchouk equitable partition (with quotient row ratios $3:4:3$) onto a silicon-nitride Mach-Zehnder interferometer array, QuantumMatter.lean proves that synthesizeKrawtchoukPhotonicCouplers realizes the exact parts-per-million power-splitting ratios $375000 : 500000 : 375000\,\text{ppm}$ ($3/8 : 4/8 : 3/8$), while a #tooth negative test proves that an uncalibrated Pythagorean $[80/60, 50/50, 80/60]$ coupler array is rejected:
lean
   -- file:///Users/ember/dev/obend/lean/Obend/Hardware/QuantumMatter.lean#L1210-L1415
   def couplerRealizesQuotientRatio (c : PhotonicCoupler) (num den : Nat) : Bool :=
     decide (c.powerSplitPpm * den == num * 1000000)

   theorem compileEquitableToPhotonicArray_ratio_sound :
       arrayRealizesKrawtchoukRatios (compileEquitableToPhotonicArray cubeEquitable343) [(3, 8), (4, 8), (3, 8)] = true

   theorem wrong_coupler_refused_by_krawtchouk_ratio :
       arrayRealizesKrawtchoukRatios
         { couplers := [couplerPythagorean80_60, coupler3dB, couplerPythagorean80_60], waveguideLossMdBPerCm := 10 }
         [(3, 8), (4, 8), (3, 8)] = false

5.4 The 6-Stage Silicon Kernel Equivalence & Ozaki Base-13 FP4 Tensor Cores (Obend/Lower/Proofs/SiliconKernel.lean & SelfAccelerate.lean)

In [lean/Obend/Lower/Proofs/SiliconKernel.lean](file:///Users/ember/dev/obend/lean/Obend/Lower/Proofs/SiliconKernel.lean#L1-L707) and [lean/Obend/Lower/Proofs/SelfAccelerate.lean](file:///Users/ember/dev/obend/lean/Obend/Lower/Proofs/SelfAccelerate.lean#L1-L660), OBend proves a 6-stage vertical equivalence chain connecting high-level Lean-lite specifications down to five concrete hardware execution substrates:

  1. Stage 1: Lean-lite dependent expression (Obend.Lower.LeanKernel.LExpr).
  2. Stage 2: Type-erased Core4 open-recursive prototype expression (Obend.Core.Expr).
  3. Stage 3: Closure-converted supercombinator Leaf.Book (Obend.Leaf.Book).
  4. Stage 4A (FPGA RTL): Synchronous LUT/FF netlist (Obend.Hardware.Compiler.NetlistModule).
  5. Stage 4B (AMD CDNA3 GPU Wavefront ISA): 64-lane SIMD wavefront instructions (v_add_u32, v_mad_u64_u32, s_cbranch_execz, LDS shared memory banks).
  6. Stage 4C (TPU Systolic Array + Xilinx Versal DSP58 Cascade + Ozaki Base-13 FP4 (E2M1) Tensor Core):
  7. Specifically, SiliconKernel.lean formalizes the Ozaki Scheme in Base-13 (RNS / residue-sliced FP4 E2M1 Tensor Cores), decomposing exact 32-bit integer/fixed-point matrix multiplications into low-bitwidth FP4 (E2M1) tensor-core outer products accumulated without overflow and reconstructed exactly:
lean
-- file:///Users/ember/dev/obend/lean/Obend/Lower/Proofs/SiliconKernel.lean#L480-L690
theorem ozakiFp4Base13_dot_exact (a b : List Nat) (hLen : a.length = b.length)
    (hBound : ∀ x ∈ a, x < 169) (hBoundB : ∀ y ∈ b, y < 169) :
    evalOzakiFp4Base13Dot a b = exactIntDot a b

theorem sixStageSiliconPipeline_coherent (fuel : Nat) (env : LEnv) (e : LExpr) (n : Nat)
    (hLean : evalLExprToNat fuel env e = some n) :
    evalCore4Stage fuel env e = some n ∧
    evalLeafBookStage fuel env e = some n ∧
    evalFpgaRtlStage env e = n ∧
    evalCdna3WavefrontStage env e = n ∧
    evalSystolicOzakiStage env e = n

And in [lean/Obend/Lower/Proofs/SelfAccelerate.lean](file:///Users/ember/dev/obend/lean/Obend/Lower/Proofs/SelfAccelerate.lean#L1-L660), OBend applies this pipeline to its own Obend.Lower.LeanKernel and Obend.Core.C4 kernels (selfAccelerateKernelDefEq_sound, selfAccelerateC4Linearize_sound), proving that the hardware-accelerated Silicon Elaborator produces bit-identical validation verdicts to the software Lean 4 kernel while achieving formal cycle-count speedups (hardware_elaborator_cycle_bound).


6. Next-Mathematica: Certified Symbolic-Numeric Analysis & Multi-Projection Workbooks (NEXT-MATHEMATICA.md)

In [NEXT-MATHEMATICA.md](file:///Users/ember/dev/obend/NEXT-MATHEMATICA.md#L1-L261), Ember positions OBend against Stephen Wolfram's Mathematica: whereas Mathematica relies on untrusted C internals where symbolic rewrites silently cross branch cuts or lose floating-point precision, Next-Mathematica makes every symbolic transformation and numerical enclosure a law-carrying Core4 prototype transition backed by a Lean 4 proof.

6.1 The Obend.Analysis.* Certified Symbolic-Numeric Suite

All 8 modules in [lean/Obend/Analysis/](file:///Users/ember/dev/obend/lean/Obend/Analysis/) are 100% sorry-free:

  1. Universal Dyadic Interval Arithmetic ([Obend/Analysis/RealAnalysis.lean](file:///Users/ember/dev/obend/lean/Obend/Analysis/RealAnalysis.lean#L1-L504)):
  2. Formalizes Interval (lo : Int, hi : Int, lo_le_hi : lo ≤ hi) with Interval.contains (I : Interval) (x : Int) : Prop := I.lo ≤ x ∧ x ≤ I.hi.
  3. Proves the component enclosure lemmas (Interval.add_mem, Interval.neg_mem, Interval.sub_mem, Interval.mul_mem, Interval.sqr_mem including the non-negativity tightening 0 ≤ x * x for squares!) and the Universal Fundamental Theorem of Interval Arithmetic (evalInterval_sound) over arbitrary RealExpr ASTs (.var, .const, .add, .sub, .mul, .neg, .sqr):
lean
   -- file:///Users/ember/dev/obend/lean/Obend/Analysis/RealAnalysis.lean#L365-L445
   theorem evalInterval_sound (e : RealExpr) (envI : Nat → Interval) (envPt : Nat → Int)
       (hEnv : ∀ v, (envI v).contains (envPt v)) :
       (evalInterval e envI).contains (evalPoint e envPt)
  • Includes 3 #tooth negative tests at lines 471–503 (tooth_naive_interval_mul_unsound, tooth_uncentered_sqr_wider_than_tight, tooth_out_of_box_root_rejected) demonstrating that naive [a.lo*b.lo, a.hi*b.hi] interval multiplication fails on negative numbers [-2, 1] * [-3, 2] and is caught by the specification.
  • Forward-Mode Dual Numbers & Symbolic Differentiation ([Obend/Analysis/Diff.lean](file:///Users/ember/dev/obend/lean/Obend/Analysis/Diff.lean)):
  • Proves exact agreement between symbolic derivative compilation (diffExpr) and dual-number evaluation (evalDual_eq_symbolic_diff), plus automatic Lipshitz bound synthesis.
  • High-Order Taylor Models ([Obend/Analysis/TaylorModel.lean](file:///Users/ember/dev/obend/lean/Obend/Analysis/TaylorModel.lean)):
  • Combines degree-$k$ polynomial expansions with rigorous interval remainder enclosures (TaylorModel.add_sound, TaylorModel.mul_sound), solving the interval dependency problem ($x - x = [0,0]$ rather than $[-\Delta, +\Delta]$).
  • Certified Buchberger / Gröbner Basis Certificates ([Obend/Analysis/Groebner.lean](file:///Users/ember/dev/obend/lean/Obend/Analysis/Groebner.lean)):
  • Multivariate polynomial rings (Monomial, Poly) with lexicographic/graded-reverse-lexicographic orders, S-polynomials (sPoly), multivariate division with remainder, and Hilbert Nullstellensatz / ideal-membership certificates (groebner_ideal_membership_sound).
  • Validated ODE Picard-Lindelöf Flowpipes ([Obend/Analysis/Flowpipe.lean](file:///Users/ember/dev/obend/lean/Obend/Analysis/Flowpipe.lean)):
  • Time-stepping Euler/Taylor enclosure tubes (FlowpipeStep) with contraction certificates proving trajectory containment across $[t_k, t_{k+1}]$.
  • Hybrid Systems & Transverse Barrier Certificates ([Obend/Analysis/Hybrid.lean](file:///Users/ember/dev/obend/lean/Obend/Analysis/Hybrid.lean)):
  • Combines continuous ODE flowpipes with discrete guard/jump transitions (HybridAutomaton), proving safety invariance via Lie-derivative barrier certificates (barrier_certificate_invariant).
  • Equitable Graph Partitions & Krawtchouk Matrices ([Obend/Analysis/Equitable.lean](file:///Users/ember/dev/obend/lean/Obend/Analysis/Equitable.lean)) & Quantum Walks ([Obend/Analysis/QuantumWalk.lean](file:///Users/ember/dev/obend/lean/Obend/Analysis/QuantumWalk.lean)):
  • Mechanizes equitable partition quotient matrices ($A P = P B$, checkEquitablePartition_sound), hypercube $Q_n$ Krawtchouk eigenvalues, and continuous/discrete quantum walk state-transfer fidelity (quantumWalk_norm_preserved).

6.2 Workbook Elaboration (Obend/Elab/Workbook.lean) & Multi-Projection GUI (crates/obend-gui/)

  • Lean 4 Elaboration Macros ([lean/Obend/Elab/Workbook.lean](file:///Users/ember/dev/obend/lean/Obend/Elab/Workbook.lean#L1-L1138)): Provides #import_obend and #obend_decl commands that parse .obend surface workbooks ([lean/Obend/Frontend/Parser.lean](file:///Users/ember/dev/obend/lean/Obend/Frontend/Parser.lean)), elaborate them into Core4 terms inside the live Lean 4 environment, track reactive cell dependencies via Obend.Slot, and incrementalize workbook recomputation (workbook_incremental_recompute_exact).
  • Multi-Projection Rust Viewport ([crates/obend-gui/src/viewport.rs](file:///Users/ember/dev/obend/crates/obend-gui/src/viewport.rs#L1-L1247)): Implements the bidirectional symbolic/CAD/EDA workbook UI with 10 ProjectionKinds (Code, SliderTable, PhasePortrait, BodePlot, Floorplan2D, SchematicNetlist, WaveformTrace, HollowSolid3D, UsdStageTree, ProofCertificateView) and 3 PhysicalViewportKinds (SdfRaymarch3D, FaltblattSchematic, FpgaDieMap), coupled to the interactive 3-state LawDial (Free / Press / Locked). Dragging a mechanical dimension or filter capacitor slider in the GUI updates the underlying Obend.Slot pin, triggers incremental Press/Locked re-verification, and immediately flags any violated thermal/timing/DRC contract in the viewport.

7. The Latest Iteration of Dregg Systems: DeOS Contracts, Vault, Ledger, Consensus & Sandstorm (DEOS-CONTRACTS-CONSENSUS.md)

In [DEOS-CONTRACTS-CONSENSUS.md](file:///Users/ember/dev/obend/DEOS-CONTRACTS-CONSENSUS.md#L1-L119), OBend unifies the distributed object, capability, contract, and consensus research from ~/dev/dregg, ~/dev/minidregg, and ~/dev/nanodregg into DeOS (Decentralized Object System).

7.1 Four-Tier Law & Contract Architecture (Obend/Law/Contract.lean)

In [lean/Obend/Law/Contract.lean](file:///Users/ember/dev/obend/lean/Obend/Law/Contract.lean#L1-L770), every object prototype or reactive workbook cell can carry a CellContract governed by LawDial (.free, .press, .locked) and backed by a 4-tier ContractCert:

lean
-- file:///Users/ember/dev/obend/lean/Obend/Law/Contract.lean#L85-L195
inductive CertTier where
  | tier0_pressKernel   -- Decidable finite witness check (`decide +kernel`)
  | tier1_symbolicProof -- Universal symbolic Lean 4 theorem hash
  | tier2_boundedModel  -- Bounded model-checking / SMT horizon k certificate
  | tier3_runtimeGuard  -- Dynamic runtime monitor with blame assignment
  deriving DecidableEq, Repr

theorem cellContract_relaw_sound
    (c : CellContract) (newPred : Expr) (cert : ContractCert)
    (hStrengthen : impliesContract newPred c.pred = true)
    (hValid : verifyContractCert newPred cert = true) :
    verifyCellContract (c.relaw newPred cert) = true
  • Monotonic Contract Strengthening (relaw): Unlike untyped dynamic languages where overrides can weaken superclass invariants, cellContract_relaw_sound proves that C4 prototype overrides (mix) preserve or monotonically strengthen locked parent laws (Liskov Behavioral Subtyping).

7.2 Vault Hyperedges, Turn Witnesses, Escrow & Rehydration (Obend/Vault/)

The [lean/Obend/Vault/](file:///Users/ember/dev/obend/lean/Obend/Vault/) subsystem replaces imperative smart-contract account mutation (EVM reentrancy hazards) with atomic multi-party hyperedge turns:

  1. [Obend/Vault/Hyperedge.lean](file:///Users/ember/dev/obend/lean/Obend/Vault/Hyperedge.lean#L1-L634):
  2. A TurnHyperedge binds a set of input object slots (inputs : List VaultObjId), output object states (outputs : List VaultObject), participant signatures (approvals : List ParticipantId), and per-participant format-validated TurnWitnesses (witnesses : List TurnWitness).
  3. Remediating a Council Wave 2 finding, checkTurnHyperedge now verifies that every participant's TurnWitness structurally satisfies the expected Obend.Judge.Format schema (checkTurnWitness : Obend.Judge.Format → TurnWitness → Bool) before admitting the hyperedge (turnHyperedge_witness_format_sound, malformed_witness_blocks_hyperedge).
  4. [Obend/Vault/Escrow.lean](file:///Users/ember/dev/obend/lean/Obend/Vault/Escrow.lean#L1-L1019) & [DragonsExchange.lean](file:///Users/ember/dev/obend/lean/Obend/Vault/DragonsExchange.lean#L1-L453):
  5. Mechanizes multi-party conditional escrow and the Dragons Exchange cross-asset atomic order-book matching engine, proving No-Partial-Fill / All-or-Nothing Atomicity (escrow_atomic_settlement, dragonsExchange_conservation) and Strict Timeout Refund Safety (escrow_expired_refund_exact).
  6. [Obend/Vault/Rehydration.lean](file:///Users/ember/dev/obend/lean/Obend/Vault/Rehydration.lean#L1-L1749):
  7. Formalizes content-addressed snapshot serialization, Merkle-DAG state dehydrate/rehydrate cycles, and schema-evolution lenses (rehydrate_dehydrate_roundtrip, schemaLens_preserves_locked_laws).
  8. [Obend/Vault/HardwareProjection.lean](file:///Users/ember/dev/obend/lean/Obend/Vault/HardwareProjection.lean#L1-L607) & [PhysicalProjection.lean](file:///Users/ember/dev/obend/lean/Obend/Vault/PhysicalProjection.lean#L1-L350):
  9. Connects DeOS Vault objects directly to the Obend.Hardware stack: a hardware IP core or mechanical CAD assembly stored in the Vault carries its 0x0BED silicon/DRC proof receipt as a locked ContractCert, preventing deployment of unverified bitstreams (vault_rejects_unverified_bitstream).

7.3 Double-Entry Conservation & Zoe-Style Offer Safety (Obend/Ledger/Book.lean & Seat.lean)

In [lean/Obend/Ledger/Book.lean](file:///Users/ember/dev/obend/lean/Obend/Ledger/Book.lean#L1-L399) and [lean/Obend/Ledger/Seat.lean](file:///Users/ember/dev/obend/lean/Obend/Ledger/Seat.lean#L1-L545):

  1. 9-Operation Double-Entry Ledger.Book:
  2. Supports .transfer, .escrowLock, .escrowRelease, .escrowRefund, .atomicSwap, .batchTransfer, .feeSplit, .dividendDistribute, and .rebalance.
  3. Proves that all 9 operations strictly conserve total supply per asset (applyLedgerOp_conserves_supply, applyLedgerBatch_conserves_supply) with zero-sum double-entry balance equations and non-negative balance invariants (no_negative_balances).
  4. Agoric Zoe-Style Offer Safety (Ledger.Seat):
  5. Each participant interacts with a contract through an isolated Seat specifying give : Allocation and want : Allocation.
  6. Even if the guest contract code is buggy or adversarial, the host Ledger.Seat kernel enforces Offer Safety (safeAt)—a seat only commits a reallocation if every participant either receives at least their want (satisfiesWant) or gets a full refund of their give (isFullRefund), and total tokens across all seats are strictly conserved (payout_exact):
lean
   -- file:///Users/ember/dev/obend/lean/Obend/Ledger/Seat.lean#L310-L515
   def safeAt (s : Seat) (nextAlloc : Allocation) : Bool :=
     satisfiesWant s.want nextAlloc || isFullRefund s.give nextAlloc

   theorem reallocateSeats_preserves_offer_safety_and_conservation
       (seats : List Seat) (proposed : List Allocation)
       (hCommit : commitSeatReallocation seats proposed = some seats') :
       (∀ i, safeAt (seats[i]!) (seats'[i]!).current = true) ∧
       totalSeatSupply seats' = totalSeatSupply seats

7.4 Simplex 3-Hop BFT Consensus, Epistemic Clearing & Trace Collapse (Obend/Consensus/ & Obend/Fold/Collapse.lean)

  1. Simplex BFT Consensus ([lean/Obend/Consensus/Simplex.lean](file:///Users/ember/dev/obend/lean/Obend/Consensus/Simplex.lean#L1-L814)):
  2. Mechanizes the Simplex BFT protocol (Chan & Pass) with $n = 3f + 1$ validators, quorum threshold $q = 2f + 1$, explicit dummy-block view timeouts (DummyCert), 2-hop notarization (NotarCert), and 3-hop finalization (FinalCert).
  3. Using the pigeonhole quorum intersection lemma (quorum_intersection_honest: two quorums of size $\ge 2f+1$ out of $3f+1$ intersect in at least $f+1$ validators, hence at least 1 non-equivocating honest validator), proves notarized_unique and finalized_safety:
lean
   -- file:///Users/ember/dev/obend/lean/Obend/Consensus/Simplex.lean#L540-L780
   theorem notarized_unique (cfg : SimplexConfig) (view : Nat) (b1 b2 : BlockHash)
       (hHonest : HonestMajorityAssumptions cfg view)
       (hNotar1 : IsNotarized cfg view b1) (hNotar2 : IsNotarized cfg view b2) :
       b1 = b2

   theorem finalized_safety (cfg : SimplexConfig) (v1 v2 : Nat) (b1 b2 : BlockHash)
       (hFinal1 : IsFinalized cfg v1 b1) (hNotar2 : IsNotarized cfg v2 b2)
       (hLe : v1 ≤ v2) (hNoSkip : NoSkipCertificateInView cfg v1) :
       AncestorOrEqual b1 b2
  1. Epistemic Consensus & Proper Scoring Rules ([lean/Obend/Consensus/Epistemic.lean](file:///Users/ember/dev/obend/lean/Obend/Consensus/Epistemic.lean#L1-L468)):
  2. Formalizes prediction/oracle markets and peer-review clearing using strictly proper Brier quadratic scoring rules (brierScore), proving truthfulness incentive-compatibility (brier_strictly_proper_truthful_max) and sybil-split invariance under stake-weighted aggregation (sybil_split_invariance).
  3. Semantic Trace Folding ([lean/Obend/Fold/Collapse.lean](file:///Users/ember/dev/obend/lean/Obend/Fold/Collapse.lean#L1-L420)):
  4. Proves that internal stuttering steps inside an Obend.Fold boundary collapse to a single canonical cryptographic receipt hash (traceHash_invariant_under_stutter), enabling Mina/Dregg-style succinct recursive step folding where external verifiers check only the boundary receipt without replaying intermediate reduction steps.

7.5 The Rust Runtime Crates & Sandstorm Capability Sandbox (crates/ & sandstorm/)

  1. [crates/obend-ffi/src/lib.rs](file:///Users/ember/dev/obend/crates/obend-ffi/src/lib.rs#L1-L44):
  2. C-ABI bridge (obend_eval_core4, obend_verify_receipt) linking the compiled Lean 4 runtime into the Rust workspace.
  3. [crates/obend-node/src/lib.rs](file:///Users/ember/dev/obend/crates/obend-node/src/lib.rs#L1-L4628) (4,628 lines):
  4. Production Rust implementation of the DeOS node daemon:
  5. VaultStore: Content-addressed Merkle object store with dehydrated/rehydrated Core4 prototype snapshots and TurnHyperedge transaction pool.
  6. SimplexEngine: Asynchronous 3-hop Simplex BFT state machine with Ed25519 quorum certificate aggregation, view-change timers, and deterministic Ledger.Book / Ledger.Seat state transitions.
  7. SiliconOffloadDriver: Dispatches compute-intensive Leaf.Book reductions and 0x0BED hardware receipt checks to the hardware/rust-ffi & Verilator/FPGA backend.
  8. [crates/obend-sandbox/src/lib.rs](file:///Users/ember/dev/obend/crates/obend-sandbox/src/lib.rs#L1-L20) & [sandstorm/](file:///Users/ember/dev/obend/sandstorm/):
  9. Implements the 5-Ring Capability Sandbox (R0 Pure Leaf.Book Kernel $\to$ R1 Deterministic Core4 $\to$ R2 Local Slot/Fold Workbook $\to$ R3 Capability-Gated Sandstorm Grain $\to$ R4 Host Hardware/FPGA Driver).
  10. [sandstorm/sandstorm-pkgdef.capnp](file:///Users/ember/dev/obend/sandstorm/sandstorm-pkgdef.capnp#L1-L81) and [sandstorm/seccomp/resident-web.policy](file:///Users/ember/dev/obend/sandstorm/seccomp/resident-web.policy#L1-L69) package each OBend workbook/contract instance as an isolated Sandstorm.io / Bubblewrap (bwrap) capability grain with zero ambient network authority and strict seccomp-bpf syscall filtering (read, write, mmap, futex, exit_group; blocking socket, connect, execve, ptrace, mount).

8. The Multimodel Council Audit (2026-11-01) & The 15-Lane Remediation Wave (2026-11-02)

One of the most revealing primary-source artifacts in the repository is the pair of Multimodel Council documents in [review/COUNCIL-BRIEF-20261101.md](file:///Users/ember/dev/obend/review/COUNCIL-BRIEF-20261101.md#L1-L64) and [review/FABLE-COUNCIL-20261101.md](file:///Users/ember/dev/obend/review/FABLE-COUNCIL-20261101.md#L1-L742) (alongside [obend-astra-decisions/review/DECISIONS-20261031.md](file:///Users/ember/dev/obend-astra-decisions/review/DECISIONS-20261031.md#L1-L81) and [obend-astra-decisions/astra/ASTRA-EFFECT-LAWS-20261031.md](file:///Users/ember/dev/obend-astra-decisions/astra/ASTRA-EFFECT-LAWS-20261031.md#L1-L682)).

At commit 7c699ca1 (2026-11-01 16:50), Ember asked Gemini 4 Argon and Claude Fable 5.1 to audit the entire 350-file Lean codebase without mercy:

From [review/COUNCIL-BRIEF-20261101.md](file:///Users/ember/dev/obend/review/COUNCIL-BRIEF-20261101.md#L48-L62): "Are any theorems vacuous, trivialized by definitions, or proving weaker statements than their names suggest? Where does the Lean 4 mechanization genuinely carry the weight, and where is it still a sketch?"

8.1 What the Council Found vs. How Commits 8f9f822c & 23a76513 Closed Every Gap

Rather than leaving the Council's findings as open errata, Ember immediately launched a 15-lane remediation wave (8f9f822c on 2026-11-01 17:45 and 23a76513 on 2026-11-02 05:51, adding +33,350 / -602 lines across 110 files) that systematically replaced every shallow or concrete-only proof identified by the Council with universal structural theorems and negative #tooth mutation tests:

Council Finding (FABLE-COUNCIL-20261101.md)Remediated Module & Exact Theorem Added in 8f9f822c / 23a76513
F1: RealAnalysis.lean had concrete interval tests (decide +kernel) instead of a universally quantified Fundamental Theorem of Interval Arithmetic (∀ x ∈ I, evalPt e x ∈ evalInterval e I).[Obend/Analysis/RealAnalysis.lean](file:///Users/ember/dev/obend/lean/Obend/Analysis/RealAnalysis.lean#L120-L445): Proved universal Interval.add_mem, neg_mem, sub_mem, mul_mem (4-corner case split), sqr_mem (non-negativity tightening), and evalInterval_sound over arbitrary RealExpr ASTs + 3 #tooth negative tests.
F2: QuantumMatter.lean checked coupler array length (couplers.length = 3) rather than proving the couplers realize the $3:4:3$ Krawtchouk quotient ratios.[Obend/Hardware/QuantumMatter.lean](file:///Users/ember/dev/obend/lean/Obend/Hardware/QuantumMatter.lean#L1210-L1415): Defined couplerRealizesQuotientRatio, synthesized exact $375000:500000:375000\,\text{ppm}$ couplers, proved compileEquitableToPhotonicArray_ratio_sound, and proved wrong_coupler_refused_by_krawtchouk_ratio.
F3: GeometryCAM.lean omitted .neg on the SSA tape and lacked backward-liveness dead-code compaction after interval box pruning.[Obend/Hardware/GeometryCAM.lean](file:///Users/ember/dev/obend/lean/Obend/Hardware/GeometryCAM.lean#L1650-L2020): Added .neg to SsaTapeOp, implemented pruneSsaTapeForBox + compactSsaTape (liveRegsBackward), and proved universal soundness prune_and_compact_ssa_tape_sound.
F4: OpenHypergraph.lean only differentiated single primitive operations rather than functorially accumulating cotangents across multi-edge graphs with fanout, and lacked pipelined RTL stage insertion.[Obend/Hardware/OpenHypergraph.lean](file:///Users/ember/dev/obend/lean/Obend/Hardware/OpenHypergraph.lean#L1380-L1850): Implemented whole-graph compileGraphAdjoint with automatic .add fanout cotangent accumulation (compileGraphAdjoint_multiEdge_sound) and synchronous wavefront pipelining (compileHypergraphToRtlPipelined_latency_exact).
F5: LeanKernel.lean used tag-only DeclKind checks and lacked structural kernelIsDefEqFull ($\beta\delta\iota\zeta$, $\eta$, Prop proof irrelevance) and term-level LExpr lowering.[Obend/Lower/LeanKernel.lean](file:///Users/ember/dev/obend/lean/Obend/Lower/LeanKernel.lean#L1400-L2180): Implemented kernelIsDefEqFull, proved kernelIsDefEqFull_refl, kernelIsDefEqFull_eta_lam, kernelIsDefEqFull_prop_proofIrrel, kernelCheckDecl_defEqFull_in_place_sound, and runLExprSteps_sound.
F6: ReductionMachine.lean modeled isolated tiles without a multi-hop NoC flit/credit conservation proof or an explicit Obend.Slot DPR guard.[Obend/Hardware/ReductionMachine.lean](file:///Users/ember/dev/obend/lean/Obend/Hardware/ReductionMachine.lean#L1100-L1710): Added NocFabric, proved stepNocRouter_conserves_flits_and_credits & noc_step_conserves_flits, and defined dprTileSlot : Slot LeafPin TileBitstreamCandidate (dprTile_moved_pin_blocks).
F7: BendTT.lean compiled Leaf.Book ASTs into BendTT terms without proving operational simulation against a target BendTT reducer.[Obend/Leaf/BendTT.lean](file:///Users/ember/dev/obend/lean/Obend/Leaf/BendTT.lean#L1150-L1480): Implemented stepB? and runB, and proved compileToBendTT_embedB, stepB?_sound, and book_to_bendtt_sound.
F8: Equiv/Contextual.lean lacked a mechanized call-by-need cost model for open-recursive prototype knots (fix (mix p q)).[Obend/Equiv/Clairvoyant.lean](file:///Users/ember/dev/obend/lean/Obend/Equiv/Clairvoyant.lean#L1-L2601): Mechanized 2,601-line Hackett–Hutton clairvoyant call-by-need cost semantics (Run .eval/.head/.knot/.wave/.cell, clairvoyant_need_le_cbv_cost).
F9: Vault/Hyperedge.lean did not validate per-turn participant witnesses against Obend.Judge.Format.[Obend/Vault/Hyperedge.lean](file:///Users/ember/dev/obend/lean/Obend/Vault/Hyperedge.lean#L240-L580): Added witnesses : List TurnWitness, checkTurnWitness, and turnHyperedge_witness_format_sound.

9. Verification & Test Suite Inventory (TEST_READY.md)

As documented in [TEST_READY.md](file:///Users/ember/dev/obend/TEST_READY.md#L1-L98) and verified against HEAD 23a76513:

  1. Lean 4 Proof Spine ([lean/Obend/All.lean](file:///Users/ember/dev/obend/lean/Obend/All.lean)):
  2. 452+ Lean modules, 62,167+ environment constants, 0 sorryAx, 0 custom axioms, enforced at build time by #assert_axioms_tree Obend.All ([lean/Obend/Test/AxiomAudit.lean](file:///Users/ember/dev/obend/lean/Obend/Test/AxiomAudit.lean)), which walks the transitive closure of every theorem in Obend.All and fails compilation if anything outside {propext, Quot.sound, Classical.choice} is encountered.
  3. Negative-Mutation #tooth Gate ([lean/Obend/Test/Teeth.lean](file:///Users/ember/dev/obend/lean/Obend/Test/Teeth.lean)):
  4. Verifies that every safety gate (Slot invalidation, C4 monotonicity, Prototype Provenance LT4, Offer Safety safeAt, Simplex quorum uniqueness, Interval multiplication, Krawtchouk coupler ratios, DPR bitstream pinning, and TurnWitness format validation) actively rejects malformed or mutated inputs.
  5. Silicon & Hardware Co-Simulation ([lean/tests/run-hardware.py](file:///Users/ember/dev/obend/lean/tests/run-hardware.py) & [tests/silicon_elab/run_verilator_cosim.py](file:///Users/ember/dev/obend/tests/silicon_elab/run_verilator_cosim.py)):
  6. Executes end-to-end Verilator cycle-accurate RTL simulation, Z3 SMT2 formal equivalence checking (QF_BV and QF_NRA), multiphysics C++ electro-thermal simulation, and 39-byte Tag 0x0BED CBOR proof certificate verification.
  7. Rust Workspace (Cargo.toml: obend-ffi, obend-gui, obend-node, obend-sandbox, hardware/rust-ffi):
  8. Full integration suite across the DeOS Simplex BFT node, Vault hyperedge clearing, Zoe-style seat settlement, 10-projection CAD/EDA viewport, and Sandstorm/Bubblewrap R0–R4 capability containment.
Dossier 03 (§1–§3) · Multi-Vendor TEE Verifier (`NitroVerifier`, `SnpVerifier`, `TdxVerifier`), GPU E2EE & 377/1,125 Residual Trust Proof
Working field notes & source index below, with theorem anchors, code pointers, git history, and open questions.

Hardware Roots of Trust, Multi-Vendor TEE Attestation, Confidential GPU E2EE, Bare-Metal seL4 Microkit, & Post-Quantum Object-Capability Security

Primary-Source Technical Dossier Scope: breadstuffs (tee-verify, tee-produce, cell::tee_attest, dregg-chutes-e2ee, attest-check, sel4/, grain-jail, macaroon, token, dregg-auth, dregg-pq, pqvrf, credentials, intent, audit, starbridge-apps), degg-research (experiments/shielded-baseline), and nanodregg (sandbox).


1. Multi-Vendor Hardware TEE Quote Verifier & Enclave Producer (tee-verify, tee-produce, cell::tee_attest)

1.1 Substrate Integration (dregg-cell::tee_attest)

Inside the cell layer (cell/src/tee_attest.rs), hardware TEE attestation is integrated as a canonical WitnessedPredicateKind::Custom verifier keyed by the domain-separated verification key tee_predicate_vk():

rust
pub const TEE_ATTEST_DOMAIN: &[u8] = b"dregg-tee-attestation-verifier-v1";

pub fn tee_predicate_vk() -> [u8; 32] {
    canonical_predicate_vk(TEE_ATTEST_DOMAIN)
}

Quotes from all supported hardware vendors share a 1-byte discriminant prefix (TeeQuoteKind) followed by the vendor-native attestation payload (encode_tee_proof, decode_tee_proof):

rust
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[repr(u8)]
pub enum TeeQuoteKind {
    SevSnp = 1,
    IntelTdx = 2,
    IntelSgx = 3,
    AwsNitro = 4,
}

TCB evaluation across platforms is normalized into TcbStatus and TeeReportClaims:

rust
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum TcbStatus {
    /// Platform exposes a TCB version and it meets the verifier's pinned minimum.
    MetPolicy,
    /// Platform exposes a TCB version and it falls below the verifier's pinned minimum.
    BelowPolicy,
    /// Platform's attestation document carries NO TCB-version rung (e.g. AWS Nitro).
    NoPolicyOnPlatform,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TeeReportClaims {
    /// 32-byte enclave image measurement (`MRENCLAVE`, `MRTD`, `MEASUREMENT`, or folded `PCR0..2`).
    pub measurement: [u8; 32],
    /// 32-byte user-supplied `report_data` bound into the hardware signature.
    pub report_data: [u8; 32],
    /// Platform TCB status relative to the verifier's pinned policy.
    pub tcb: TcbStatus,
}

TcbStatus::as_token() emits wire strings "met-pinned-minimum", "below-pinned-minimum", and "no-tcb-rung-on-this-platform"; TcbStatus::is_refusal() returns true iff matches!(self, Self::BelowPolicy).

The cell-layer predicate adapter TeeWitnessedPredicateVerifier is fail-closed by default (inner: Option<Arc<dyn TeeAttestationVerifier>> is None in TeeWitnessedPredicateVerifier::fail_closed()). When a concrete verifier is installed, TeeWitnessedPredicateVerifier::verify enforces four conditions:

  1. Decodes (kind, report_bytes) via decode_tee_proof(proof_bytes).
  2. Calls verifier.verify_report(kind, report_bytes) to validate the hardware vendor's cryptographic signature chain.
  3. Checks &claims.measurement == commitment (the cell's StateConstraint::Witnessed 32-byte commitment must equal the enclave's code measurement).
  4. Checks claims.report_data == Self::input_commitment(input)? (where PredicateInput::FieldElement(v) from grain_turn::ATTESTATION_SLOT is SHA-256 hashed via Sha256::digest(b"dregg-tee-field-input-v1:" || v.to_le_bytes()) or passed raw as PredicateInput::Bytes32) and !claims.tcb.is_refusal().

1.2 AWS Nitro Enclaves (NitroVerifier)

Implemented in tee-verify/src/lib.rs (introduced in commit 17b6e5539, 2026-07-11, hardened in commit a9d5df4db, 2026-09-30), NitroVerifier verifies AWS Nitro Hypervisor attestation documents without any external network calls:

  • Pinned Hardware Root of Trust: AWS_NITRO_ROOT_PEM embeds tee-verify/src/aws_nitro_root_g1.pem (CN=aws.nitro-enclaves, O=Amazon, C=US, valid 2019-10-28T13:22:05Z to 2049-10-28T14:22:05Z, P-384 public key, SHA-256 fingerprint 641a0321a3e244efe456463195d606317ed7cdcc3c1756e09893f3c68f79bb5b).
  • CBOR COSE_Sign1 & AttDoc Parsing:
  • CoseSign1 is deserialized via ciborium as a 4-tuple (ByteBuf, ciborium::Value, ByteBuf, ByteBuf) representing [protected, unprotected, payload, signature], optionally wrapped in CBOR tag 18. The signature length must be exactly 96 bytes (r || s, 48 bytes each for P-384).
  • AttDoc is deserialized from payload:
rust
    struct AttDoc {
        module_id: String,
        digest: String,
        timestamp: u64,
        pcrs: BTreeMap<u8, ByteBuf>,
        certificate: ByteBuf,
        cabundle: Vec<ByteBuf>,
        #[serde(default)]
        public_key: Option<ByteBuf>,
        #[serde(default)]
        user_data: Option<ByteBuf>,
        #[serde(default)]
        nonce: Option<ByteBuf>,
    }
  • Requires !doc.module_id.is_empty() and doc.digest == "SHA384".
  • X.509 Certificate Chain Verification (verify_cert_chain):
  • Parses pinned_root_der from AWS_NITRO_ROOT_PEM and asserts doc.cabundle[0].as_slice() == pinned_root_der.contents.as_slice() (byte-exact root match).
  • Constructs the full chain [cabundle[0], cabundle[1..], certificate] and parses every DER certificate via x509-parser.
  • Checks X.509 validity windows (cert.validity().is_valid_at(t)) at ref_time = doc.timestamp / 1000 (converting Nitro's millisecond timestamp to Unix seconds).
  • Verifies every parent→child link window[1].verify_signature(Some(window[0].public_key())).
  • ES384 COSE_Sign1 Signature Verification (verify_cose_sig):
  • Serializes RFC 8152 §4.4 Sig_structure = ["Signature1", protected, b"", payload] to CBOR bytes.
  • Extracts the leaf certificate's P-384 SEC1 public key (p384::ecdsa::VerifyingKey::from_sec1_bytes) and verifies the 96-byte ECDSA-P384/SHA-384 signature (p384::ecdsa::Signature::from_slice(sig_bytes)).
  • Measurement Folding & report_data Extraction:
  • fold_pcrs verifies that PCR0 (enclave image), PCR1 (Linux kernel + bootstrap), and PCR2 (application) are each present and 48 bytes (SHA-384), then folds them into a 32-byte commitment: $$\text{measurement} = \text{SHA-256}(\text{PCR}_0 \mathbin{\Vert} \text{PCR}_1 \mathbin{\Vert} \text{PCR}_2)$$
  • extract_report_data requires doc.user_data to be Some and at least 32 bytes; if doc.user_data is 32 bytes it copies it directly into claims.report_data (rejecting documents with missing user_data so an empty user_data can never collide with [0u8; 32]).
  • Sets claims.tcb = TcbStatus::NoPolicyOnPlatform because Nitro attestation documents do not expose a numeric TCB SPL vector.
  • Document Freshness Enforcement (check_nitro_freshness):
  • Added in commit a9d5df4db to close audit finding F10: fails closed if now_secs == 0, if doc.timestamp == 0, if doc_ts > now_secs + MAX_FUTURE_SKEW_SECS (60 seconds), or if now_secs - doc_ts > max_age_secs (default MAX_DOC_AGE_SECS = 3600).

1.3 AMD SEV-SNP (SnpVerifier)

Implemented in tee-verify/src/snp.rs and tee-verify/src/snp_chain.rs (introduced in commit 8ce36ba16, 2026-07-11; RSA-PSS ARK/ASK chain added in 261a06f8d, 2026-07-13; policy/VMPL/corroboration/CRL gates added in 4d98292c2 and 3bf5e041a, 2026-09-30), SnpVerifier validates AMD SEV-SNP hardware attestation reports:

Fixed Binary Layout (ATTESTATION_REPORT, 1184 bytes = 0x4A0)

Per AMD Publication #56860 (SEV-SNP ABI Specification, Table 22), SnpAttestationReport::parse parses the exact little-endian offsets (snp.rs:69-81):

ConstantByte OffsetSizeField & Verification Rule
OFF_VERSION0x0004B (u32)Report format version; must be 2 or 3 (MIN_REPORT_VERSION = 2, MAX_REPORT_VERSION = 3)
OFF_GUEST_SVN0x0044B (u32)Guest Security Version Number; checked against SnpPolicy::min_guest_svn
OFF_POLICY0x0088B (u64)Guest POLICY bitfield (Table 9: bit 16 SMT, bit 17 RESERVED_MBO, bit 18 MIGRATE_MA, bit 19 DEBUG, bit 20 SINGLE_SOCKET)
OFF_VMPL0x0304B (u32)Virtual Machine Privilege Level (0..=3); must be 0 under default policy
OFF_SIGNATURE_ALGO0x0344B (u32)Must equal SIG_ALGO_ECDSA_P384_SHA384 = 1
OFF_CURRENT_TCB0x0388B (u64)Current platform TCB_VERSION
OFF_KEY_INFO0x0484B (u32)Bits [4:2] (SIGNING_KEY = (key_info >> 2) & 0b111) must equal SIGNING_KEY_VCEK = 0 (VLEK 1 rejected)
OFF_REPORT_DATA0x05064BGuest-supplied REPORT_DATA; report_data_32() extracts [0x050..0x070]
OFF_MEASUREMENT0x09048B384-bit launch digest (MEASUREMENT); folded_measurement() computes SHA-256(measurement)
OFF_HOST_DATA0x0C032BHypervisor-supplied HOST_DATA
OFF_REPORTED_TCB0x1808B (u64)REPORTED_TCB bound into the VCEK certificate extensions
OFF_CHIP_ID0x1A064BUnique 512-bit processor CHIP_ID
OFF_SIGNATURE0x2A0512BECDSA P-384 signature over &raw[..0x2A0]: R at 0x2A0..0x2E8 (72B LE), S at 0x2E8..0x330 (72B LE)

In verify_snp_signature, the verifier checks that the upper 24 padding bytes ([48..72]) of both 72-byte little-endian R and S buffers are all zero, reverses the lower 48 bytes ([..48]) of each from little-endian to big-endian SEC1 scalar order, constructs p384::ecdsa::Signature::from_scalars(r_be, s_be), and verifies &raw_report[..0x2A0] (SIGNED_BODY_LEN = 672 bytes) using ECDSA-P384 with SHA-384.

Processor Generation TCB Layout (TcbVersion)

TcbVersion handles both the legacy Milan/Genoa 8-byte layout and the Turin 8-byte layout:

  • Milan / Genoa (from_le_u64): b[0] = bootloader, b[1] = tee, b[2..6] = reserved, b[6] = snp, b[7] = microcode (fmc = 0).
  • Turin (from_le_u64_turin): b[0] = fmc, b[1] = bootloader, b[2] = tee, b[3] = snp, b[4..7] = reserved, b[7] = microcode.
  • TcbVersion::meets(&self, floor: &Self) enforces component-wise dominance:
rust
  self.fmc >= floor.fmc
      && self.bootloader >= floor.bootloader
      && self.tee >= floor.tee
      && self.snp >= floor.snp
      && self.microcode >= floor.microcode

ARK → ASK → VCEK Certificate Chain & X.509 OIDs (snp_chain.rs)

tee-verify/src/snp_chain.rs embeds the DER-encoded AMD Root Key (ARK) and AMD SEV Signing Key (ASK) bundles fetched from https://kdsintf.amd.com/vcek/v1/{Product}/cert_chain on 2026-07-13 for all three EPYC generations (SnpProduct):

ProductFamily/ModelPinned ARK SHA-256Pinned ASK SHA-256
Milan (Zen 3)Family 19h, Model 00h–0Fh69D063B45344D26A2E94E1F4210DE49EF555308287D4C174445C95639A540BCD767B409B0DC90F5D7F2E2CE3E63D0C8B84E8A3122A557D5D56D3B1B6A82C4C38
Genoa (Zen 4)Family 19h, Model 10h–1Fh / A0h–AFh4C6598D19C18719C5DFD4A7D335F674E5BFE1D8F800CEA2CF270C10D103DB2F184B8F522B5B9A77C779A2C8C60C90F6623082917D981E5A9786E9244D4D34394
Turin (Zen 5)Family 1Ah, Model 00h–1Fh1F084161A44BB6D93778A904877D4819CAFA5D05EF4193B2DED9DD9C73DD3F6A94C13A3B3F9B7B2B1B6877F9E9C69F63922416C7476645F3F1B84F0F7F4D5D0F

verify_vcek_against_amd_root executes a 5-stage verification:

  1. ARK Self-Signature: Verifies SHA256(ark_der) == product.ark_sha256() and checks the ARK self-signature via verify_rsassa_pss_sha384 (OID 1.2.840.113549.1.1.10, RSA-4096 PSS with SHA-384 digest, MGF1-SHA-384, 48-byte salt via rsa::pss::VerifyingKey::<Sha384>).
  2. ASK ← ARK Signature: Asserts ask.issuer() == ark.subject() and verifies the RSA-4096 PSS SHA-384 signature of the ASK against the ARK's modulus/exponent.
  3. VCEK ← ASK Signature: Asserts vcek.issuer() == ask.subject(), rejects CA VCEKs (vcek.is_ca()), and verifies the signature on vcek.tbs_certificate against the ASK's RSA-4096 PSS key.
  4. Leaf P-384 Public Key Extraction: Requires algorithm OID 1.2.840.10045.2.1 (id-ecPublicKey) with curve parameter OID 1.3.132.0.34 (secp384r1).
  5. AMD VCEK X.509 Extensions (extract_vcek_extensions): Parses AMD Private Enterprise Number 3704 (1.3.6.1.4.1.3704.1.*) DER INTEGER / OCTET STRING extensions:
  6. 1.3.6.1.4.1.3704.1.3.1 (blSPL — Bootloader SVN)
  7. 1.3.6.1.4.1.3704.1.3.2 (teeSPL — PSP OS / TEE SVN)
  8. 1.3.6.1.4.1.3704.1.3.3 (snpSPL — SNP firmware SVN)
  9. 1.3.6.1.4.1.3704.1.3.8 (ucodeSPL — Microcode patch level)
  10. 1.3.6.1.4.1.3704.1.3.9 (fmcSPL — Turin FMC SVN; required on Turin)
  11. 1.3.6.1.4.1.3704.1.4 (hwID — 64-byte chip hardware ID)

Report↔VCEK Corroboration & Guest Policy Enforcement (SnpPolicy)

In SnpVerifier::verify_snp_at:

  • Report↔VCEK Cross-Check (Audit F2): Requires report.reported_tcb == vcek.tcb (snp.rs:554-560), report.chip_id != [0u8; 64] (rejecting MaskChipId=1), and report.chip_id == vcek.hw_id (snp.rs:564-574), preventing an attacker from pairing a report from a downgraded chip with a VCEK from a patched chip.
  • Guest Policy & VMPL Gates (Audit F1): SnpPolicy::default() enforces:
  • POLICY bit 17 (POLICY_RESERVED_MBO = 1 << 17) must be 1 and bits 63:26 must be 0 (snp.rs:581-594).
  • POLICY bit 19 (POLICY_DEBUG = 1 << 19) must be 0 (!policy.allow_debug, snp.rs:595-600) — any debug-enabled guest (where hypervisor SNP_DBG_DECRYPT/SNP_DBG_ENCRYPT can read/write private memory) is unconditionally refused.
  • POLICY bit 18 (POLICY_MIGRATE_MA = 1 << 18) must be 0 (!policy.allow_migrate_ma, snp.rs:601-606).
  • report.vmpl < 4 and (policy.allowed_vmpls & (1 << report.vmpl)) != 0 where allowed_vmpls = 0b0001 (VMPL == 0 only, rejecting less-privileged VMPL 1..3 paravisor rings, snp.rs:608-620).
  • report.guest_svn >= policy.min_guest_svn (snp.rs:621-627).
  • vcek.tcb.meets(&policy.min_tcb) (evaluated against the VCEK's X.509 extension TCB, not the report body's reported_tcb).

1.4 Intel TDX / SGX DCAP (TdxVerifier)

Implemented in tee-verify/src/tdx.rs, TdxVerifier verifies Intel TDX v4 and v5 quotes over Intel SGX DCAP (dcap-qvl v0.5.2):

  • Pinned Root Certificate: INTEL_SGX_ROOT_CA_SHA256 pins the SHA-256 digest of the DER-encoded Intel SGX Root CA (CN=Intel SGX Root CA, O=Intel Corporation, C=US):
text
  44A0196B2B99F889B8E149E95B807A350E7424964399E885A7CBB8CCFAB674D3
  • Quote Header & DCAP Verification (verify_tdx_core):
  • Parses the quote via dcap_qvl::quote::Quote::parse(report_bytes) and checks quote.header.tee_type == TEE_TYPE_TDX (0x0000_0081), rejecting SGX quotes (0x0000_0000) on the TDX lane.
  • Parses the PEM chain in collateral.root_ca_pem_chain, locates the self-signed root (cert.Subject == cert.Issuer), and checks SHA256(root.raw_der) == INTEL_SGX_ROOT_CA_SHA256.
  • Invokes dcap_qvl::verify::verify(report_bytes, &self.collateral, self.now_secs) to verify the QE Report ECDSA signature, PCK Certificate Chain, QE Identity, and TCB Info JSON collateral.
  • Extracts the TD10 / TD15 report (quote.report.as_td10()), packing mr_td (48B), rt_mr0 (48B), rt_mr1 (48B), rt_mr2 (48B), rt_mr3 (48B), and report_data (64B) into TdxVerifiedReport.
  • Measurement Folding & TCB Status:
  • TdxVerifiedReport::folded_measurement() hashes the 4 static boot registers (excluding runtime RTMR3): $$\text{measurement} = \text{SHA-256}(\text{MRTD} \mathbin{\Vert} \text{RTMR}_0 \mathbin{\Vert} \text{RTMR}_1 \mathbin{\Vert} \text{RTMR}_2)$$
  • Default accepted_statuses contains only {"UpToDate"}; any other FMSPC TCB status (OutOfDate, SWHardeningNeeded, ConfigurationNeeded, Revoked) yields TcbStatus::BelowPolicy, which causes TeeWitnessedPredicateVerifier to refuse the turn.

1.5 Security Audit Findings (docs/TEE-VERIFY-AUDIT-2026-07-25.md)

On 2026-07-25, an internal adversarial security audit (docs/TEE-VERIFY-AUDIT-2026-07-25.md) catalogued 14 findings (F1–F14) across tee-verify, tee-produce, and dregg-discharge-gateway:

  • F1 (CRITICAL — SEV-SNP POLICY / VMPL / GUEST_SVN unvalidated): SnpAttestationReport originally discarded bytes 0x008..0x034, permitting DEBUG=1 or VMPL=3 reports. Remediated in commit 4d98292c2 (2026-09-30) via SnpPolicy.
  • F2 (CRITICAL — SEV-SNP reported_tcb and chip_id not cross-checked against VCEK OIDs): Originally allowed mixing a VCEK from a patched machine with a report from an unpatched machine if signed by the same key, or accepting MaskChipId=1 zeroed chip_id. Remediated in commit 4d98292c2 (snp.rs:554-574).
  • F3 (HIGH — SEV-SNP CRL checking): Added ark_crl_der / ask_crl_der checking on SnpVerifier in commit 4d98292c2 (snp.rs:463-474, 543-552).
  • F10 (MEDIUM — Nitro freshness bypass when now_secs == 0): Remediated in commit a9d5df4db (2026-09-30) so NitroVerifier::new() seeds wall-clock time (SystemTime::now()) and check_nitro_freshness fails closed on now_secs == 0 or future-dated documents.
  • F11 / F12 / F14 (CRITICAL/HIGH — Discharge gateway condition validation): Remediated in commit 551fc897f (2026-09-30).

1.6 Enclave Quote Producer (tee-produce & NitroNsmBackend)

In tee-produce/src/lib.rs and tee-produce/src/nsm.rs (introduced in commit ad33c9247, 2026-07-12):

  • NitroNsmBackend (gated behind --features nitro-nsm on Linux) opens /dev/nsm via aws_nitro_enclaves_nsm_api::driver::nsm_init() (failing closed if fd < 0), issues nsm_process_request(fd, Request::Attestation { user_data: Some(ByteBuf::from(report_data.to_vec())), nonce: None, public_key: None }), closes the descriptor with nsm_exit(fd), and returns the raw COSE_Sign1 bytes from Response::Attestation { document }.
  • QuoteProducer::produce_predicate_proof binds a 32-byte report_data commitment (matching grain_turn::ATTESTATION_SLOT) into the hardware quote and wraps it via encode_tee_proof(self.kind(), &raw).
  • serve_single_request serves the enclave quote over newline-delimited JSON (ProduceRequest { report_data_hex } → ProduceResponse { ok, quote_kind, proof_hex, error }, capped at MAX_FRAME_BYTES = 1 << 20 bytes) across an AF_VSOCK or TCP stream.

2. Confidential GPU Inference & Post-Quantum E2EE (dregg-chutes-e2ee & attest-check)

2.1 Confidential GPU TDX Attestation (dregg-chutes-e2ee/src/attest.rs)

dregg-chutes-e2ee (commits 9d5d06853 2026-07-23, 6f38efbe3 2026-07-26, 4bcb934a3 2026-07-27) implements end-to-end encrypted confidential LLM inference against GPU instances running inside Intel TDX Confidential VMs with NVIDIA H200/B200 TEE GPUs.

Before any prompt is encrypted, attest_chute executes the hardware attestation handshake:

  1. Generates a fresh 32-byte random nonce (nonce_bytes: [u8; 32]) and encodes it as a 64-character lowercase hex string (nonce_hex).
  2. Fetches GET /e2e/instances/{chute_id} (returning instance list with instance_id and e2e_pubkey Base64 ML-KEM-768 public key) and GET /chutes/{chute_id}/evidence?nonce={nonce_hex} (returning per-instance quote Base64 Intel TDX v4 quote, gpu_evidence, and collateral).
  3. Calls verify_instance_evidence, which invokes TdxVerifier::verify_tdx_core(&quote_bytes) followed by TdxVerifier::apply_chutes_bindings.
  4. Anti-MITM Session Binding (chutes_report_data_binding):
  5. Validates that nonce_hex is 64 hex characters and e2e_pubkey_b64 Base64-decodes to exactly CHUTES_MLKEM768_PK_LEN = 1184 bytes (tdx.rs:268-277).
  6. Computes the 32-byte binding hash over the ASCII bytes of the nonce and the Base64 public key: $$\text{expected} = \text{SHA-256}(\text{ascii}(\text{nonce\_hex}) \mathbin{\Vert} \text{ascii}(\text{e2e\_pubkey\_b64}))$$
  7. Verifies in constant time (subtle::ConstantTimeEq) that the hardware-signed TDX quote's report_data[0..32] (at byte offset 568 of the TDX v4 quote) equals expected:
rust
     if report.report_data[..32].ct_eq(&expected).unwrap_u8() != 1 {
         return Err("tdx-verify: Chutes report_data[..32] != SHA256(nonce || e2e_pubkey) — MITM or stale quote".into());
     }
  • This prevents the untrusted API gateway from substituting its own ML-KEM-768 keypair or replaying a stale quote from another session.
  • Measurement Registry & TCB Floor: Checks (mr_td, rt_mr0, rt_mr1, rt_mr2) against ChutesMeasurements and requires report.tcb_ok (unless allow_tcb_ProceedAnyway is explicitly set for dev collateral).
  • Caches the resulting AttestedSession in SessionCache with a 30-minute TTL (DEFAULT_TTL_SECS = 1800) and automatic single-retry eviction on HTTP 466 (instance key rotation).

2.2 Post-Quantum ML-KEM-768 + HKDF-SHA256 + ChaCha20-Poly1305 Envelope (dregg-chutes-e2ee/src/crypto.rs)

Implemented in dregg-chutes-e2ee/src/crypto.rs, prompt encryption and streaming response decryption use NIST FIPS 203 ML-KEM-768 (pqcrypto_mlkem::mlkem768):

  • Key & Wire Sizes (crypto.rs:23-32):
  • MLKEM_PK_SIZE = 1184 bytes
  • MLKEM_SK_SIZE = 2400 bytes
  • MLKEM_CT_SIZE = 1088 bytes
  • NONCE_SIZE = 12 bytes
  • TAG_SIZE = 16 bytes
  • BLOB_HEADER_SIZE = 1100 bytes (1088 + 12)
  • Request Encryption ( build_encrypted_request):
  • Generates a single-use ephemeral ML-KEM-768 keypair (response_pk, response_sk) = mlkem768::keypair() so the enclave can encapsulate its response back to the client.
  • Injects "e2e_response_pk": base64(response_pk) into the JSON request object and compresses the UTF-8 JSON bytes with flate2::write::GzEncoder (Compression::default()).
  • Encapsulates to the attested enclave's instance_pk: (shared_secret, mlkem_ct) = mlkem768::encapsulate(&pk) (shared_secret = 32 bytes, mlkem_ct = 1088 bytes).
  • Derives the 32-byte symmetric key via hkdf_derive_key: $$\text{key}_{\text{req}} = \text{HKDF-SHA256}\bigl(\text{salt} = \text{mlkem\_ct}[0..16],\;\text{ikm} = \text{shared\_secret},\;\text{info} = \texttt{"e2e-req-v1"}\bigr)$$
  • Generates a 12-byte random nonce and encrypts the gzipped payload with ChaCha20Poly1305, serializing the wire envelope as: $$\text{blob} = \text{mlkem\_ct (1088B)} \mathbin{\Vert} \text{nonce (12B)} \mathbin{\Vert} \text{ciphertext} \mathbin{\Vert} \text{poly1305\_tag (16B)}$$
  • Transmits blob to POST https://api.chutes.ai/e2e/invoke with headers X-Chute-Id, X-Instance-Id, and Content-Type: application/octet-stream (client.rs:148-159).
  • Non-Streaming & SSE Streaming Response Decryption (decrypt_response, StreamDecryptor):
  • For non-streaming replies, decapsulates mlkem_ct = blob[..1088] using response_sk, derives key_resp via HKDF-SHA256 with info = b"e2e-resp-v1", decrypts with ChaCha20Poly1305, and gunzips (capped at MAX_DECOMPRESSED_BYTES = 64 * 1024 * 1024 = 64 MiB to prevent gzip-bomb OOM).
  • For SSE streaming replies, the first event data: {"e2e_init": "<b64 mlkem_ct>"} is decapsulated via StreamDecryptor::from_init_b64 using info = b"e2e-stream-v1" (retaining only the 32-byte stream_key), and each subsequent data: {"e2e": "<b64 nonce(12) || ct || tag(16)>"} chunk is authenticated and decrypted via StreamDecryptor::decrypt_chunk_b64.

In commit 6f38efbe3 (2026-07-26, "the attested narration was visible and UNCHECKABLE — now the quote outlives the process, and the rate is the provider's own"), dregg-chutes-e2ee/src/narrator_backend.rs was wired to persist a self-contained TeeProvenanceRecord (raw_quote_b64, collateral, nonce_hex, e2e_pubkey_b64, expected_measurements, tee_provenance_commit_hex) alongside every attested narrator receipt.

The standalone verifier attest-check/src/lib.rs and CLI binary attest-check/src/bin/dungeon-attest-check.rs verify six independent cryptographic provenance links (verify_record):

  1. Link 1 — quote digest (check_quote_digest): Base64-decodes raw_quote_b64, verifies quote_bytes.len() == record.quote_len and quote_bytes.len() >= MIN_TDX_V4_QUOTE_LEN (584), and checks hex(SHA-256(quote_bytes)) == record.quote_sha256_hex.
  2. Link 2 — session binding (check_session_binding): Checks nonce_hex.len() == 64 (valid hex), Base64-decodes e2e_pubkey_b64 and checks pk_bytes.len() == 1184 (ML-KEM-768 public key size), reads report_data[0..32] directly from the TDX v4 quote at byte offset TD10_REPORT_DATA_OFFSET = 568 (48 + 520), and verifies report_data[0..32] == SHA-256(nonce_hex || e2e_pubkey_b64) == record.report_data_32_hex.
  3. Link 3 — measurement registry (check_measurement_registry): Parses the TD10 report body, checks mr_td, rt_mr0, rt_mr1, rt_mr2 against the record's hex fields, checks SHA-256(MRTD || RTMR0 || RTMR1 || RTMR2) == record.folded_measurement_hex, and verifies membership in expected_measurements (ChutesMeasurements).
  4. Link 4 — receipt commitment (check_receipt_commitment): Recomputes the domain-separated BLAKE3 receipt commitment (TeeProvenanceRecord::recompute_commit_hex, domain "dungeon-on-dregg/tee-provenance-v1:") over (chute_id, instance_id, quote_sha256_hex, folded_measurement_hex, report_data_32_hex, tcb_status, verified_at_unix_ms) and checks equality with tee_provenance_commit_hex.
  5. Link 5 — Intel root pin (check_intel_root_pin): Parses collateral.root_ca_pem_chain, locates the self-signed root (cert.Subject == cert.Issuer), and verifies SHA-256(root.raw_der) == INTEL_SGX_ROOT_CA_SHA256 (44a0196b...674d3).
  6. Link 6 — DCAP signature chain (check_dcap_chain): Reconstructs TdxVerifier with the embedded collateral at verified_at_unix_ms / 1000 (with a 60s skew fallback for leaf quote issuance skew) and runs verifier.verify_tdx_core(&quote_bytes).

The CLI (dungeon-attest-check) maps OverallStatus to deterministic exit codes: 0 (Verified — all 6 links PASS), 1 (Broken — any link FAIL), 2 (CLI usage / I/O error), and 3 (Unauthenticated — Link 6 SKIP when no offline collateral bundle was captured).


3. Why TEE Alone Is Not Enough (degg-research Residual Trust Proof)

In /Users/ember/dev/degg-research, Ember proved mathematically and empirically why a hardware TEE / shielded dark pool without a zero-knowledge conservation and uniform-clearing proof leaves a massive residual trust surface.

3.1 The dark-fba/n4-k4-q15/v0 Model & price_tie_low Witness

Tracked in docs/VERDICTS.md (Verdicts V3 and V4, commit ac77a4d, 2026-08-18) and experiments/shielded-baseline/tests/residual_trust.rs:

  • Market Shape (dark-fba/n4-k4-q15/v0):
  • SLOT_COUNT = 4 order slots (i ∈ {0, 1, 2, 3}), 4 owners (owner_id = i).
  • TICK_COUNT = 4 discrete price ticks (0, 1, 2, 3), plus ClearedTick::NoCross (5 total tick states).
  • QUANTITY_MAX = 15 (q_i ∈ 0..=15), so maximum single-side aggregate quantity is MAX_SIDE_TOTAL = 4 * 15 = 60 (owner.rs:9).
  • The price_tie_low() Batch (tests/common/mod.rs:28-36):
  • Slot 0: BookOrder::exact(0, Side::Buy, limit_tick = 2, quantity = 4)
  • Slot 1: BookOrder::exact(1, Side::Sell, limit_tick = 1, quantity = 4)
  • Slot 2: padding Side::Buy, limit_tick = 0, quantity = 0
  • Slot 3: padding Side::Sell, limit_tick = 3, quantity = 0
  • Honest uniform batch clearing result: ClearedTick::Tick(1), volume = 4, fills = [4, 4, 0, 0].

3.2 What Each Participant Can Check Locally (owner::audit)

In a shielded / TEE-only dark pool without a validity proof, each participant $i$ sees only the public batch header (cleared_tick, volume, delivery_root, batch_digest) and their own private fill opening fill_i (with Merkle path to delivery_root). In experiments/shielded-baseline/src/owner.rs, each owner runs the strongest possible 8-point local audit (owner::audit):

  1. BatchDigestMismatch: header digest matches the committed order slots.
  2. PublicationInvalid: volume <= SLOT_COUNT * QUANTITY_MAX (60) and NoCross ==> volume == 0.
  3. InclusionFailed: Merkle inclusion proof of (slot, owner_id, fill_i, salt_i) against delivery_root.
  4. Overfill: fill_i <= order.quantity.
  5. BelowMinimum: fill_i == 0 || fill_i >= order.min_fill.
  6. VolumeBelowFill: fill_i <= header.volume (since a single participant's fill cannot exceed total cleared volume).
  7. CrossedWithoutFill: if header.cleared_tick == NoCross, fill_i == 0; if Tick(p) is worse than order.limit_tick, fill_i == 0.
  8. ProRataImplausible (pro_rata_feasible): if the order is eligible at Tick(p), checks whether there exists any hypothetical aggregate side total $T \in [\max(q_i, V), 60]$ and hypothetical pre-OrderId-tiebreak prefix $B \in [0, \min(\text{slot}, (V \cdot T) \bmod T)]$ such that integer pro-rata rationing $\lfloor \frac{V \cdot q_i}{T} \rfloor + \mathbb{I}[\text{tiebreak}]$ produces fill_i.

3.3 The Exhaustive Forgery Theorem: 377 out of 1,125 Outcomes Survive

In exhaust_price_tie_low_forgeries, the test enumerates the entire candidate outcome space for price_tie_low():

  • $5$ cleared-tick values (NoCross, Tick(0), Tick(1), Tick(2), Tick(3))
  • $9$ volume values ($V \in 0..=8$, where $8 = \sum q_i$)
  • $5$ fill values for Buyer 0 ($f_0 \in 0..=4$)
  • $5$ fill values for Seller 1 ($f_1 \in 0..=4$)
  • $1$ fill value for Padding 2 ($f_2 = 0$) and $1$ fill value for Padding 3 ($f_3 = 0$)
  • Total candidate space: $5 \times 9 \times 5 \times 5 \times 1 \times 1 = \mathbf{1,125}$ candidate outcomes.

For each candidate (cleared_tick, volume, fills), forge_outcome builds a valid Merkle DeliveryCommitment and ShieldedReceipt and runs receipt.public_check(&batch) plus owner::audit for all 4 owners. The exact asserted result (residual_trust.rs:159-215):

rust
assert_eq!(total_candidates, 1_125);
assert_eq!(accepted.len(), 377);
assert_eq!(distinct_headers.len(), 33);
  • 377 out of 1,125 outcomes (33.5%, or 376 false accepts besides the 1 honest clearing (Tick(1), 4, [4, 4, 0, 0])) pass the public check and all four owners' local audits simultaneously.
  • All 33 well-formed (cleared_tick, volume) pairs (1 for NoCross at $V=0$, plus $4 \times 8 = 32$ for Tick(0..=3) at $V \in 1..=8$) admit at least one fill vector that passes every owner's local check!
  • Five concrete pathology classes are exhibited in residual_trust.rs:
  • Silent Suppression (NoCross, $V=0$, fills = [0, 0, 0, 0]): The operator claims no cross occurred even though Buyer 0 (limit 2) and Seller 1 (limit 1) crossed by 1 tick.
  • Volume Inflation (Tick(1), $V=8$, fills = [4, 4, 0, 0]): The operator reports double the actual cleared volume ($V=8$ when each side only has 4 units).
  • Conservation Violation / Unbalanced Fill (Tick(1), $V=4$, fills = [4, 2, 0, 0]): Buyer 0 receives 4 units while Seller 1 only delivers 2 units ($\sum f_{\text{buy}} = 4 \neq 2 = \sum f_{\text{sell}}$). Seller 1 accepts fill = 2 because $T_{\text{sell}} = 8$ is plausible to Seller 1 in isolation!
  • Limit Violation Hidden in Aggregate (Tick(0), $V=4$, fills = [4, 0, 0, 0]): Cleared below Seller 1's limit of 1; Seller 1 receives 0 (valid for an out-of-the-money seller) and cannot see that Buyer 0 was filled against nobody.
  • Worse-Price Clearing (Tick(2), $V=4$, fills = [4, 4, 0, 0]): Cleared at Tick(2) instead of the canonical tie-broken Tick(1).

As docs/VERDICTS.md concludes:

V3 (shielded-alone-insufficient, REFUTED): "An unproved shielded matcher can forge 377 of 1,125 outcomes (376 false accepts) and all 33 of 33 well-formed (cleared_tick, volume) pairs on price_tie_low while passing every owner's local fill check." V4 (shielded-plus-proof-Adopted, ADOPTED): Pairing the shielded channel with a zero-knowledge proof of the canonical clearing circuit (verify_ canonical_batch) collapses the 376 forgeries to 0.


Dossier 03 (§4–§6) · Bare-Metal `seL4` Microkit 2.2.0, Firmament Capability Calculus & Post-Quantum Credential Stack
Working field notes & source index below, with theorem anchors, code pointers, git history, and open questions.

4. Bare-Metal seL4 Microkit Protection Domains & OS Sandboxing (sel4/, grain-jail, nanodregg/sandbox)

4.1 Bare-Metal seL4 Microkit 2.2.0 Architecture (breadstuffs/sel4/)

Introduced on 2026-06-13 (commits 8ef312b5e, a744edfc0, 2490e7f33, f49b87b35, 9dfdfea27), /Users/ember/dev/breadstuffs/sel4/ boots a multi-Protection-Domain Dregg system directly on top of the formally verified seL4 microkernel (via seL4 Microkit SDK 2.2.0) on both ARM64 (aarch64-sel4-microkit, QEMU virt,virtualization=on, Cortex-A53) and RISC-V 64 (riscv64-sel4-microkit, QEMU virt, rv64imac_zicsr_zifencei).

Protection Domain Topology (dregg.system & riscv-stark.system)

In sel4/dregg.system, the static capability topology is partitioned into 6 isolated Protection Domains (PDs) communicating strictly via seL4 notification channels and page-bounded shared memory regions (0x4_000_000–0x4_020_000):

PD NamePriorityBudget / PeriodProgram ImageRole & Shared Memory
verifier1001000 / 1000verifier-pd.elfLean-free no_std verifier checking turn format, conservation, capabilities, and STARK proofs (turn_inbox r at 0x4_000_000, verdict_outbox rw at 0x4_001_000)
executor1205000 / 10000executor-pd.elfLinks libdregg_lean_v2.a (2,703-symbol leanc archive) + bare-metal C runtime shim (setjmp/longjmp bump-heap rollback) to run dregg_exec_full_forest
persist80—persist-pd.elfAppend-only hash-chained journal over shared memory (persist_inbox, persist_outbox)
net60—net-pd.elfMMIO driver (0x0a003000, IRQ 79) for virtio-net-device with DMA ring at 0x4_010_000
net_client59—net-client-pd.elfBridges net rx/tx rings into the executor turn inbox
app50—app-pd.elfUntrusted application PD holding only a capability to submit turns (ch 1)

Proving & Verifying a Real BabyBear + BLAKE3 + FRI STARK Inside PD 3 (verifier-stark)

In sel4/dregg-pd/verifier-stark/src/main.rs (and its original self-test in commit 7cb8626a41 on 2026-06-15, plus sel4/riscv-stark.system), PD 3 runs a 64 MiB static bump-allocated heap (#[global_allocator] static HEAP: LockedHeap, HEAP_BYTES = 64 * 1024 * 1024) in .bss:

  • Kernel Patch (0001-2mib-elf-image-pages.patch): Because the 64 MiB .bss heap exceeds Microkit's default 4 KiB page mapping loop limit, Ember patched the Microkit loader to map 2 MiB large pages for the PD ELF image.
  • Original Self-Test (7cb8626a41): Defined a 2-column Plonky3 CounterSquareAir (col 0: counter $0, 1, \dots, N-1$ with constraint $(c' - c - 1)$ on transitions; col 1: $c^2$ with constraint $s - c \cdot c = 0$ on every row) over BabyBear (p3_baby_bear), committed the trace with SerializingHasher64<Blake3> (p3_blake3) + CompressionFunctionFromHasher (2 -> 32 bytes), opened via TwoAdicFriPcs (log_blowup = 2, num_queries = 28, proof_of_work_bits = 8), and generated & verified a 78,135-byte STARK proof on bare-metal ARM64 and RISC-V64 inside the seL4 protection domain.
  • Cutover to Lean-Emitted Descriptor Prover (dd038c08e0, 2026-07-09): Replaced the hand-written CounterSquareAir with dregg_p3_pcs::prove_descriptor and dregg_p3_pcs::verify_descriptor over LEAN_FACT_HASH_IR_V2_JSON (Dregg2.Circuit.FactHashAir.factHashIrV2Json, 6 columns, pub_inputs = [10, 20, 30, 40, 240]), proving and verifying the Lean-emitted AIR descriptor inside the seL4 PD (main.rs:88-127).

4.2 Unifying seL4 CNode Caps and Distributed Dregg Caps (dregg-firmament & Dregg2.Firmament)

In sel4/dregg-firmament/src/lib.rs, Capability unifies hardware-enforced seL4 capabilities and cryptographically-enforced distributed Dregg capabilities behind one handle:

rust
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Target {
    /// Target is a Protection Domain on THIS machine (`ch: u8` = Microkit channel 0..63).
    Local { ch: u8 },
    /// Target is a cell across a `quorum_size`-of-N federation (`cell_id`, `token_hash`, `quorum_size`).
    Distributed {
        cell_id: [u8; 32],
        token_hash: [u8; 32],
        quorum_size: u16,
    },
    /// Target is a GPU surface at `surface_idx` in the compositor's table.
    Surface { surface_idx: u16, quorum_size: u16 },
    /// Target is a host-OS child process confined by Seatbelt/seccomp (`pd_id`, `door_fd`).
    HostPd { pd_id: u8, door_fd: i32 },
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Bounds {
    pub revocation_immediate: bool,
    pub commit_synchronous: bool,
    pub n: u16,
}
  • Capability::attenuate(&self, mask: Rights) -> Option<Self> checks is_attenuation(self.rights, mask) ((granted.0 & !held.0) == 0, i.e., granted ⊆ held) identically regardless of backing (Target), mirroring seL4_CNode_Mint rights masking locally and Macaroon/Biscuit caveat append remotely.
  • Capability::bounds(&self) returns the exact synchrony gradation: at n == 1 (Target::Local, Target::HostPd, or Target::Distributed { quorum_size: 1 }), revocation_immediate = true and commit_synchronous = true.

Lean 4 Formalization (Dregg2.Firmament.CapGradation & SeL4Abstract)

  1. metatheory/Dregg2/Firmament/CapGradation.lean:
  2. theorem attenuate_decision_backing_agnostic (lines 112–115):
lean
     theorem attenuate_decision_backing_agnostic (t₁ t₂ : Target) (r mask : Rights) :
         (attenuate ⟨t₁, r⟩ mask).isSome = (attenuate ⟨t₂, r⟩ mask).isSome := by
       simp [attenuate]
  • theorem attenuate_iff_grantOk (lines 125–129):
lean
     theorem attenuate_iff_grantOk (c : Capability) (mask : Rights) :
         (attenuate c mask).isSome = true ↔ grantOk c.rights mask = true := by
       simp [attenuate, isAttenuation, grantOk]
  • theorem no_amplification (lines 134–141):
lean
     theorem no_amplification (c c' : Capability) (mask : Rights)
         (h : attenuate c mask = some c') :
         ∀ a, a ∈ c'.rights → a ∈ c.rights := by ...
  • theorem distributed_collapses_at_one (lines 166–170):
lean
     theorem distributed_collapses_at_one (cid : CellId) (th : Nat) (ch : ChannelId) (r : Rights) :
         bounds ⟨.distributed cid th 1, r⟩ = bounds ⟨.local ch, r⟩ := by
       simp [bounds]
  1. metatheory/Dregg2/Firmament/SeL4Abstract.lean (transcribing Data61 l4v@e2f32e54 spec/abstract/Structures_A.thy and CSpaceAcc_A.thy):
  2. theorem seL4_derive_cap_non_amplifying (lines 128–134):
lean
     theorem seL4_derive_cap_non_amplifying (c : SeL4Cap) (mask : CapRights) :
         ∀ r, r ∈ (maskCapRights mask c).rights → r ∈ c.rights :=
       maskCapRights_subset c mask
  • theorem alpha_total_iff_used (lines 195–199):
lean
     theorem alpha_total_iff_used (c : SeL4Cap) :
         (α c).isSome = true ↔ UsedSeL4Cap c := by
       cases c <;> simp [α, UsedSeL4Cap]
  • theorem dregg_executor_cap_authority_grounded_in_seL4 (lines 253–269):
lean
     theorem dregg_executor_cap_authority_grounded_in_seL4
         (c : SeL4Cap) (mask : CapRights) (fc fc' : CapGradation.Capability)
         (hα : α c = some fc)
         (h_mint : α (maskCapRights mask c) = some fc') :
         (∀ r, r ∈ fc'.rights → r ∈ fc.rights) ∧
         fc'.target = fc.target := by ...

4.3 Host-OS Sandboxing (grain-jail & nanodregg/sandbox)

grain-jail & dregg-firmament/src/sandbox.rs

In sel4/dregg-firmament/src/sandbox.rs and grain-jail/src/jail.rs (commits 5a707ec02, 44e272708, ab659504d on 2026-07-05..06; hardened in 292829518 and 3ecfd0bd1 on 2026-09-30):

  • ProcessKernel::spawn_pd creates an IPC socketpair(AF_UNIX, SOCK_STREAM) per channel, forks the child process, closes every inherited file descriptor except {0, 1, 2} and the PD's assigned channel descriptors (close_all_fds_except), and applies confine_current_process() before executing the PD closure:
  • macOS (apply_seatbelt): Calls sandbox_init(profile, 0, &mut errbuf) with the deny-by-default SBPL profile:
scheme
    (version 1)
    (deny default)
    (allow process-info* (target self))
    (allow sysctl-read)
    (allow mach-lookup (global-name "com.apple.system.logger"))

Any subsequent File::open, TcpStream::connect, or Command::new fails with EPERM.

  • Linux (apply_linux_sandbox): Sets prctl(PR_SET_NO_NEW_PRIVS, 1), unshares CLONE_NEWUSER | CLONE_NEWNET | CLONE_NEWNS | CLONE_NEWIPC, applies Landlock ABI v1 with empty ruleset (LANDLOCK_ACCESS_FS_READ_FILE | WRITE_FILE | EXECUTE handled and denied), and installs a classic BPF seccomp filter (SECCOMP_SET_MODE_FILTER) that permits only read, write, recvmsg, sendmsg, futex, mmap, munmap, mprotect, brk, rt_sigreturn, exit_group, clock_gettime, getrandom, sched_yield, close, poll/ppoll, and ioctl(fd, FIONBIO) (0x5421 matched on the full 64-bit request per commit 292829518), or traps to a supervisor fd via SECCOMP_RET_USER_NOTIF (provider_door).
  • grain-jail/src/lib.rs wraps the confined child in ConfinedBrain<C: BodyChannel>: the jailed process holds zero secret keys and receives only opaque state commitments (WorldView { tick, current_state_commitment, available_actions }), returning a chosen action_index over the line protocol while the host brain builds and proves the R2 turn receipt.

nanodregg/sandbox

In /Users/ember/dev/nanodregg/sandbox/src/lib.rs, connect.rs, and custody.rs (commits af3dfd3 through 1ab410e, Oct 2026):

  • Policy specifies { read, write, exec, hidden, connect }, enforcing CONNECT_MAX = 2 Unix domain sockets (connect.rs:14).
  • Before spawning, confine canonicalizes all paths (O_NOFOLLOW where required), refuses any policy where a read/write/exec path overlaps a hidden path (ConfineError::Exposed), refuses any program binary not covered by read or exec (ConfineError::ProgramOutside, commit 6278ab8), and validates every connect socket via connect::validate (S_IFSOCK, mode 0600 or 0660, owned by euid, ancestor chain verified via custody::chain StrictModes walk).
  • die_with_parent() (commit 1ab410e, 2026-10-24) binds child lifetime to its parent via rustix::process::set_parent_process_death_signal( Some(Signal::KILL)) on Linux (checking getppid() != ppid after registration to close the fork race) and a background orphan-watch thread polling getppid() on macOS.
  • Enforces confinement via /usr/bin/sandbox-exec on macOS (emitting (deny file-read* (subpath ...)) after (allow ...) so hidden overrides broader read grants) or /usr/local/libexec/nd-bwrap on Linux (--unshare-all --unshare-user --disable-userns --cap-drop ALL --new-session --die-with-parent, binding an empty 0400 tmpfs over hidden directories and /dev/null over hidden files).

5. Object-Capability & Post-Quantum Credential Stack (macaroon, token, dregg-auth, credentials, dregg-pq, pqvrf, intent, starbridge-apps)

5.1 HMAC-SHA256 Macaroons (macaroon, em2_) & Third-Party Caveat Discharge

In macaroon/src/macaroon.rs and macaroon/src/caveat_3p.rs:

  • HMAC-SHA256 Tag Chain: Given root_key: [u8; 32] and random nonce: [u8; 16]: $$T_0 = \text{HMAC-SHA256}(\text{root\_key},\;\text{nonce}), \qquad T_i = \text{HMAC-SHA256}(T_{i-1},\;\text{encode}(C_i))$$ Anyone holding the macaroon can append a caveat $C_{n+1}$ and replace $T_n$ with $T_{n+1} = \text{HMAC-SHA256}(T_n, \text{encode}(C_{n+1}))$ without knowing root_key; truncating $C_{n+1}$ requires inverting HMAC-SHA256 to recover $T_n$. Signature comparison uses subtle::ConstantTimeEq.
  • Third-Party Caveats (ThirdPartyCaveat):
  • add_third_party_caveat generates a random 32-byte caveat root key $r$, encrypts $r$ under the current HMAC tail $T_{i-1}$ using XChaCha20-Poly1305 (verifier_key = seal(T_{i-1}, r)), and encrypts {r, caveats} under the 3P service's shared key (ticket = seal(shared_key, WireTicket { discharge_key: r, caveats }), #[derive(Zeroize, ZeroizeOnDrop)]).
  • bind_discharge binds the discharge macaroon to the authorizing root macaroon by appending caveat ID CAV_BIND_TO_PARENT (0xFE) containing $\text{SHA-256}(T_{\text{root}})$.
  • verify_discharge is fail-closed: it enforces a 300-second freshness window (MAX_DISCHARGE_AGE = 300) and rejects any discharge macaroon that lacks a CAV_BIND_TO_PARENT caveat matching $\text{SHA-256}(T_{\text{root}})$, preventing cross-macaroon discharge replay.
  • Lean 4 Proofs (Dregg2/Authority/Caveat.lean & MacaroonDischarge.lean):
  • theorem attenuate_narrows, theorem attenuate_subset, theorem macaroon_not_crossvat, theorem biscuit_crossvat (Caveat.lean:95-190).
  • theorem bound_discharge_verifies, theorem unbound_discharge_rejected, theorem binding_not_replayable_to_other_root, theorem rebinding_changes_replay (MacaroonDischarge.lean:115-198).

5.2 Unified Token Layer (token: em2_ & eb2_) and Hybrid Revocation (RevocationRegistry)

In token/src/lib.rs, token/src/biscuit_backend.rs, and token/src/revocation.rs:

  • Unifies em2_ (msgpack + URL-safe Base64 MacaroonToken) and eb2_ (Ed25519 + Datalog BiscuitToken via biscuit-auth v6.0) behind the AuthToken trait.
  • Revocation Non-Membership & Hybrid Root Attestation (revocation.rs):
  • SortedRevocationTree maintains revoked token hashes in sorted order in a BLAKE3 Merkle tree and produces a NonMembershipProof consisting of two adjacent leaves $(L_i, L_{i+1})$ with $L_i < x < L_{i+1}$ and their Merkle inclusion proofs, proving $x$ is not in the revoked set.
  • AttestedRevocationRoot signs the revocation root with both Ed25519 and ML-DSA-65 (pq_signature: Option<Vec<u8>>). AttestedRevocationRoot::verify_hybrid(&self, authority: &HybridAuthorityKey) requires both the classical Ed25519 signature and the post-quantum ML-DSA-65 signature (domain "dregg-revocation-root-v1") to verify, failing closed if pq_signature is None.

5.3 Standalone Hybrid Post-Quantum Credentials (dregg-auth: dga1_ / dgd1_ & eb2_)

Introduced on 2026-06-09 (3e4bfa483) and upgraded to hybrid post-quantum in dregg-auth/src/credential/, dregg-auth implements an offline-attenuable, chain-independent capability credential (dga1_ URL-safe Base64 token wire, dgd1_ detached proof-of-possession signature wire):

  • Cryptographic Chain Structure (credential/chain.rs):
  • Each Block contains:
rust
    pub struct Block {
        pub caveats: Vec<Pred>,
        pub next_pub: VerifyingKey,
        pub next_pub_ml_dsa: Option<Box<MlDsaPubBytes>>, // 1952-byte ML-DSA-65 PK
        pub sig: Signature,                              // 64-byte Ed25519 sig
        pub sig_ml_dsa: Option<Box<MlDsaSigBytes>>,      // 3309-byte ML-DSA-65 sig
    }
  • A Credential carries root_pub: VerifyingKey, root_pub_ml_dsa: Option<Box<MlDsaPubBytes>>, blocks: Vec<Block>, and the bearer tail secret tail: SigningKey (zeroized on drop, plus a cached tail_ml_dsa_memo: Option<Arc<MlDsaSeedMemo>> so repeated PQ operations do not re-run the ~200ms Lean ML-DSA keygen).
  • Hybrid Verification & DoS-Resistant Ordering (Credential::verify_hybrid):
  • Checks blocks.len() <= MAX_BLOCKS (32) and total AST nodes <= MAX_PRED_NODES (256).
  • Step 1 — Classical Proof-of-Possession (check_pop_classical): Fast (~50 µs) Ed25519 signature check against last.next_pub before touching any post-quantum verification.
  • Step 2 — Classical + PQ Chain Verification: Pins expected_key = root.ed25519 and expected_pq = root.ml_dsa_65 from the enrolled HybridRootPublic (never trusting the wire's self-reported root_pub_ml_dsa!). For every block $i$, verifies both expected_key.verify_strict(&msg, &block.sig) and pq::ml_dsa_verify(&expected_pq, &msg, &block.sig_ml_dsa) (under FIPS 204 context CRED_PQ_CTX = b"dregg-auth v1 credential mldsa"). Rejects with VerifyError::MissingPostQuantumSignature { block: i } if any block omits its ML-DSA-65 signature or key.
  • Step 3 — Post-Quantum Proof-of-Possession (check_pop_pq): Executed after chain authentication (mod.rs:483-508) so an unauthenticated attacker cannot force the verifier to derive a 1,952-byte ML-DSA-65 public key (~200 ms in Lean) on a forged token.
  • Step 4 — Fail-Closed 3-Valued Caveat Algebra (credential/pred.rs): Evaluates every Pred across all blocks using 3-valued logic (Outcome::{Pass, Fail, Unbound}). If a clock or attribute is absent from Context, comparison predicates return Unbound, and Pred::Not(Unbound) remains Unbound (which fails closed at top level), so Not(AttrEq("role", "guest")) can never invert a missing "role" attribute into a pass!
  • Lean 4 Proofs (Dregg2/Authority/BiscuitGraph.lean — namespace Authority.Biscuit — plus TokenCapBridge.lean & Dregg2/Crypto/CapabilityChain.lean; extended in Nov 2026 by /Users/ember/dev/qsag qsag-cred / qsag-agg, Dossier 28 §1):
  • theorem biscuit_narrows, theorem amplifying_block_rejected, theorem forged_block_rejected, theorem sealed_biscuit_final.

5.4 Lean-Verified Post-Quantum Cryptography (dregg-pq & pqvrf)

dregg-pq: leanc-Compiled FIPS 204 (ML-DSA-65) & FIPS 203 (ML-KEM-768) with Uncatchable Audit Gate

Consolidated on 2026-07-09 (commits 13eff7a3f, 7aa833047, 0cdfd2ed5, 8f5d51acf, f52d8ed91), dregg-pq/src/lib.rs is the workspace's single post-quantum leaf crate:

  • ML-DSA-65 (dregg-pq/src/mldsa.rs): Parameter set ML-DSA-65 (FIPS 204, NIST Security Category 3): PK_LEN = 1952, SK_LEN = 4032, SIG_LEN = 3309.
  • Hybrid X25519 + ML-KEM-768 (dregg-pq/src/hybrid_kem.rs): Parameter set ML-KEM-768 (FIPS 203): EK_LEN = 1184, DK_LEN = 2400, CT_LEN = 1088. hybrid_kem::combine implements the X-Wing / IETF hybrid KEM combiner (DOMAIN = b"dregg-hybrid-kem-x25519-mlkem768-v1"): $$\text{ikm} = \text{ss}_{\text{X25519}} \mathbin{\Vert} \text{ss}_{\text{ML-KEM-768}}, \qquad K = \text{HKDF-SHA256}(\text{salt} = \text{DOMAIN},\;\text{ikm},\;\text{info} = \text{DOMAIN} \mathbin{\Vert} \text{transcript})$$ Remaining secure if either X25519 (IND-CCA under Gap-CDH) or ML-KEM-768 (IND-CCA under Module-LWE) holds.
  • Lean-Verified Core Hook Table (PqSite & dregg-exec-lean): All 6 post-quantum operations (PqSite::ALL: MlDsaVerify, MlDsaSign, MlDsaKeygen, MlKemEncaps, MlKemDecaps, MlKemKeygen) dispatch through OnceLock hooks populated by dregg_exec_lean::register_lean_fips204_verify(), which links the leanc-compiled Lean 4 implementations (dregg_fips204_verify_real, dregg_fips204_sign_real, dregg_mldsa_keygen_real, dregg_mlkem_keygen_real, dregg_mlkem_encaps_real, dregg_mlkem_decaps_real).
  • Uncatchable Fail-Closed Audit Gate (dregg-pq/src/audit.rs): If any of the 6 PQ sites is invoked before its Lean-verified core is registered:
  • enter_unaudited writes a diagnostic banner directly to file descriptor 2 via libc::write(2, ...) (eprintln_fd2, bypassing Rust's buffered std::io::stderr() so the reason is never lost on abort) and calls std::process::abort() (SIGABRT, which cannot be caught by std::panic::catch_unwind).
  • Even if DREGG_ALLOW_UNAUDITED_PQ=1 is set in the environment, setting DREGG_REQUIRE_LEAN=1 revokes the override (audit.rs:155-168) and forces std::process::abort().

pqvrf: Lattice-Based Post-Quantum VRF (Dregg2.Crypto.VRF)

Introduced in commit 19205169f (2026-07-11), pqvrf/src/lib.rs implements the Esgin, Kuchta, Sakzad, Steinfeld, Zhao, and Liu (FC 2021) Module-LWE / Module-SIS Lattice-Based VRF over the cyclotomic ring $R_q = \mathbb{Z}_q[X]/(X^d + 1)$:

  • Exact Set I Parameters (pqvrf/src/lib.rs:62-92):
  • Ring degree $d = 256$ (DEGREE = 256)
  • Primary modulus $q = 100,679,681$ (MODULUS_Q, 27-bit prime, $q \equiv 1 \pmod{512}$)
  • Rounding modulus $p = 2,097,169$ (MODULUS_P, 21-bit)
  • Module-SIS rank $k = 4$ (MSIS_RANK = 4), secret width $l = 9$ (SECRET_WIDTH = 9)
  • Ternary challenge weight $\kappa = 39$ (CHALLENGE_WEIGHT = 39, $\approx 2^{192}$ challenge space)
  • Rejection-sampling mask bound $\gamma = 89,856$ (MASK_BOUND), norm bound $\beta = \gamma - \kappa = 89,817$ (NORM_BOUND).
  • Lean 4 Uniqueness Theorem (metatheory/Dregg2/Crypto/VRF.lean): theorem lattice_vrf_uniqueness_reduces_to_msis proves that any two valid proofs $(\pi_1, \pi_2)$ for the same public key and input yielding distinct VRF outputs produce a short non-zero vector $z = s_1 - s_2$ solving $\text{MSIS}_{q, k, l, 2\beta}$.

5.5 Anonymous Selective-Disclosure Credentials (credentials)

In credentials/src/lib.rs, issuance.rs, presentation.rs, verification.rs, and revocation.rs:

  • Blinded Issuer Federation & Selective Disclosure:
  • issue mints a Credential backed by an Ed25519 + Datalog Biscuit token (attr("cred_type", ...), attr(field, value), attr("subject_commitment", hex(BLAKE3("dregg-credential-subject-v1" || holder_secret || issuer_pubkey)))) and registers the issuer's public key in a blinded Poseidon2 Merkle federation registry (BlindedFederationRegistry).
  • present_anonymous produces an unlinkable Presentation using a per-presentation presentation_nonce (rerandomized_leaf = Poseidon2(issuer_leaf, nonce)) so multiple presentations of the same credential cannot be correlated (unlinkable multi-show), while optionally attaching Gte/Lte/InRange predicate proofs (CredentialPredicate) and a non-membership RevocationProof against the revocation tree.
  • Injective 9-Lane Base-$2^{28}$ Field Encoding (field_limbs9):
  • In credentials/src/verification.rs, compute_revealed_terms_commitment hashes revealed attributes using domain "dregg-credentials-revealed-v2" and encodes each 256-bit digest into 9 base-$2^{28}$ BabyBear limbs (field_limbs9, $9 \times 28 = 252 \ge 248$ bits), proved injective in Lean (Dregg2.Circuit.FieldLanes9.fieldToLanes9_injective), replacing an older non-injective from_le_bytes % P reduction.
  • Fail-Closed Verification & Residual-Gap Honesty (verification.rs:140-215):
  • verify requires expected_federation_root == proof.federation_root, checks expiration, verifies RevocationProof, checks revealed_terms_commitment, and fail-closes on expected_predicates (VerificationError::PredicateProofInvalid), documenting in-code that until the emitted predicate AIR binds facts_root as a public input, predicate-bearing credential presentations are refused rather than silently accepted.

5.6 Agent Mandates, Audit Proofs, & Verifiable MCP Delegation (intent, audit, starbridge-apps)

(Note: A repository-wide and cv --frozen search confirms there is no type literally named AlignmentProof; agent alignment, mandate containment, and usage auditing are implemented via intent::agent_mandate::Mandate / DelegTree, audit::proofs::{CountProof, RangeProof, LastUseProof, ConsistencyProof, BudgetProof}, and the Lean-verified starbridge-apps agent-provenance and tool-access-delegation.)

intent/src/agent_mandate.rs & Lean Dregg2.Agent.Mandate

In intent/src/agent_mandate.rs and metatheory/Dregg2/Agent/Mandate.lean:

  • Mandate::sub_delegate constructs a child mandate whose target is fixed to self.target, whose rights are intersected (&self.keep & want), whose budget is clamped (ask_budget.min(self.budget)), and whose caveat is intersected (self.caveat.intersect(extra_caveat)).
  • DelegTree enforces:
  • well_attenuated: every child's rights, budget, target, and caveat narrow its parent's.
  • no_amplify: every node in the tree satisfies m.keep.is_subset(&root.keep).
  • budget_bounded: every node satisfies m.budget <= root.budget.
  • budget_partitioned: at every internal node, $\sum_{c \in \text{children}} c.\text{budget} \le \text{node}.\text{budget}$ (conservation of delegated budget across parallel sub-agents).
  • materialize_grants() → Vec<Effect::GrantCapability> and materialize_revoke(child) → Effect::RevokeDelegation { child }.
  • Lean 4 Theorems (Dregg2/Agent/Mandate.lean):
  • theorem subtree_rights_le_root:
lean
    theorem subtree_rights_le_root (t : DelegTree) ( probe : List MethodId)
        (hw : wellAttenuated probe t = true) :
        ∀ m ∈ mandateList t, ∀ a, a ∈ m.keep → a ∈ (rootMandate t).keep
  • theorem materialize_non_amplifying, theorem children_no_oversubscribe, theorem subtree_budget_le_root, and theorem revoke_kills_subtree.

starbridge-apps/agent-provenance & Lean Dregg2.Apps.AgentProvenanceGated

In starbridge-apps/agent-provenance/src/lib.rs and metatheory/Dregg2/Apps/AgentProvenanceGated.lean:

  • The provenance cell configures HEAD_SLOT = 2 ("head") with SlotCaveat::Monotonic, TIP_SLOT = 3 ("tip"), and ENTRY_BASE + i ("entry0", "entry1", ...) each with SlotCaveat::WriteOnce.
  • Each entry stores link_hash(prev, claim) = BLAKE3("dregg-provenance-link\x01" || prev || claim) (with IncrementalChainVerifier maintaining $O(1)$ incremental verification state).
  • Lean 4 Theorems (AgentProvenanceGated.lean:154-309, all #assert_axioms-clean):
  • theorem prov_forged_credential_rejected (s : RecChainedState) (slot : FieldName) (value : Int) : execFullForestG s (provNode forgedCred slot value) = none
  • theorem prov_entry_writeonce (s : RecChainedState) (i : Nat) (digest : Int) (hgate : gateOK (mkAuth goodCred []) s = true) (hfrozen : caveatsAdmit s.kernel (entrySlot i) agentActor logCell digest = false) : execFullForestG s (appendEntryRaw goodCred i digest) = none
  • theorem prov_head_cannot_rewind (s : RecChainedState) (newHead : Int) (hgate : gateOK (mkAuth goodCred []) s = true) (hrewind : caveatsAdmit s.kernel headSlot agentActor logCell newHead = false) : execFullForestG s (advanceHeadNode goodCred newHead) = none
  • theorem prov_append_reads_back, theorem prov_append_audited, theorem prov_chain_links, theorem prov_chain_tamper_rejected, theorem prov_append_conserves.

starbridge-apps/tool-access-delegation & Lean Dregg2.Apps.ToolAccessDelegation

In starbridge-apps/tool-access-delegation/src/lib.rs and metatheory/Dregg2/Apps/ToolAccessDelegation.lean:

  • Mints a mandate cell with CALLS_MADE_SLOT = 0 (Monotonic + FieldLteField { target_slot: 1 }), RATE_LIMIT_SLOT = 1 (WriteOnce), DEADLINE_SLOT = 2 (WriteOnce + FieldGteHeight), and TOOL_ID_SLOT = 3 (WriteOnce).
  • deleg_admit calls the @[export dregg_deleg_admit] Lean function Dregg2.Apps.DelegAdmit.delegAdmit directly across dregg-lean-ffi.
  • Lean 4 Headline Theorem (ToolAccessDelegation.lean:179-193, #assert_axioms-clean):
lean
  theorem tool_invocation_commit_iff_admit (g : Grant) (now tool : Int) (cell worker : CellId)
      (s : RecChainedState) (c : Int)
      (hprog : s.kernel.slotCaveats cell = (mandateSpec g now tool cell).caveats)
      (hcur : (mandateSpec g now tool cell).committed s.kernel = c)
      (hold : c ∈ (mandateSpec g now tool cell).oldRange)
      (hnew : (c + 1) ∈ (mandateSpec g now tool cell).newRange) :
      (execFullA s (.setFieldA worker cell callsMadeSlot (c + 1))).isSome = true
        ↔ (delegAdmit g now tool c (c + 1) = true
            ∧ (stateStep s callsMadeSlot worker cell (.int (c + 1))).isSome = true)

Plus the rejection teeth tool_invocation_over_rate_rejected, tool_invocation_past_deadline_rejected, tool_invocation_out_of_scope_rejected, invocation_forged_rejected, invocation_revoked_rejected, and kernel keystones tool_invocation_conserves and tool_invocation_no_amplify.


6. Chronological Git & cv Archaeology

Phase 1: Initial breadstuffs Macaroon & Biscuit Prototype (2026-02-07, Session 95e87c6f-fb60-4963-a126-0b26186708ad)

The capability lineage began on 2026-02-07 in Claude Code session 95e87c6f-fb60-4963-a126-0b26186708ad (recorded in /Users/ember/.claude/history.jsonl):

  • 1770467968194 (2026-02-07):

"We are working on \"breadstuffs,\" excellent implementations of macaroons and biscuits... We basically want to weaponize biscuits and macaroons."

In that February 2026 sprint, Ember built the em2_ HMAC-SHA256 macaroon crate (with XChaCha20-Poly1305 3P caveats and ZeroizeOnDrop WireTickets), the eb2_ Ed25519 + Datalog token crate (FeatureGlob, Budget, Revocable), and the cuckoo-filter revocation mesh.

Phase 2: pyana — Distributed Object-Capability Runtime with ZK Proofs (2026-05-19..21)

Ember brought the macaroon and token crates into /Users/ember/dev/breadstuffs as pyana:

  • 3d0d0bfafb2d89fef4ed03537b5191f85dbc1cf5 (2026-05-19): "pyana: distributed object-capability authorization with ZK proofs — A post-quantum capable authorization system for AI agent execution across trust domains. Prove you're authorized without revealing your delegation chain. 22 crates, ~70k LOC, 1000+ tests." (Importing macaroon, token, cell, bridge, audit, circuit).
  • d5be7258e (2026-05-20): Added the distributed intent engine (Intent, MatchSpec, Fulfillment).
  • 77b998170 / d1b48d885 (2026-05-24): Added the credentials crate (selective disclosure, blinded federation registry, unlinkable multi-show).

Phase 3: Standalone Agent Auth, Bare-Metal seL4, & Lean-Verified PQ (dregg, June–July 2026)

  • 3e4bfa483 (2026-06-09) & d15b94f63 (2026-06-11): Created dregg-auth (dga1_ / eb2_ offline-attenuable agent permission wedge and MCP gateway profile).
  • 8ef312b5e, a744edfc0, 2490e7f33, f49b87b35 (2026-06-13) & 7cb8626a41 (2026-06-15): Built the sel4/ Microkit 2.2.0 6-PD system, dregg-firmament (Capability unifying seL4 CNode caps and distributed cell caps), and verifier-stark proving and verifying a 78,135-byte BabyBear + BLAKE3 + FRI STARK inside a bare-metal seL4 protection domain on ARM64 and RISC-V64.
  • 5a707ec02, 44e272708, ab659504d (2026-07-05..06): Built grain-jail (ConfinedBrain + macOS Seatbelt / Linux Landlock+seccomp-BPF process confinement).
  • 13eff7a3f, 7aa833047, 0cdfd2ed5, 8f5d51acf, f52d8ed91 (2026-07-09): Consolidated all post-quantum cryptography into dregg-pq, routing ML-DSA-65 (FIPS 204) and ML-KEM-768 (FIPS 203) through leanc-compiled Lean-verified cores with the uncatchable std::process::abort() audit gate (audit.rs).
  • 19205169f (2026-07-11): Built pqvrf (Esgin et al. FC 2021 Module-LWE / Module-SIS lattice VRF bound to Lean Dregg2.Crypto.VRF.lattice_vrf_uniqueness_reduces_to_msis).

Phase 4: Hardware TEE Roots of Trust, Confidential GPU E2EE, & Residual Trust Proofs (July–October 2026)

  • 17b6e5539 & 8ce36ba16 (2026-07-11), ad33c9247 (2026-07-12), 261a06f8d (2026-07-13): Built tee-verify (NitroVerifier, SnpVerifier with Milan/Genoa/Turin RSA-4096 PSS ARK→ASK→VCEK chains, TdxVerifier) and tee-produce (NitroNsmBackend over /dev/nsm).
  • 9d5d06853 (2026-07-23), 6f38efbe3 (2026-07-26), 4bcb934a3 (2026-07-27): Built dregg-chutes-e2ee (confidential GPU TDX attestation + ML-KEM-768 / HKDF-SHA256 / ChaCha20-Poly1305 E2EE) and attest-check (dungeon-attest-check 6-link provenance verifier).
  • ac77a4d (2026-08-18): Proved in degg-research (experiments/shielded-baseline/tests/residual_trust.rs, Verdicts V3/V4) that an unproved TEE/shielded matcher can forge 377 out of 1,125 clearing outcomes (33/33 headers) that pass every participant's local fill audit.
  • 4d98292c2, a9d5df4db, 551fc897f, 3bf5e041a, 3ecfd0bd1, 292829518 (2026-09-30): Closed the 2026-07-25 TEE and Firmament security audit findings (F1–F3, F10–F14).
  • af3dfd3..1ab410e (2026-10-16..24): Built nanodregg/sandbox (deny-by-default macOS sandbox-exec and Linux nd-bwrap confinement, custody StrictModes directory walk, CONNECT_MAX = 2 socket validation, and die_with_parent).