LeanUI Docs
← Open LeanUI Studio GitHub

03 · Formal Verification & Lean 4 Proofs#

LeanUI combines instant static analysis (running on every edit in <15ms) with real machine-checked Lean 4 theorem proving (running the actual Lean 4 compiler in WebAssembly or natively via Lake).


Two-Tier Verification Architecture#

TierEngineLatencyWhat It Checks
Tier 1 · Instant Static Verifier@leanui/verifier (TypeScript)~2–15 msPort type compatibility, computed cycles, expression typing, bounded invariant counterexample search, WCAG AA contrast math, i18n locale coverage, View A11y (alt, labels, slider bounds), user proof_rule checks, and incremental Solution contracts.
Tier 2 · Real Lean 4 Kernel@leanui/lean-wasm (Browser WASM) or @leanui/lean-server (Native lake env lean)~0.4–1.5 sCompiles the generated .lean specification through the actual Lean 4.14.0 typechecker & kernel, mechanically verifying every theorem with zero sorry placeholders.

Choosing the Lean 4 Backend#

In the Verification Console (▤ Console), switch the backend dropdown between:

  • WASM (Browser) — Runs Init-only Lean 4 inside a persistent browser Web Worker (zero backend needed; works on GitHub Pages).
  • Native (Local) — Connects to the local Vite/Node bridge (@leanui/lean-server) invoking your machine's lake env lean --json.

Click λ Prove in the topbar (or inside the ✓ Proofs panel) to run the Lean 4 kernel on the active specification.

LIVE GENERATED SVG · AUTO-UPDATED ON BUILD
Open SVG ↗
Formal Proofs & 5-Mode Proof Visualizer Panel — Matrix, Dependency Graph, Tactic Tree, Counterexample & AST Formal Proofs & 5-Mode Proof Visualizer Panel — Matrix, Dependency Graph, Tactic Tree, Counterexample & AST
Formal Proofs & 5-Mode Proof Visualizer Panel — Matrix, Dependency Graph, Tactic Tree, Counterexample & AST
LIVE GENERATED SVG · AUTO-UPDATED ON BUILD
Open SVG ↗
Verification Console Panel — WASM vs Native Lake Backend, Solution Verification & Clickable Diagnostics Verification Console Panel — WASM vs Native Lake Backend, Solution Verification & Clickable Diagnostics
Verification Console Panel — WASM vs Native Lake Backend, Solution Verification & Clickable Diagnostics
LIVE GENERATED SVG · AUTO-UPDATED ON BUILD
Open SVG ↗
Lean 4 Specification Panel — Live Formal Code & Bidirectional Line-to-Node Mapping Lean 4 Specification Panel — Live Formal Code & Bidirectional Line-to-Node Mapping
Lean 4 Specification Panel — Live Formal Code & Bidirectional Line-to-Node Mapping

All 14 Built-In Lean 4 Theorems & User-Authored Proof Language#

Every generated Lean 4 specification emits your user-authored Lean 4 declarations (lean_type, lean_tactic, lean_def, lean_theorem) together with a formal MVU model (structure ViewModel, def initState, inductive Action, def update, def Invariant, def rootView) and machine-checked theorems:

