Skip to content

Authoring Rules

Rules and pipeline for authoring restricted Lean (.lean) and Pythonic contract (.lema) modules in Lema v0.2.

Lema accepts source code in two deterministic surfaces: Pythonic .lema contract files and restricted .lean implementation files. Both surfaces are parsed, elaborated in a hermetic sandbox, exported as canonical lema.core/v4 objects, and replayed from scratch by the pinned Lean 4.34.1 kernel before any object enters the store.


Dual authoring surfaces

SurfaceFile extensionAccepted declarationsPrimary use
Contract syntax.lemadef, law, contract, selectWriting human-auditable specifications, multi-law interfaces, and progressive contract selections (lema.contract/v1).
Restricted Lean.leandef, theorem, instance, abbrev, structure, inductiveWriting implementations, inductive types, tactics, and machine-checked proof terms.

When you pass a .lema file to lema add, lema publish, or the publish API, crates/lema-core/src/view.rs (parse_module and lean_declaration) lowers each def, law, and contract declaration into restricted Lean source before elaboration, and registers each select declaration as a lema.contract/v1 record in the store. See Contract Syntax for the full .lema grammar.


Six-stage publication pipeline

Every call to elaborate or publish runs the following six stages in order:

  1. Binding and symbolic import resolution: The store resolves every entry in bindings (or lema.binding-map/v1) and receive to concrete lema.core/v4 object IDs and reconstructs their Lean declarations under the Received.* namespace.
  2. Module installation: Required upstream object closures are materialized into .olean modules inside the runtime’s isolated modules/ cache.
  3. Sandboxed elaboration: The runtime spawns Lean 4.34.1 inside an isolated Bubblewrap (bwrap) and systemd-run --user (or "container") sandbox with zero network access, read-only toolchain mounts, and deterministic memory/CPU limits.
  4. Checked export (lema.checked-export/v3): The in-sandbox exporter inspects the elaborated Lean environment, rejects banned constructs (unsafe, partial, metaprogramming, multiple mutually recursive inductives, or disallowed axioms), and emits a lema.checked-export/v3 intermediate bundle.
  5. Canonical object construction (lema.core/v4): crates/lema-core translates each exported declaration, structure, inductive family, statement, template, proof, or satisfaction into canonical lema.core/v4 JSON objects and computes their 64-hex content-addressed IDs.
  6. Source-free kernel replay: crates/lema-lean-check replays the lema.core/v4 objects from scratch in a fresh Lean 4.34.1 kernel process without reading the original .lema or .lean source text, verifies that every object’s transitive axiom footprint obeys the store’s axiom policy, and writes the verification receipt.

Elaboration and publication request fields

When calling the elaborate or publish JSON API directly (or constructing a lema.authoring/v2 record), the request accepts these fields:

FieldTypeRequiredDescription
sourceStringYesUTF-8 .lema or .lean source text.
syntax"lean" | "lema"OptionalSource parser mode (inferred from file extension by lema add and lema publish).
prefixStringYesDot-separated namespace prefix applied to exported declarations (for example "Lema.Cap.Collector").
rootsArray of stringsYesDeclaration names within source to export and alias into the store.
seed_saltStringOptionalDisambiguating salt mixed into template and seed derivation when needed.
seedsArray of objectsOptionalTemplate holes (name, type, value?) used to synthesize template and satisfaction objects.
bindingsObject ({alias: id})OptionalDirect mappings from Received.<alias> to accepted object IDs.
receiveArray of objectsOptionalSymbolic imports referencing lema.bundle/v1 records via a lema.binding-map/v1.
metadataObjectOptionalAuthoring provenance stored in lema.authoring/v2.

Allowed and forbidden Lean constructs

Restricted Lean is designed so that every accepted declaration has a transparent, source-free kernel representation in lema.core/v4.

