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,329commits) now builds597/597Tier-1 Lean 4.35 modules (837.leanfiles total,0 sorryAx), sealsStageBInstances.lean(0 *Obligations), ships a 5-stageSiliconElabFabric, certifies 29/29 RDNA2 RX 6750 XT dumps +Ozakiexact integer collectives, and is orchestrated byobebuilder(obb v6/v7,aab42d2) — note that early Wave 1–2 paths below (Core/AST.leanvs real 25-constructorObend/Core/Term.lean,hardware/HardwareVerify.lean,crates/obend-node,sandstorm/, andCDNA3framing) 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
- Core Thesis & Macro-Architecture of Objective Bend (
THESIS.md,DESIGN.md,GROUNDING.md,METATHEORY.md): - 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). - 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). - The Silicon Elaborator (
SILICON-ELABORATOR.md,Obend/Lower/,Obend/Leaf/Futamura.lean,Obend/Hardware/ReductionMachine.lean): - 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) intoCore4and flatLeaf.Bookrules. - 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-cycleSlotGuardRegdependency 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-freeICAPDynamic 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)). - The Silicon / FPGA / Physical Engineering Flow (
PHYSICAL.md,hardware/,Obend/Hardware/,Obend/Lower/Proofs/): - 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-byteTag 0x0BEDCBOR 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). - 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_eFPGAtargets),[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 toCore4C4 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, AMDCDNA3GPU Wavefront ISA, and TPU Systolic /DSP58/ Ozaki Base-13FP4 (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). - Next-Mathematica (
NEXT-MATHEMATICA.md,Obend/Analysis/,Obend/Elab/Workbook.lean,crates/obend-gui/): - 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_declworkbook elaboration macros, and theobend-guimulti-projection CAD/EDA/Symbolic viewport (10ProjectionKinds,3PhysicalViewportKinds, and.free/.press/.lockedLawDial). - 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/): - The synthesis of
dregg,minidregg, andnanodregginto DeOS: 4-tierContractCert(Tier 0Pressdecide +kernel,Tier 1Symbolic Lean Proof,Tier 2Bounded Model Check,Tier 3Runtime Monitor),cellContract_relaw_sound, atomic multi-partyTurnHyperedgeclearing withTurnWitnessformat checks,Escrow&DragonsExchangeatomic swaps, double-entryLedger.Book(9 conserved operations) + Zoe-style offer-safetyLedger.Seat(safeAt,payout_exact), 3-hopConsensus.SimplexBFT finality (notarized_unique,finalized_safety),Consensus.Epistemicsybil-resistant Brier-score clearing,Fold.Collapsesemantic trace folding (traceHash_invariant_under_stutter), and theobend-node(4,628-line Rust daemon),obend-sandbox(Grain R0–R4 + Bubblewrap), andsandstorm/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 SHA | Milestone Summary |
|---|---|---|
10-29 19:03 | bc2c6bd | Initial Objective Bend thesis and design draft (THESIS.md, DESIGN.md) |
10-29 20:54 | 7857f61 | Complete Obend Lean 4 core (Core4, Denot, Eval, Lower, Leaf, Slot, Fold, Receipt, Law) |
10-30 14:12 | d194a02 | METATHEORY.md & initial resolution of nanodregg metatheoretic boundaries (C4, Slot, Fold) |
10-31 09:45 | c83a190 | obend-astra-decisions effect-law alignment (ASTRA-EFFECT-LAWS-20261031.md: 11 laws across Slot, Fold, Judge, Net, Pack, Refine) |
10-31 18:20 | 58a241b | NEXT-MATHEMATICA.md & Obend/Analysis/* (Dyadic intervals, AD, Taylor models, Buchberger/Gröbner, Flowpipe, Hybrid, Equitable, QuantumWalk) |
11-01 03:15 | 94e01b2 | DEOS-CONTRACTS-CONSENSUS.md & full DeOS stack (Law/Contract, Vault/Hyperedge, Ledger/Book, Ledger/Seat, Consensus/Simplex, Consensus/Epistemic, obend-node, sandstorm/) |
11-01 11:40 | e402a19 | PHYSICAL.md, standalone hardware/{EfpgaFabric,HardwareVerify,SiliconProcess}.lean, hardware/rust-ffi, hardware/sim/, and Obend/Hardware/* |
11-01 15:30 | 1a77d8c | SILICON-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:50 | 7c699ca1 | Multimodel Council Review (review/COUNCIL-BRIEF-20261101.md, review/FABLE-COUNCIL-20261101.md) |
11-01 17:45 | 8f9f822c | Council 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:51 | 23a76513 | Complete 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:
- 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.
- 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 transformerSelf → Super → Record(proto), composed via associative/idempotent prototype mixing (mix) and closed only at projection time via a lazy fixed-point (fix). - Explicitly Carved Leaf Kernels (
Obend.Leaf): Only when a computation is explicitly marked via theleafboundary (or lowered throughObend.Lower) does OBend enforce first-order closure conversion and compile the subterm into a flat supercombinatorLeaf.Book(or affine interaction-combinator netBendTT) 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:
- Object / Prototype Calculus (Faré's POO):
.proto (body : Expr): Open-recursive prototype wrapper bindingself(bvar 0) andsuper(bvar 1)..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))..fix (target : Expr): Closes an open prototype by tying the recursive knotself := fix targetand supplying the empty record as the basesuper..recLit (fields : List (Field × Expr)): Extensional record literal..proj (target : Expr) (field : Field): Field selection.- Standard $\lambda$- and Algebraic Core:
.bvar (idx : Nat),.lit (v : Val),.lam (body : Expr),.app (fn arg : Expr),.letE (val body : Expr),.prim (op : PrimOp) (args : List Expr).- Law & Refinement Stratum:
.law (dial : LawDial) (pred : Expr) (subject : Expr): Attaches a first-class boolean/propositional contractpredtosubjectunder a three-state dialLawDial(.free= observational/log-only,.press= property-checked/narrowed over finite witnesses,.locked= admission-blocking certificate required).- Live Reactive & Hardware-Leaf Stratum:
.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)..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)..leaf (body : Expr): Explicit boundary carving out a pure first-order kernel for lowering intoObend.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:
-- 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 = false2. 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):
-- 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:
-- 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):
- Full Structural
kernelIsDefEqFull:LeanKernel.leanmodels Lean expressions (LExpr:.bvar,.fvar,.mvar,.sort,.const,.app,.lam,.forallE,.letE,.lit,.proj) and defines the structural definitional-equality checkerkernelIsDefEqFull : Nat → LEnv → LExpr → LExpr → Boolhandling $\beta\delta\iota\zeta$-reduction,Natliteral successor bridges (Nat.succ n ≡ n + 1), $\eta$-expansion across.lam, andPropproof irrelevance:
-- 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- Computational Relevance Erasure & Term-Level Lowering: Types (
.forallE,.sort) andPropproofs are erased to.lit (.int 0)at the runtime boundary (eraseTypesLExpr), while inductive constructors and recursors (InductiveSpec,CtorSpec,RecRule) are lowered into tagged records andCore4dispatch tables (compileInductiveToCore4,compileRecursorToCore4), with mechanized simulationrunLExprSteps_sound:
-- 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):
- Single-Cycle Structural Hash-Consing & Pointer Equality: Because
ExprCAMmaintains canonical bottom-up interning (internNode), two normalized expressions are structurally equal iff their 16-bit CAM indices match (idx1 == idx2in 1 clock cycle). - $O(1)$ Metadata Fast-Paths: Following Lean 4's
Exprbitpacking in C++,looseBVar(bit 59) andhasFVar(bit 58) are computed combinatorially at insertion time: - If
looseBVar == 0,instantiateRevis a 0-cycle no-op (camInstantiate_noLooseBVar_noop). - If
hasFVar == 0,abstractFVaris a 0-cycle no-op (camAbstract_noFVar_noop). - If
hash26(a) != hash26(b),isDefEqrejects in 1 clock cycle before walking children (camDefEqFastReject_sound).
-- 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 = idx4.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.starwildcard branches evaluated in parallel with exact-key branches via bitwise OR over candidate rule bitvectors (CandidateMask64). - Every cached
simpor typeclass rule entry carries adepMask : BitVec 64recording whichObend.Slotpins (environment declarations/attributes) it depends on. When a user edits a definition in a live workbook, flipping bit $k$ inSlotGuardReginvalidates all affected hardware cache lines in 1 clock cycle via(entry.depMask &&& activeSlotReg) == entry.depMask:
-- 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.depMask4.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:
- First Futamura Projection (
futamura1 : Book → FnId → List LVal → Book): Specializes an interpreter/elaborator ruleinterpwith respect to a static object/type-class tablestaticArgs, eliminating all static dispatch.caseIntbranches and producing a specialized residualBook:
-- 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- Second Futamura Projection (
futamura2 : SpecGenConfig → Book): Specializes the partial evaluatormixPEwith respect to the elaboratorelabBook, producing a standalone hardware compiler generator (cogen) that maps new user declarations directly to residualLeaf.Booktiles without re-running interpretive lookup. - Third Futamura Projection (
futamura3): Self-appliesmixPEtomixPE, proven coherent viafutamura_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):
- 2D XY Wormhole NoC with Mechanized Flit & Credit Conservation:
- Each tile at
(x, y)holdsNocTileState(inbox : List NocFlit,outbox : List NocFlit,credits : Nat,rules : List TileRule). - Routing (
routeXYStep) steps along X untilcurX == dstX, then along Y untilcurY == dstY(provably deadlock-free on a 2D mesh,routeXY_manhattan_decreases), whilestepNocRouter_conserves_flits_and_creditsandnoc_step_conserves_flitsprove universal conservation of total in-flight flits across the entire fabric:
-- 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- Glitch-Free 3-Phase
ICAPDynamic Partial Reconfiguration InstantiatingObend.Slot: - When a Futamura-specialized rule changes because a workbook
Slotpin mutated, the FPGA reconfigures only that tile region via a 3-phase protocol (DprPhase:.active$\to$.isolatedAndDraining$\to$.loadingFrames$\to$.releasingIsolation$\to$.active). - Crucially,
dprTileSlotis formalized directly as an instance ofObend.Slot.Slot LeafPin TileBitstreamCandidate, proving that a mutatedLeafPinimmediately rejects stale tile bitstreams (dprTile_moved_pin_blocks) and that reconfiguration preserves all in-flight packets outside the isolated tile (dpr_glitch_free_isolation):
-- 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) = false4.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:
- Vector 1 (
ExprCAMHash-Consing & Pointer Equality): InternsNat.add x 0twice and verifies single-cycle CAM hit (hit == 1, identical 16-bit index) pluslooseBVar == 0fast-path. - Vector 2 (
DiscrTreeLUTParallel Wildcard Match +SlotGuardRegInvalidation): Queries[const(add), star, lit(0)], verifies parallel LUT match returning rules{R1, R2}in 3 cycles, then flips bit 1 ofSlotGuardRegand verifies 1-cycle hardware invalidation of ruleR2. - Vector 3 (Glitch-Free 3-Phase
ICAPDPR Hot-Swap): Assertsreq_reconfig, verifiestile_isolated == 1drainsinflight_countto0before assertingicap_we, streams the Futamura-specialized rule frames, and resumes throughput with0dropped packets. - 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+whnfreduction step.
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_roundtripfor 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,MetalSegmentacrossli1/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 0x0BEDCBOR 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 betweenObend.Hardware.CompilerRTL 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_tileDPR 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 FFIcargo test, Verilator RTL simulation, Multiphysics C++ simulation, Z3 SMT2 LEC checks, and 39-byte0x0BEDCBOR 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 Path | Lines | Core Mechanized Capabilities & Key Theorems |
|---|---|---|
[Compiler.lean](file:///Users/ember/dev/obend/lean/Obend/Hardware/Compiler.lean) | 2,560 | SignalExpr, 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) | 789 | Unified 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,881 | Symmetric 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,066 | Implicit 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,532 | Formalization 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) | 529 | Unified 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,438 | Tight-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) | 512 | Halbach 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) | 498 | 1D/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) | 518 | Buck/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:
- Interval-Pruned & Dead-Code-Compacted SSA Geometry Tapes (
Obend/Hardware/GeometryCAM.lean): Following Matt Keeter's libfive / Prospero architecture,GeometryCAM.leancompiles anSdfExprinto a flat linear SSA register tape (List SsaTapeInstr), evaluates 3DBox3Dinterval bounds across the tape to rewrite.min rL rR/.max rL rRinstructions into.copy rLor.copy rRwhenever 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$:
-- 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- Whole-Graph Functorial Reverse-Mode AD & Wavefront Pipelining (
Obend/Hardware/OpenHypergraph.lean):compileGraphAdjointtraverses an arbitrary multi-edgeOpenHypergraphin reverse topological order, replacing each forward hyperedge with its local pullback (localAdjointOps) and automatically inserting.addcotangent-accumulation nodes whenever a forward wire fans out to multiple consumer edges:
-- 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- 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.leanproves thatsynthesizeKrawtchoukPhotonicCouplersrealizes the exact parts-per-million power-splitting ratios $375000 : 500000 : 375000\,\text{ppm}$ ($3/8 : 4/8 : 3/8$), while a#toothnegative test proves that an uncalibrated Pythagorean $[80/60, 50/50, 80/60]$ coupler array is rejected:
-- 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)] = false5.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:
- Stage 1: Lean-lite dependent expression (
Obend.Lower.LeanKernel.LExpr). - Stage 2: Type-erased
Core4open-recursive prototype expression (Obend.Core.Expr). - Stage 3: Closure-converted supercombinator
Leaf.Book(Obend.Leaf.Book). - Stage 4A (FPGA RTL): Synchronous LUT/FF netlist (
Obend.Hardware.Compiler.NetlistModule). - Stage 4B (AMD
CDNA3GPU Wavefront ISA): 64-lane SIMD wavefront instructions (v_add_u32,v_mad_u64_u32,s_cbranch_execz, LDS shared memory banks). - Stage 4C (TPU Systolic Array + Xilinx Versal
DSP58Cascade + Ozaki Base-13FP4 (E2M1)Tensor Core): - Specifically,
SiliconKernel.leanformalizes the Ozaki Scheme in Base-13 (RNS/ residue-slicedFP4 E2M1Tensor Cores), decomposing exact 32-bit integer/fixed-point matrix multiplications into low-bitwidthFP4 (E2M1)tensor-core outer products accumulated without overflow and reconstructed exactly:
-- 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 = nAnd 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:
- Universal Dyadic Interval Arithmetic (
[Obend/Analysis/RealAnalysis.lean](file:///Users/ember/dev/obend/lean/Obend/Analysis/RealAnalysis.lean#L1-L504)): - Formalizes
Interval(lo : Int,hi : Int,lo_le_hi : lo ≤ hi) withInterval.contains (I : Interval) (x : Int) : Prop := I.lo ≤ x ∧ x ≤ I.hi. - Proves the component enclosure lemmas (
Interval.add_mem,Interval.neg_mem,Interval.sub_mem,Interval.mul_mem,Interval.sqr_memincluding the non-negativity tightening0 ≤ x * xfor squares!) and the Universal Fundamental Theorem of Interval Arithmetic (evalInterval_sound) over arbitraryRealExprASTs (.var,.const,.add,.sub,.mul,.neg,.sqr):
-- 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
#toothnegative 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_obendand#obend_declcommands that parse.obendsurface workbooks ([lean/Obend/Frontend/Parser.lean](file:///Users/ember/dev/obend/lean/Obend/Frontend/Parser.lean)), elaborate them intoCore4terms inside the live Lean 4 environment, track reactive cell dependencies viaObend.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 10ProjectionKinds (Code,SliderTable,PhasePortrait,BodePlot,Floorplan2D,SchematicNetlist,WaveformTrace,HollowSolid3D,UsdStageTree,ProofCertificateView) and 3PhysicalViewportKinds (SdfRaymarch3D,FaltblattSchematic,FpgaDieMap), coupled to the interactive 3-stateLawDial(Free/Press/Locked). Dragging a mechanical dimension or filter capacitor slider in the GUI updates the underlyingObend.Slotpin, triggers incrementalPress/Lockedre-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:
-- 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_soundproves 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:
[Obend/Vault/Hyperedge.lean](file:///Users/ember/dev/obend/lean/Obend/Vault/Hyperedge.lean#L1-L634):- A
TurnHyperedgebinds a set of input object slots (inputs : List VaultObjId), output object states (outputs : List VaultObject), participant signatures (approvals : List ParticipantId), and per-participant format-validatedTurnWitnesses (witnesses : List TurnWitness). - Remediating a Council Wave 2 finding,
checkTurnHyperedgenow verifies that every participant'sTurnWitnessstructurally satisfies the expectedObend.Judge.Formatschema (checkTurnWitness : Obend.Judge.Format → TurnWitness → Bool) before admitting the hyperedge (turnHyperedge_witness_format_sound,malformed_witness_blocks_hyperedge). [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):- 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). [Obend/Vault/Rehydration.lean](file:///Users/ember/dev/obend/lean/Obend/Vault/Rehydration.lean#L1-L1749):- Formalizes content-addressed snapshot serialization, Merkle-DAG state dehydrate/rehydrate cycles, and schema-evolution lenses (
rehydrate_dehydrate_roundtrip,schemaLens_preserves_locked_laws). [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):- Connects DeOS Vault objects directly to the
Obend.Hardwarestack: a hardware IP core or mechanical CAD assembly stored in the Vault carries its0x0BEDsilicon/DRC proof receipt as a lockedContractCert, 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):
- 9-Operation Double-Entry
Ledger.Book: - Supports
.transfer,.escrowLock,.escrowRelease,.escrowRefund,.atomicSwap,.batchTransfer,.feeSplit,.dividendDistribute, and.rebalance. - 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). - Agoric Zoe-Style Offer Safety (
Ledger.Seat): - Each participant interacts with a contract through an isolated
Seatspecifyinggive : Allocationandwant : Allocation. - Even if the guest contract code is buggy or adversarial, the host
Ledger.Seatkernel enforces Offer Safety (safeAt)—a seat only commits a reallocation if every participant either receives at least theirwant(satisfiesWant) or gets a full refund of theirgive(isFullRefund), and total tokens across all seats are strictly conserved (payout_exact):
-- 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 seats7.4 Simplex 3-Hop BFT Consensus, Epistemic Clearing & Trace Collapse (Obend/Consensus/ & Obend/Fold/Collapse.lean)
- Simplex BFT Consensus (
[lean/Obend/Consensus/Simplex.lean](file:///Users/ember/dev/obend/lean/Obend/Consensus/Simplex.lean#L1-L814)): - 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). - 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), provesnotarized_uniqueandfinalized_safety:
-- 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- Epistemic Consensus & Proper Scoring Rules (
[lean/Obend/Consensus/Epistemic.lean](file:///Users/ember/dev/obend/lean/Obend/Consensus/Epistemic.lean#L1-L468)): - 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). - Semantic Trace Folding (
[lean/Obend/Fold/Collapse.lean](file:///Users/ember/dev/obend/lean/Obend/Fold/Collapse.lean#L1-L420)): - Proves that internal stuttering steps inside an
Obend.Foldboundary 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/)
[crates/obend-ffi/src/lib.rs](file:///Users/ember/dev/obend/crates/obend-ffi/src/lib.rs#L1-L44):- C-ABI bridge (
obend_eval_core4,obend_verify_receipt) linking the compiled Lean 4 runtime into the Rust workspace. [crates/obend-node/src/lib.rs](file:///Users/ember/dev/obend/crates/obend-node/src/lib.rs#L1-L4628)(4,628 lines):- Production Rust implementation of the DeOS node daemon:
VaultStore: Content-addressed Merkle object store with dehydrated/rehydratedCore4prototype snapshots andTurnHyperedgetransaction pool.SimplexEngine: Asynchronous 3-hop Simplex BFT state machine with Ed25519 quorum certificate aggregation, view-change timers, and deterministicLedger.Book/Ledger.Seatstate transitions.SiliconOffloadDriver: Dispatches compute-intensiveLeaf.Bookreductions and0x0BEDhardware receipt checks to thehardware/rust-ffi& Verilator/FPGA backend.[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/):- Implements the 5-Ring Capability Sandbox (
R0PureLeaf.BookKernel $\to$R1DeterministicCore4$\to$R2LocalSlot/FoldWorkbook $\to$R3Capability-Gated Sandstorm Grain $\to$R4Host Hardware/FPGA Driver). [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 strictseccomp-bpfsyscall filtering (read,write,mmap,futex,exit_group; blockingsocket,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:
- Lean 4 Proof Spine (
[lean/Obend/All.lean](file:///Users/ember/dev/obend/lean/Obend/All.lean)): - 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 inObend.Alland fails compilation if anything outside{propext, Quot.sound, Classical.choice}is encountered. - Negative-Mutation
#toothGate ([lean/Obend/Test/Teeth.lean](file:///Users/ember/dev/obend/lean/Obend/Test/Teeth.lean)): - Verifies that every safety gate (Slot invalidation, C4 monotonicity, Prototype Provenance
LT4, Offer SafetysafeAt, Simplex quorum uniqueness, Interval multiplication, Krawtchouk coupler ratios, DPR bitstream pinning, and TurnWitness format validation) actively rejects malformed or mutated inputs. - 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)): - Executes end-to-end Verilator cycle-accurate RTL simulation, Z3 SMT2 formal equivalence checking (
QF_BVandQF_NRA), multiphysics C++ electro-thermal simulation, and 39-byteTag 0x0BEDCBOR proof certificate verification. - Rust Workspace (
Cargo.toml:obend-ffi,obend-gui,obend-node,obend-sandbox,hardware/rust-ffi): - 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.
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), andnanodregg(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():
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):
#[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:
#[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:
- Decodes
(kind, report_bytes)viadecode_tee_proof(proof_bytes). - Calls
verifier.verify_report(kind, report_bytes)to validate the hardware vendor's cryptographic signature chain. - Checks
&claims.measurement == commitment(the cell'sStateConstraint::Witnessed32-byte commitment must equal the enclave's code measurement). - Checks
claims.report_data == Self::input_commitment(input)?(wherePredicateInput::FieldElement(v)fromgrain_turn::ATTESTATION_SLOTis SHA-256 hashed viaSha256::digest(b"dregg-tee-field-input-v1:" || v.to_le_bytes())or passed raw asPredicateInput::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_PEMembedstee-verify/src/aws_nitro_root_g1.pem(CN=aws.nitro-enclaves, O=Amazon, C=US, valid2019-10-28T13:22:05Zto2049-10-28T14:22:05Z, P-384 public key, SHA-256 fingerprint641a0321a3e244efe456463195d606317ed7cdcc3c1756e09893f3c68f79bb5b). - CBOR
COSE_Sign1&AttDocParsing: CoseSign1is deserialized viaciboriumas a 4-tuple(ByteBuf, ciborium::Value, ByteBuf, ByteBuf)representing[protected, unprotected, payload, signature], optionally wrapped in CBOR tag18. The signature length must be exactly96bytes (r || s, 48 bytes each for P-384).AttDocis deserialized frompayload:
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()anddoc.digest == "SHA384". - X.509 Certificate Chain Verification (
verify_cert_chain): - Parses
pinned_root_derfromAWS_NITRO_ROOT_PEMand assertsdoc.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 viax509-parser. - Checks X.509 validity windows (
cert.validity().is_valid_at(t)) atref_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_Sign1Signature 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_dataExtraction: fold_pcrsverifies thatPCR0(enclave image),PCR1(Linux kernel + bootstrap), andPCR2(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_datarequiresdoc.user_datato beSomeand at least 32 bytes; ifdoc.user_datais 32 bytes it copies it directly intoclaims.report_data(rejecting documents with missinguser_dataso an emptyuser_datacan never collide with[0u8; 32]).- Sets
claims.tcb = TcbStatus::NoPolicyOnPlatformbecause Nitro attestation documents do not expose a numeric TCB SPL vector. - Document Freshness Enforcement (
check_nitro_freshness): - Added in commit
a9d5df4dbto close audit finding F10: fails closed ifnow_secs == 0, ifdoc.timestamp == 0, ifdoc_ts > now_secs + MAX_FUTURE_SKEW_SECS(60seconds), or ifnow_secs - doc_ts > max_age_secs(defaultMAX_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):
| Constant | Byte Offset | Size | Field & Verification Rule |
|---|---|---|---|
OFF_VERSION | 0x000 | 4B (u32) | Report format version; must be 2 or 3 (MIN_REPORT_VERSION = 2, MAX_REPORT_VERSION = 3) |
OFF_GUEST_SVN | 0x004 | 4B (u32) | Guest Security Version Number; checked against SnpPolicy::min_guest_svn |
OFF_POLICY | 0x008 | 8B (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_VMPL | 0x030 | 4B (u32) | Virtual Machine Privilege Level (0..=3); must be 0 under default policy |
OFF_SIGNATURE_ALGO | 0x034 | 4B (u32) | Must equal SIG_ALGO_ECDSA_P384_SHA384 = 1 |
OFF_CURRENT_TCB | 0x038 | 8B (u64) | Current platform TCB_VERSION |
OFF_KEY_INFO | 0x048 | 4B (u32) | Bits [4:2] (SIGNING_KEY = (key_info >> 2) & 0b111) must equal SIGNING_KEY_VCEK = 0 (VLEK 1 rejected) |
OFF_REPORT_DATA | 0x050 | 64B | Guest-supplied REPORT_DATA; report_data_32() extracts [0x050..0x070] |
OFF_MEASUREMENT | 0x090 | 48B | 384-bit launch digest (MEASUREMENT); folded_measurement() computes SHA-256(measurement) |
OFF_HOST_DATA | 0x0C0 | 32B | Hypervisor-supplied HOST_DATA |
OFF_REPORTED_TCB | 0x180 | 8B (u64) | REPORTED_TCB bound into the VCEK certificate extensions |
OFF_CHIP_ID | 0x1A0 | 64B | Unique 512-bit processor CHIP_ID |
OFF_SIGNATURE | 0x2A0 | 512B | ECDSA 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:
self.fmc >= floor.fmc
&& self.bootloader >= floor.bootloader
&& self.tee >= floor.tee
&& self.snp >= floor.snp
&& self.microcode >= floor.microcodeARK → 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):
| Product | Family/Model | Pinned ARK SHA-256 | Pinned ASK SHA-256 |
|---|---|---|---|
| Milan (Zen 3) | Family 19h, Model 00h–0Fh | 69D063B45344D26A2E94E1F4210DE49EF555308287D4C174445C95639A540BCD | 767B409B0DC90F5D7F2E2CE3E63D0C8B84E8A3122A557D5D56D3B1B6A82C4C38 |
| Genoa (Zen 4) | Family 19h, Model 10h–1Fh / A0h–AFh | 4C6598D19C18719C5DFD4A7D335F674E5BFE1D8F800CEA2CF270C10D103DB2F1 | 84B8F522B5B9A77C779A2C8C60C90F6623082917D981E5A9786E9244D4D34394 |
| Turin (Zen 5) | Family 1Ah, Model 00h–1Fh | 1F084161A44BB6D93778A904877D4819CAFA5D05EF4193B2DED9DD9C73DD3F6A | 94C13A3B3F9B7B2B1B6877F9E9C69F63922416C7476645F3F1B84F0F7F4D5D0F |
verify_vcek_against_amd_root executes a 5-stage verification:
- ARK Self-Signature: Verifies
SHA256(ark_der) == product.ark_sha256()and checks the ARK self-signature viaverify_rsassa_pss_sha384(OID1.2.840.113549.1.1.10, RSA-4096 PSS with SHA-384 digest, MGF1-SHA-384, 48-byte salt viarsa::pss::VerifyingKey::<Sha384>). - 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. - VCEK ← ASK Signature: Asserts
vcek.issuer() == ask.subject(), rejects CA VCEKs (vcek.is_ca()), and verifies the signature onvcek.tbs_certificateagainst the ASK's RSA-4096 PSS key. - Leaf P-384 Public Key Extraction: Requires algorithm OID
1.2.840.10045.2.1(id-ecPublicKey) with curve parameter OID1.3.132.0.34(secp384r1). - AMD VCEK X.509 Extensions (
extract_vcek_extensions): Parses AMD Private Enterprise Number3704(1.3.6.1.4.1.3704.1.*) DER INTEGER / OCTET STRING extensions: 1.3.6.1.4.1.3704.1.3.1(blSPL— Bootloader SVN)1.3.6.1.4.1.3704.1.3.2(teeSPL— PSP OS / TEE SVN)1.3.6.1.4.1.3704.1.3.3(snpSPL— SNP firmware SVN)1.3.6.1.4.1.3704.1.3.8(ucodeSPL— Microcode patch level)1.3.6.1.4.1.3704.1.3.9(fmcSPL— Turin FMC SVN; required on Turin)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](rejectingMaskChipId=1), andreport.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: POLICYbit 17 (POLICY_RESERVED_MBO = 1 << 17) must be1and bits63:26must be0(snp.rs:581-594).POLICYbit 19 (POLICY_DEBUG = 1 << 19) must be0(!policy.allow_debug,snp.rs:595-600) — any debug-enabled guest (where hypervisorSNP_DBG_DECRYPT/SNP_DBG_ENCRYPTcan read/write private memory) is unconditionally refused.POLICYbit 18 (POLICY_MIGRATE_MA = 1 << 18) must be0(!policy.allow_migrate_ma,snp.rs:601-606).report.vmpl < 4and(policy.allowed_vmpls & (1 << report.vmpl)) != 0whereallowed_vmpls = 0b0001(VMPL == 0only, 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'sreported_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_SHA256pins the SHA-256 digest of the DER-encoded Intel SGX Root CA (CN=Intel SGX Root CA, O=Intel Corporation, C=US):
44A0196B2B99F889B8E149E95B807A350E7424964399E885A7CBB8CCFAB674D3- Quote Header & DCAP Verification (
verify_tdx_core): - Parses the quote via
dcap_qvl::quote::Quote::parse(report_bytes)and checksquote.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 checksSHA256(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()), packingmr_td(48B),rt_mr0(48B),rt_mr1(48B),rt_mr2(48B),rt_mr3(48B), andreport_data(64B) intoTdxVerifiedReport. - Measurement Folding & TCB Status:
TdxVerifiedReport::folded_measurement()hashes the 4 static boot registers (excluding runtimeRTMR3): $$\text{measurement} = \text{SHA-256}(\text{MRTD} \mathbin{\Vert} \text{RTMR}_0 \mathbin{\Vert} \text{RTMR}_1 \mathbin{\Vert} \text{RTMR}_2)$$- Default
accepted_statusescontains only{"UpToDate"}; any other FMSPC TCB status (OutOfDate,SWHardeningNeeded,ConfigurationNeeded,Revoked) yieldsTcbStatus::BelowPolicy, which causesTeeWitnessedPredicateVerifierto 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_SVNunvalidated):SnpAttestationReportoriginally discarded bytes0x008..0x034, permittingDEBUG=1orVMPL=3reports. Remediated in commit4d98292c2(2026-09-30) viaSnpPolicy. - F2 (CRITICAL — SEV-SNP
reported_tcbandchip_idnot 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 acceptingMaskChipId=1zeroedchip_id. Remediated in commit4d98292c2(snp.rs:554-574). - F3 (HIGH — SEV-SNP CRL checking): Added
ark_crl_der/ask_crl_derchecking onSnpVerifierin commit4d98292c2(snp.rs:463-474,543-552). - F10 (MEDIUM — Nitro freshness bypass when
now_secs == 0): Remediated in commita9d5df4db(2026-09-30) soNitroVerifier::new()seeds wall-clock time (SystemTime::now()) andcheck_nitro_freshnessfails closed onnow_secs == 0or 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-nsmon Linux) opens/dev/nsmviaaws_nitro_enclaves_nsm_api::driver::nsm_init()(failing closed iffd < 0), issuesnsm_process_request(fd, Request::Attestation { user_data: Some(ByteBuf::from(report_data.to_vec())), nonce: None, public_key: None }), closes the descriptor withnsm_exit(fd), and returns the rawCOSE_Sign1bytes fromResponse::Attestation { document }.QuoteProducer::produce_predicate_proofbinds a 32-bytereport_datacommitment (matchinggrain_turn::ATTESTATION_SLOT) into the hardware quote and wraps it viaencode_tee_proof(self.kind(), &raw).serve_single_requestserves the enclave quote over newline-delimited JSON (ProduceRequest { report_data_hex }→ProduceResponse { ok, quote_kind, proof_hex, error }, capped atMAX_FRAME_BYTES = 1 << 20bytes) across anAF_VSOCKor 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:
- Generates a fresh 32-byte random nonce (
nonce_bytes: [u8; 32]) and encodes it as a 64-character lowercase hex string (nonce_hex). - Fetches
GET /e2e/instances/{chute_id}(returning instance list withinstance_idande2e_pubkeyBase64 ML-KEM-768 public key) andGET /chutes/{chute_id}/evidence?nonce={nonce_hex}(returning per-instancequoteBase64 Intel TDX v4 quote,gpu_evidence, andcollateral). - Calls
verify_instance_evidence, which invokesTdxVerifier::verify_tdx_core("e_bytes)followed byTdxVerifier::apply_chutes_bindings. - Anti-MITM Session Binding (
chutes_report_data_binding): - Validates that
nonce_hexis 64 hex characters ande2e_pubkey_b64Base64-decodes to exactlyCHUTES_MLKEM768_PK_LEN = 1184bytes (tdx.rs:268-277). - 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}))$$
- Verifies in constant time (
subtle::ConstantTimeEq) that the hardware-signed TDX quote'sreport_data[0..32](at byte offset568of the TDX v4 quote) equalsexpected:
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)againstChutesMeasurementsand requiresreport.tcb_ok(unlessallow_tcb_ProceedAnywayis explicitly set for dev collateral). - Caches the resulting
AttestedSessioninSessionCachewith a 30-minute TTL (DEFAULT_TTL_SECS = 1800) and automatic single-retry eviction on HTTP466(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 = 1184bytesMLKEM_SK_SIZE = 2400bytesMLKEM_CT_SIZE = 1088bytesNONCE_SIZE = 12bytesTAG_SIZE = 16bytesBLOB_HEADER_SIZE = 1100bytes (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 withflate2::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
blobtoPOST https://api.chutes.ai/e2e/invokewith headersX-Chute-Id,X-Instance-Id, andContent-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]usingresponse_sk, deriveskey_respvia HKDF-SHA256 withinfo = b"e2e-resp-v1", decrypts withChaCha20Poly1305, and gunzips (capped atMAX_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 viaStreamDecryptor::from_init_b64usinginfo = b"e2e-stream-v1"(retaining only the 32-bytestream_key), and each subsequentdata: {"e2e": "<b64 nonce(12) || ct || tag(16)>"}chunk is authenticated and decrypted viaStreamDecryptor::decrypt_chunk_b64.
2.3 Standalone 6-Link Provenance Verifier (attest-check / dungeon-attest-check)
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):
- Link 1 —
quote digest(check_quote_digest): Base64-decodesraw_quote_b64, verifiesquote_bytes.len() == record.quote_lenandquote_bytes.len() >= MIN_TDX_V4_QUOTE_LEN (584), and checkshex(SHA-256(quote_bytes)) == record.quote_sha256_hex. - Link 2 —
session binding(check_session_binding): Checksnonce_hex.len() == 64(valid hex), Base64-decodese2e_pubkey_b64and checkspk_bytes.len() == 1184(ML-KEM-768 public key size), readsreport_data[0..32]directly from the TDX v4 quote at byte offsetTD10_REPORT_DATA_OFFSET = 568(48 + 520), and verifiesreport_data[0..32] == SHA-256(nonce_hex || e2e_pubkey_b64)==record.report_data_32_hex. - Link 3 —
measurement registry(check_measurement_registry): Parses the TD10 report body, checksmr_td,rt_mr0,rt_mr1,rt_mr2against the record's hex fields, checksSHA-256(MRTD || RTMR0 || RTMR1 || RTMR2) == record.folded_measurement_hex, and verifies membership inexpected_measurements(ChutesMeasurements). - 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 withtee_provenance_commit_hex. - Link 5 —
Intel root pin(check_intel_root_pin): Parsescollateral.root_ca_pem_chain, locates the self-signed root (cert.Subject == cert.Issuer), and verifiesSHA-256(root.raw_der) == INTEL_SGX_ROOT_CA_SHA256(44a0196b...674d3). - Link 6 —
DCAP signature chain(check_dcap_chain): ReconstructsTdxVerifierwith the embedded collateral atverified_at_unix_ms / 1000(with a 60s skew fallback for leaf quote issuance skew) and runsverifier.verify_tdx_core("e_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 = 4order slots (i ∈ {0, 1, 2, 3}), 4 owners (owner_id = i).TICK_COUNT = 4discrete price ticks (0, 1, 2, 3), plusClearedTick::NoCross(5 total tick states).QUANTITY_MAX = 15(q_i ∈ 0..=15), so maximum single-side aggregate quantity isMAX_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):
BatchDigestMismatch: header digest matches the committed order slots.PublicationInvalid:volume <= SLOT_COUNT * QUANTITY_MAX(60) andNoCross ==> volume == 0.InclusionFailed: Merkle inclusion proof of(slot, owner_id, fill_i, salt_i)againstdelivery_root.Overfill:fill_i <= order.quantity.BelowMinimum:fill_i == 0 || fill_i >= order.min_fill.VolumeBelowFill:fill_i <= header.volume(since a single participant's fill cannot exceed total cleared volume).CrossedWithoutFill: ifheader.cleared_tick == NoCross,fill_i == 0; ifTick(p)is worse thanorder.limit_tick,fill_i == 0.ProRataImplausible(pro_rata_feasible): if the order is eligible atTick(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}]$ producesfill_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):
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 (1forNoCrossat $V=0$, plus $4 \times 8 = 32$ forTick(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 acceptsfill = 2because $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 atTick(2)instead of the canonical tie-brokenTick(1).
As docs/VERDICTS.md concludes:
V3 (
shielded-alone-insufficient, REFUTED): "An unproved shielded matcher can forge 377 of 1,125 outcomes (376false accepts) and all 33 of 33 well-formed(cleared_tick, volume)pairs onprice_tie_lowwhile 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.
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 Name | Priority | Budget / Period | Program Image | Role & Shared Memory |
|---|---|---|---|---|
verifier | 100 | 1000 / 1000 | verifier-pd.elf | Lean-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) |
executor | 120 | 5000 / 10000 | executor-pd.elf | Links 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 |
persist | 80 | — | persist-pd.elf | Append-only hash-chained journal over shared memory (persist_inbox, persist_outbox) |
net | 60 | — | net-pd.elf | MMIO driver (0x0a003000, IRQ 79) for virtio-net-device with DMA ring at 0x4_010_000 |
net_client | 59 | — | net-client-pd.elf | Bridges net rx/tx rings into the executor turn inbox |
app | 50 | — | app-pd.elf | Untrusted 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.bssheap 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 Plonky3CounterSquareAir(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) overBabyBear(p3_baby_bear), committed the trace withSerializingHasher64<Blake3>(p3_blake3) +CompressionFunctionFromHasher(2 -> 32 bytes), opened viaTwoAdicFriPcs(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-writtenCounterSquareAirwithdregg_p3_pcs::prove_descriptoranddregg_p3_pcs::verify_descriptoroverLEAN_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:
#[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>checksis_attenuation(self.rights, mask)((granted.0 & !held.0) == 0, i.e.,granted ⊆ held) identically regardless of backing (Target), mirroringseL4_CNode_Mintrights masking locally and Macaroon/Biscuit caveat append remotely.Capability::bounds(&self)returns the exact synchrony gradation: atn == 1(Target::Local,Target::HostPd, orTarget::Distributed { quorum_size: 1 }),revocation_immediate = trueandcommit_synchronous = true.
Lean 4 Formalization (Dregg2.Firmament.CapGradation & SeL4Abstract)
metatheory/Dregg2/Firmament/CapGradation.lean:theorem attenuate_decision_backing_agnostic(lines 112–115):
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):
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):
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):
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]metatheory/Dregg2/Firmament/SeL4Abstract.lean(transcribing Data61l4v@e2f32e54spec/abstract/Structures_A.thyandCSpaceAcc_A.thy):theorem seL4_derive_cap_non_amplifying(lines 128–134):
theorem seL4_derive_cap_non_amplifying (c : SeL4Cap) (mask : CapRights) :
∀ r, r ∈ (maskCapRights mask c).rights → r ∈ c.rights :=
maskCapRights_subset c masktheorem alpha_total_iff_used(lines 195–199):
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):
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_pdcreates an IPCsocketpair(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 appliesconfine_current_process()before executing the PD closure:- macOS (
apply_seatbelt): Callssandbox_init(profile, 0, &mut errbuf)with the deny-by-default SBPL profile:
(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): Setsprctl(PR_SET_NO_NEW_PRIVS, 1), unsharesCLONE_NEWUSER | CLONE_NEWNET | CLONE_NEWNS | CLONE_NEWIPC, applies Landlock ABI v1 with empty ruleset (LANDLOCK_ACCESS_FS_READ_FILE | WRITE_FILE | EXECUTEhandled and denied), and installs a classic BPF seccomp filter (SECCOMP_SET_MODE_FILTER) that permits onlyread,write,recvmsg,sendmsg,futex,mmap,munmap,mprotect,brk,rt_sigreturn,exit_group,clock_gettime,getrandom,sched_yield,close,poll/ppoll, andioctl(fd, FIONBIO)(0x5421matched on the full 64-bit request per commit292829518), or traps to a supervisor fd viaSECCOMP_RET_USER_NOTIF(provider_door). grain-jail/src/lib.rswraps the confined child inConfinedBrain<C: BodyChannel>: the jailed process holds zero secret keys and receives only opaque state commitments (WorldView { tick, current_state_commitment, available_actions }), returning a chosenaction_indexover 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):
Policyspecifies{ read, write, exec, hidden, connect }, enforcingCONNECT_MAX = 2Unix domain sockets (connect.rs:14).- Before spawning,
confinecanonicalizes all paths (O_NOFOLLOWwhere required), refuses any policy where aread/write/execpath overlaps ahiddenpath (ConfineError::Exposed), refuses any program binary not covered byreadorexec(ConfineError::ProgramOutside, commit6278ab8), and validates everyconnectsocket viaconnect::validate(S_IFSOCK, mode0600or0660, owned byeuid, ancestor chain verified viacustody::chainStrictModes walk). die_with_parent()(commit1ab410e, 2026-10-24) binds child lifetime to its parent viarustix::process::set_parent_process_death_signal( Some(Signal::KILL))on Linux (checkinggetppid() != ppidafter registration to close the fork race) and a backgroundorphan-watchthread pollinggetppid()on macOS.- Enforces confinement via
/usr/bin/sandbox-execon macOS (emitting(deny file-read* (subpath ...))after(allow ...)sohiddenoverrides broader read grants) or/usr/local/libexec/nd-bwrapon Linux (--unshare-all --unshare-user --disable-userns --cap-drop ALL --new-session --die-with-parent, binding an empty0400tmpfs overhiddendirectories and/dev/nulloverhiddenfiles).
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 randomnonce: [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 knowingroot_key; truncating $C_{n+1}$ requires inverting HMAC-SHA256 to recover $T_n$. Signature comparison usessubtle::ConstantTimeEq. - Third-Party Caveats (
ThirdPartyCaveat): add_third_party_caveatgenerates 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_dischargebinds the discharge macaroon to the authorizing root macaroon by appending caveat IDCAV_BIND_TO_PARENT (0xFE)containing $\text{SHA-256}(T_{\text{root}})$.verify_dischargeis fail-closed: it enforces a 300-second freshness window (MAX_DISCHARGE_AGE = 300) and rejects any discharge macaroon that lacks aCAV_BIND_TO_PARENTcaveat 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 Base64MacaroonToken) andeb2_(Ed25519 + DatalogBiscuitTokenviabiscuit-authv6.0) behind theAuthTokentrait. - Revocation Non-Membership & Hybrid Root Attestation (
revocation.rs): SortedRevocationTreemaintains revoked token hashes in sorted order in a BLAKE3 Merkle tree and produces aNonMembershipProofconsisting 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.AttestedRevocationRootsigns 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 ifpq_signatureisNone.
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
Blockcontains:
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
Credentialcarriesroot_pub: VerifyingKey,root_pub_ml_dsa: Option<Box<MlDsaPubBytes>>,blocks: Vec<Block>, and the bearer tail secrettail: SigningKey(zeroized on drop, plus a cachedtail_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 againstlast.next_pubbefore touching any post-quantum verification. - Step 2 — Classical + PQ Chain Verification: Pins
expected_key = root.ed25519andexpected_pq = root.ml_dsa_65from the enrolledHybridRootPublic(never trusting the wire's self-reportedroot_pub_ml_dsa!). For every block $i$, verifies bothexpected_key.verify_strict(&msg, &block.sig)andpq::ml_dsa_verify(&expected_pq, &msg, &block.sig_ml_dsa)(under FIPS 204 contextCRED_PQ_CTX = b"dregg-auth v1 credential mldsa"). Rejects withVerifyError::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 everyPredacross all blocks using 3-valued logic (Outcome::{Pass, Fail, Unbound}). If a clock or attribute is absent fromContext, comparison predicates returnUnbound, andPred::Not(Unbound)remainsUnbound(which fails closed at top level), soNot(AttrEq("role", "guest"))can never invert a missing"role"attribute into a pass! - Lean 4 Proofs (
Dregg2/Authority/BiscuitGraph.lean— namespaceAuthority.Biscuit— plusTokenCapBridge.lean&Dregg2/Crypto/CapabilityChain.lean; extended in Nov 2026 by/Users/ember/dev/qsagqsag-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::combineimplements 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 throughOnceLockhooks populated bydregg_exec_lean::register_lean_fips204_verify(), which links theleanc-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_unauditedwrites a diagnostic banner directly to file descriptor 2 vialibc::write(2, ...)(eprintln_fd2, bypassing Rust's bufferedstd::io::stderr()so the reason is never lost on abort) and callsstd::process::abort()(SIGABRT, which cannot be caught bystd::panic::catch_unwind).- Even if
DREGG_ALLOW_UNAUDITED_PQ=1is set in the environment, settingDREGG_REQUIRE_LEAN=1revokes the override (audit.rs:155-168) and forcesstd::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_msisproves 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:
issuemints aCredentialbacked 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_anonymousproduces an unlinkablePresentationusing a per-presentationpresentation_nonce(rerandomized_leaf = Poseidon2(issuer_leaf, nonce)) so multiple presentations of the same credential cannot be correlated (unlinkable multi-show), while optionally attachingGte/Lte/InRangepredicate proofs (CredentialPredicate) and a non-membershipRevocationProofagainst the revocation tree.- Injective 9-Lane Base-$2^{28}$ Field Encoding (
field_limbs9): - In
credentials/src/verification.rs,compute_revealed_terms_commitmenthashes 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-injectivefrom_le_bytes % Preduction. - Fail-Closed Verification & Residual-Gap Honesty (
verification.rs:140-215): verifyrequiresexpected_federation_root == proof.federation_root, checks expiration, verifiesRevocationProof, checksrevealed_terms_commitment, and fail-closes onexpected_predicates(VerificationError::PredicateProofInvalid), documenting in-code that until the emitted predicate AIR bindsfacts_rootas 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_delegateconstructs a child mandate whosetargetis fixed toself.target, whose rights are intersected (&self.keep & want), whosebudgetis clamped (ask_budget.min(self.budget)), and whosecaveatis intersected (self.caveat.intersect(extra_caveat)).DelegTreeenforces:well_attenuated: every child's rights, budget, target, and caveat narrow its parent's.no_amplify: every node in the tree satisfiesm.keep.is_subset(&root.keep).budget_bounded: every node satisfiesm.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>andmaterialize_revoke(child)→Effect::RevokeDelegation { child }.- Lean 4 Theorems (
Dregg2/Agent/Mandate.lean): theorem subtree_rights_le_root:
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).keeptheorem materialize_non_amplifying,theorem children_no_oversubscribe,theorem subtree_budget_le_root, andtheorem 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") withSlotCaveat::Monotonic,TIP_SLOT = 3("tip"), andENTRY_BASE + i("entry0","entry1", ...) each withSlotCaveat::WriteOnce. - Each entry stores
link_hash(prev, claim) = BLAKE3("dregg-provenance-link\x01" || prev || claim)(withIncrementalChainVerifiermaintaining $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) = nonetheorem 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) = nonetheorem 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) = nonetheorem 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), andTOOL_ID_SLOT = 3(WriteOnce). deleg_admitcalls the@[export dregg_deleg_admit]Lean functionDregg2.Apps.DelegAdmit.delegAdmitdirectly acrossdregg-lean-ffi.- Lean 4 Headline Theorem (
ToolAccessDelegation.lean:179-193,#assert_axioms-clean):
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." (Importingmacaroon,token,cell,bridge,audit,circuit).d5be7258e(2026-05-20): Added the distributedintentengine (Intent,MatchSpec,Fulfillment).77b998170/d1b48d885(2026-05-24): Added thecredentialscrate (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): Createddregg-auth(dga1_/eb2_offline-attenuable agent permission wedge and MCP gateway profile).8ef312b5e,a744edfc0,2490e7f33,f49b87b35(2026-06-13) &7cb8626a41(2026-06-15): Built thesel4/Microkit 2.2.0 6-PD system,dregg-firmament(Capabilityunifying seL4 CNode caps and distributed cell caps), andverifier-starkproving 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): Builtgrain-jail(ConfinedBrain+ macOS Seatbelt / Linux Landlock+seccomp-BPF process confinement).13eff7a3f,7aa833047,0cdfd2ed5,8f5d51acf,f52d8ed91(2026-07-09): Consolidated all post-quantum cryptography intodregg-pq, routing ML-DSA-65 (FIPS 204) and ML-KEM-768 (FIPS 203) throughleanc-compiled Lean-verified cores with the uncatchablestd::process::abort()audit gate (audit.rs).19205169f(2026-07-11): Builtpqvrf(Esgin et al. FC 2021 Module-LWE / Module-SIS lattice VRF bound to LeanDregg2.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): Builttee-verify(NitroVerifier,SnpVerifierwith Milan/Genoa/Turin RSA-4096 PSS ARK→ASK→VCEK chains,TdxVerifier) andtee-produce(NitroNsmBackendover/dev/nsm).9d5d06853(2026-07-23),6f38efbe3(2026-07-26),4bcb934a3(2026-07-27): Builtdregg-chutes-e2ee(confidential GPU TDX attestation + ML-KEM-768 / HKDF-SHA256 / ChaCha20-Poly1305 E2EE) andattest-check(dungeon-attest-check6-link provenance verifier).ac77a4d(2026-08-18): Proved indegg-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/33headers) 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): Builtnanodregg/sandbox(deny-by-default macOSsandbox-execand Linuxnd-bwrapconfinement,custodyStrictModes directory walk,CONNECT_MAX = 2socket validation, anddie_with_parent).