TheoremScopeFormal Statement
init_preserves_invInitial State SafetyInvariant initState
step_preserves_invAction & Setter Induction∀ s a, Invariant s → Invariant (update s a)
uiSpec.reachable_preserves_invMulti-Step Reachability∀ trace : List Action, Invariant (runActions initState trace)
view_well_formedState-Dependent View Soundness∀ s, Invariant s → VNode.wellFormed s rootView (proves slider min < max & value bounds, non-empty alt text, accessible labels, valid structure across all 37 View kinds)
reachable_view_well_formedReachable View Soundness∀ trace, VNode.wellFormed (runActions initState trace) rootView
update_deterministicReducer Determinism∀ s a s₁ s₂, update s a = s₁ → update s a = s₂ → s₁ = s₂
styles_wcag_aa (when style nodes exist)Design System Contrast ProofStyleBindingsValid styleSheet usedStyleTokens (proves every style token meets WCAG AA luminance contrast & every bound view token exists)
resources_resolved (when resource nodes exist)i18n Resource Coverage ProofResourceBundleValid locales entries usedKeys (proves every locale defines every key & every view resourceKey resolves)
data_sources_valid (when datasource nodes exist)Data Source Schema & Endpoint ProofDataSourcesValid dataSources (proves non-empty schemas, unique fields, valid online endpoints, and defined primary keys)
foreign_keys_valid (when FKs exist)Relational Foreign Key Integrity ProofForeignKeysValid foreignKeyChecks (proves every MS Access / SQL foreign key references an existing table & column and every seed record satisfies referential integrity)
data_queries_valid (when data_query nodes exist)Declarative Query Schema ProofDataQueriesValid dataQueries (proves every wired data_query has a valid primary source, join keys, and schema-resolved sort/search/aggregate fields)
control_templates_valid (when control_template or template-scope nodes exist)Templated Control, Root Container & Resource ProofControlTemplatesValid controlTemplates (proves every template has ≥ 1 visual part or nested View control, every {tpl:prop} across root/parts/nested controls is declared, and every {res:token} resolves in the wired Resource Dictionary; paired with static TPL001–TPL005 checks including grid columns & scroll min-height bounds — see Chapter 08)
state_machines_valid (when state_machine nodes exist)Finite State Machine Transition SoundnessFSMsValid stateMachines := by decide (proves every state_machine declares ≥ 1 state, its initialState belongs to states, and every transition's from/to endpoints are valid declared states with non-empty event names)
validators_valid (when validator nodes exist)Multi-Rule Validator CompletenessValidatorsValid validators := by decide (proves every validator declares ≥ 1 rule and every rule carries non-empty label, expr, and error message)

Authoring Full Lean 4 Proofs & App-Callable Functions#

Use the Lean 4 Proof Language nodes directly on the canvas (see the Lean 4 Proof & App Workbench preset):

  • lean_type: Define algebraic inductive types, structure records, class typeclasses, or abbrev aliases with deriving clauses.
  • lean_def: Define verified pure functions (def, partial def, noncomputable def, instance) that are simultaneously proved by your lean_theorem nodes AND called directly inside App computed, predicate, and action expressions (e.g., used = safeConsume(used, 10, tierLimit(tier))).
  • lean_theorem: Write standalone or app-linked theorem, lemma, example, or axiom blocks using either raw Lean 4 tactics/terms OR the Visual Tactic Proof Builder (ƒ) (intro, simp, rw, cases, induction, split, apply, exact, have, omega, decide, rfl, constructor). Inside ƒ, click λ Check Proof to run the live Lean 4 WASM/Native kernel on your draft tactic script and inspect goal diagnostics, or click ⚡ Quick-Fix Tactics (+ omega, + simp, + decide, + rfl, + intro h, + cases) to splice tactics directly before ∎ QED. Also supports customImports for referencing shared Lake modules in native mode.
  • lean_tactic: Define reusable macro, syntax, notation, and @[simp] tactic helpers.

User-Defined Verification Rules (proof_rule)#

In addition to built-in invariants, you can author custom mathematical theorems visually using proof_rule nodes (click + Proof Rule in the ✓ Proofs panel or Palette):

  1. ViewConstraint — Proves a state-conditioned UI/ViewModel property across all invariant-preserving states (∀ s, Invariant s → Pre s → Conclusion s).
  2. HoareTriple (ruleKind: 'transition') — Proves a Hoare triple {Invariant ∧ Pre} Action {Conclusion} for a specific target Action constructor (targetActionName).
  3. ReachableGoal (ruleKind: 'reachability') — Proves a safety conclusion holds across all reachable action traces (theorem reachable_rule_<name>).

Each proof_rule supports:

  • Precondition Expression (preconditionExpr, defaults to true)
  • Conclusion Expression (expr, editable via text or the Visual Logic Node Editor ƒ)
  • Live Verification: Checked immediately by the static verifier, evaluated frame-by-frame in the Runtime Timeline Debugger, and compiled into a formal Lean 4 theorem verified by the Lean kernel.

Verified Styles (Inheritance & WCAG AA/AAA) & Parameterized ICU i18n Resources#

  • Style Nodes (style):
    • Define tokenName, optional parent extendsToken (style token inheritance with automatic cycle/missing-parent detection STYLE004), bgHex, fgHex, borderHex, fontSizePx, radiusPx, paddingPx, and minContrastX10 (default 45 = 4.5:1 WCAG AA; 70 = 7.0:1 WCAG AAA).
    • Wire the style output port into any View node's style input port.
    • Both @leanui/verifier and the Lean 4 styles_wcag_aa theorem evaluate the resolved inherited style and reject insufficient contrast or dangling token references.
  • Resource Nodes (resource):
    • Define supported locales (e.g., ["en", "de", "pl"]), keyed translation entries with parameterized {name} & ICU pluralization ({count, plural, =0 {Empty} one {# item} other {# items}}), and design tokens supporting semantic {res:alias} → {res:base} chains.
    • @leanui/verifier enforces full locale coverage (RES001), valid view keys (RES002), cross-locale ICU placeholder parity (RES003), and token alias cycle detection (RES004) alongside the Lean 4 resources_resolved theorem.
    • Switch locales live inside the Live Preview dropdown (🌐 EN / DE / PL) and test responsive layouts across Desk | Tab | Mob preview frames.

Using the Proofs Matrix & Interactive Proof Visualizer (✓ Proofs)#

The ✓ Proofs dockable panel gives both a real-time theorem matrix and an Interactive Lean 4 Proof Visualizer with 5 sub-views:

  • Matrix: Complete checklist of built-in theorems, user proof_rule cards, WCAG style contrast proofs, and i18n locale coverage with ◫ (Proof Tree), ▶ (Infoview Step-Through), λ (jump-to-Lean), ● (breakpoints), and ƒ (Visual Logic Editor).
  • Blueprint (Lean Blueprint–style SVG DAG): Visualizes the full 4-stage validation pipeline (1. Static Gate → 2. Base Proofs → 3. Induction & Rules → 4. Lean 4 Kernel QED); click any stage or theorem to highlight its formal dependency ancestry.
  • Proof Tree (Paperproof-style Deduction Tree): Displays Given Hypotheses, Tactic Derivation rules, branching subgoals across every Action/Setter/View/FK obligation, and ✓ QED / ✗ Refuted leaves.
  • Infoview (Lean 4 Tactic Goal Step-Through): Steps line-by-line (◀ Prev, ▶ Auto-Step, Next ▶) through the actual generated Lean 4 theorem showing live Hypotheses (+ diff highlights), ⊢ Turnstile goals, and plain-English explanations of intro, cases, simp, omega, and decide.
  • Induction (State-Space Safety Envelope): Interactive SVG diagram showing init_preserves_inv (base case), step_preserves_inv (inductive transition arcs staying inside the safe invariant boundary), and your live Preview state cursor.
Diagram Preview
Enlarged diagram