ConstructStatusRule
def, abbrev, theorem, instanceAllowedMust be total and terminating. Structural recursion and single self-recursive well-founded recursion are supported.
structureAllowedExported as a lema.core/v4 record object.
Single inductive (including indexed families)AllowedExported as a lema.core/v4 family object (num_params, num_indices).
Mutual or nested inductiveForbiddenRejected during export; refactor into a single indexed inductive family or nested sum type.
partial or unsafe definitionsForbiddenRejected at both the syntax guard and kernel export boundary.
sorry, admit, or axiom declarationsForbiddenUser-declared axioms and sorryAx are blocked by the fixed floor.
Custom macro, elab, syntax, notationForbiddenMetaprogramming and custom parser extensions are rejected so files remain readable without executing arbitrary user code during parsing.
import statementsForbiddenSource files cannot read the host filesystem; all dependencies enter through Received.* bindings (bindings or receive).
IO, System, @[extern], @[implemented_by]ForbiddenHost I/O and FFI hooks are forbidden; effectful programs are written as pure values of type Prog E R A.

Single self-recursive definitions and whole-unit reconstruction

When a single function uses well-founded recursion (termination_by / decreasing_by), Lean’s elaborator generates internal auxiliary definitions (_unary, _mutual, equational lemmas). Per architecture decision 0045, Lema reconstructs the entire declaration cluster as a single whole unit during export so that internal compiler auxiliaries never leak into the public store namespace.


Seeds

Seeds allow an authoring request to parameterize a module over abstract operations or implementation choices and simultaneously export a template object (the parameterized specification) and a satisfaction object (the proof that the concrete seed values satisfy the template).

JSON
"seeds": [
  {
    "name": "impl",
    "type": "CounterImpl",
    "value": "myCounterImpl"
  }
]

In .lema files, you rarely need to write raw seeds JSON manually: declaring a contract and a select statement automatically synthesizes the underlying statement, template, realizations, and lema.contract/v1 selection record.


Externals

Declarations in a Lema module can reference constants from Lean’s standard Init library (such as Nat, Bool, List, ByteArray, UInt8, UInt16, UInt32, UInt64, Int64, String, Eq, And, Or) as external objects.

An external object does not re-serialize the implementation of Init into the store; instead, it records the constant’s fully qualified name, universe parameters, and type signature (lema.core/v4 "kind": "external"), which crates/lema-lean-check verifies against the pinned Lean 4.34.1 kernel environment during replay.


Code that will run

Not every Lean definition is meant to execute at runtime: propositions (Prop), proofs, and unbounded quantifier statements exist only at verification time and are erased before execution.

Declarations that are reachable from an execution manifest (entry.root and roots in lema.exec-source/v2) are compiled from their lema.core/v4 objects into lema.ir/v1 (crates/lema-ir) for execution on the register VM (crates/lema-vm). Executable declarations must follow these rules:

  • Computable definitions only: No reachable function may depend on Classical.choice or Quot.lift in a computational (non-Prop) position. Proofs of theorems and Prop fields are erased and may freely use Classical.choice if allowed by the store’s axiom policy.
  • Supported primitives: Runtime types must lower to LemaIR primitives (Bool, UInt8, UInt16, UInt32, UInt64, Int64, Nat, Int, ByteArray, String, algebraic data types, records, and closures).
  • Static guarantee compliance: If the manifest lists VM guarantee profiles (such as NoBigIntPrimitives, NoBoxOrCtorInCycles, ConstantTime, or SecretFlow.*), every reachable function in the call graph must pass those static analyses during lema build.

Evaluation in proofs (decide +kernel vs decide)

When discharging finite decidable propositions by computation inside a proof:

  • Allowed: decide and decide +kernel reduce terms inside the trusted Lean kernel using verified kernel reduction rules.
  • Forbidden: native_decide compiles Lean code to native machine code and trusts the result via Lean.ofReduceBool / Lean.trustCompiler. Every axiom generated by native_decide is unconditionally blocked by the fixed floor.

Fileless library conventions (audit/inputs/ and audit/view/)

In the Lema repository itself, the standard and capability libraries are authored as store-first inputs under audit/inputs/ and published directly into the store during bootstrap. To keep the library easy to browse in editors and code review tools without making loose files the source of truth, lema audit render exports a read-only projection of the accepted store objects into audit/view/{core,data,std,cap}/.

Lema v0.3.2 · Updated 29 October 2026 · Version and compatibility