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
| Surface | File extension | Accepted declarations | Primary use |
|---|---|---|---|
| Contract syntax | .lema | def, law, contract, select | Writing human-auditable specifications, multi-law interfaces, and progressive contract selections (lema.contract/v1). |
| Restricted Lean | .lean | def, theorem, instance, abbrev, structure, inductive | Writing 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:
- Binding and symbolic import resolution: The store resolves every entry in
bindings(orlema.binding-map/v1) andreceiveto concretelema.core/v4object IDs and reconstructs their Lean declarations under theReceived.*namespace. - Module installation: Required upstream object closures are materialized into
.oleanmodules inside the runtime’s isolatedmodules/cache. - Sandboxed elaboration: The runtime spawns Lean
4.34.1inside an isolated Bubblewrap (bwrap) andsystemd-run --user(or"container") sandbox with zero network access, read-only toolchain mounts, and deterministic memory/CPU limits. - 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 alema.checked-export/v3intermediate bundle. - Canonical object construction (
lema.core/v4):crates/lema-coretranslates each exported declaration, structure, inductive family, statement, template, proof, or satisfaction into canonicallema.core/v4JSON objects and computes their 64-hex content-addressed IDs. - Source-free kernel replay:
crates/lema-lean-checkreplays thelema.core/v4objects from scratch in a fresh Lean4.34.1kernel process without reading the original.lemaor.leansource 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:
| Field | Type | Required | Description |
|---|---|---|---|
source | String | Yes | UTF-8 .lema or .lean source text. |
syntax | "lean" | "lema" | Optional | Source parser mode (inferred from file extension by lema add and lema publish). |
prefix | String | Yes | Dot-separated namespace prefix applied to exported declarations (for example "Lema.Cap.Collector"). |
roots | Array of strings | Yes | Declaration names within source to export and alias into the store. |
seed_salt | String | Optional | Disambiguating salt mixed into template and seed derivation when needed. |
seeds | Array of objects | Optional | Template holes (name, type, value?) used to synthesize template and satisfaction objects. |
bindings | Object ({alias: id}) | Optional | Direct mappings from Received.<alias> to accepted object IDs. |
receive | Array of objects | Optional | Symbolic imports referencing lema.bundle/v1 records via a lema.binding-map/v1. |
metadata | Object | Optional | Authoring 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.
| Construct | Status | Rule |
|---|---|---|
def, abbrev, theorem, instance | Allowed | Must be total and terminating. Structural recursion and single self-recursive well-founded recursion are supported. |
structure | Allowed | Exported as a lema.core/v4 record object. |
Single inductive (including indexed families) | Allowed | Exported as a lema.core/v4 family object (num_params, num_indices). |
Mutual or nested inductive | Forbidden | Rejected during export; refactor into a single indexed inductive family or nested sum type. |
partial or unsafe definitions | Forbidden | Rejected at both the syntax guard and kernel export boundary. |
sorry, admit, or axiom declarations | Forbidden | User-declared axioms and sorryAx are blocked by the fixed floor. |
Custom macro, elab, syntax, notation | Forbidden | Metaprogramming and custom parser extensions are rejected so files remain readable without executing arbitrary user code during parsing. |
import statements | Forbidden | Source files cannot read the host filesystem; all dependencies enter through Received.* bindings (bindings or receive). |
IO, System, @[extern], @[implemented_by] | Forbidden | Host 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).
"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.choiceorQuot.liftin a computational (non-Prop) position. Proofs of theorems andPropfields are erased and may freely useClassical.choiceif allowed by the store’s axiom policy. - Supported primitives: Runtime types must lower to
LemaIRprimitives (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, orSecretFlow.*), every reachable function in the call graph must pass those static analyses duringlema build.
Evaluation in proofs (decide +kernel vs decide)
When discharging finite decidable propositions by computation inside a proof:
- Allowed:
decideanddecide +kernelreduce terms inside the trusted Lean kernel using verified kernel reduction rules. - Forbidden:
native_decidecompiles Lean code to native machine code and trusts the result viaLean.ofReduceBool/Lean.trustCompiler. Every axiom generated bynative_decideis 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