Read your first contract and proof
Learn to read Lema contracts in Pythonic .lema syntax, Lean syntax, and plain English on any machine, with zero installation or theorem-proving background required.
Before installing any tools or starting a local server, the fastest way to understand Lema is to read a few working examples of contracts, implementations, and proofs, and see how they work together when you build software with an AI coding agent.
You do not need a Linux machine or a repository checkout for this lesson, and you do not need any prior experience with functional programming or Lean. Every example on this page has interactive tabs so you can compare the Pythonic .lema syntax, the Lean syntax, and the plain-English Explanation side by side.
1. Why sample unit tests break down when AI agents write code
Suppose you are pairing with an AI coding agent such as Claude Code or Codex, and you ask it to write a function advance that assigns the next sequence number to each event in a log. Your core requirement is that the sequence number always moves forward.
In a traditional repository, the agent edits a source file and writes three or four unit tests:
assert advance(0) > 0
assert advance(1) > 1
assert advance(42) > 42Those three assertions test three inputs out of infinitely many. If the agent introduced an off-by-one branch or an overflow wrap at n == 1000000, your unit tests would pass and you would have to spot the bug by reading the agent’s implementation line by line.
In Lema, instead of trusting a handful of sample inputs or auditing a thousand-line diff, you own a short contract that states what must hold for every input, and your coding agent supplies the implementation and the mathematical proof.
Switch between the Pythonic, Lean, and Explanation tabs in this first example:
Pythonic
def advance(n: Nat) -> Nat:
n + 1
def Advances(f: Nat -> Nat) -> Prop:
forall n: Nat :: f(n) > n
select Advances(advance)Lean
These declarations express the same implementation and promise. Selection is a Lema codebase operation; the final comment names its target, without supplying a proof.
def advance (n : Nat) : Nat := n + 1
def Advances (f : Nat → Nat) : Prop :=
∀ n : Nat, f n > n
-- Selected proposition: Advances advanceExplanation
For every nonnegative integer n, the selected function must return a number greater than n. The implementation advance adds one.
Advances describes the promise independently of the implementation. Selecting Advances(advance) records an open obligation about that exact function. It becomes checked only when a matching proof is accepted.
The promise requires an increase, but does not require an increase of exactly one. A function that adds two would satisfy it too.
Walk through the three parts of the Pythonic .lema view above:
def advance(n: Nat) -> Nat:defines the implementation.Natis a non-negative whole number (0, 1, 2, ...), andadvancereturnsn + 1.def Advances(f: Nat -> Nat) -> Prop:defines a contract claim. It takes any candidate functionffromNattoNatand returns a logical proposition (Prop):forall n: Nat :: f(n) > n(“for every natural numbern, callingf(n)returns a number strictly greater thann”).select Advances(advance)binds that contract claim to the specific implementationadvancein your project’s content-addressed store.
2. Two syntax views over one content-addressed store
When you clicked between the Pythonic and Lean tabs above, you were not looking at two different programming languages that need to be kept in sync by hand. Both tabs are deterministic syntax views rendered from the exact same typed objects in Lema’s content-addressed store (.lema/store).
Under the hood, Lema’s renderer and parser (crates/lema-core/src/view.rs, hashed under domain LEMA-CONTRACT-VIEW-v1\0) translate directly between Pythonic .lema syntax and Lean syntax:
| Concept | Pythonic .lema syntax | Lean syntax | Plain-English meaning |
|---|---|---|---|
| Function or template | def f(x: Nat) -> Nat: | def f (x : Nat) : Nat := | Defines a function or value of a given type. |
| Theorem or law | law name(x: Nat): | theorem name (x : Nat) : | States a logical rule that holds for all inputs. |
| Preconditions & postconditions | requires P / ensures Q | P → Q | If precondition P holds, then postcondition Q follows. |
| Universal quantifier | forall x: Nat :: P(x) | ∀ x : Nat, P x | For every possible value x of type Nat, P(x) is true. |
| Multi-law contract | contract Name(ops: T): | structure Name (ops : T) : Prop where | Groups multiple named laws into one contract record. |
| Anonymous function | fn(x: Nat) -> x + 1 | fun (x : Nat) => x + 1 | A lambda expression (lambda x: x + 1 in Python). |
| Comparisons & booleans | ==, !=, <=, >=, and, or, not | =, ≠, ≤, ≥, ∧, ∨, ¬ | Standard logical and comparison operators. |
Because the store identifies every definition and theorem by the SHA-256 hash of its canonical kernel structure rather than by source file formatting, you can author and review contracts in Pythonic .lema syntax while your coding agent writes implementations and proofs in restricted Lean. Even better, Lema’s structural rederive check parses the Pythonic .lema view back into its canonical object IDs in pure Rust without invoking Lean, guaranteeing that the contract text you read on screen matches the exact mathematical claim in the store.
3. How select moves a contract from open to checked
Writing select Advances(advance) in a .lema file does not prove that advance obeys Advances. Instead, it creates an immutable contract selection record (lema.contract/v1) in the store and tracks its evidence status as you and your coding agent work:
-
Step 1 · State
Write the .lema contract
You define Advances in Pythonic .lema syntax. The Lean kernel checks that the proposition itself is well-typed with zero proofs required.
-
Step 2 · Select
select Advances(advance)
The store pins the target proposition to the exact SHA-256 identity of advance and records the selection status as open.
-
Step 3 · Prove
Agent supplies a theorem
Your coding agent (such as Claude Code) iterates with lema add until the Lean 4.34.1 kernel accepts a theorem proving the claim.
-
Step 4 · Discharge
Store::check_witness
The store verifies that the theorem matches both the target statement and the exact implementation binding, moving the selection to checked.
At any moment, lema status and lema diff report one of three statuses for each selected contract:
openmeans the contract selection is recorded in the project, and you can already compile, test, and runadvanceon the Lema VM, while proof evidence is still needed (or only a subset of laws in a multi-law contract have been proved so far, such as1/2 laws proved).checkedmeans an accepted theorem in the store passedStore::check_witnessfor the whole selection, verifying both the logical statement and the concrete implementation bindings (realizations).waivedmeans an authorized human actor explicitly closed an open obligation with a recorded reason (lema commit --waive). A waiver is a governance decision and is never counted as proof evidence.
4. Reading what a contract says (and what it leaves out)
Notice an important detail in Advances above: the contract requires f(n) > n, which says the counter increases, but it does not say the counter increases by exactly one. If your coding agent changed advance(n) to n + 2, the proof of Advances(advance) would still pass. If consecutive sequence numbers matter to your application, your contract should state f(n) == n + 1.
The same principle applies to real-world data structures and algorithms. Look at how Lema’s standard library specifies sortBy (Std.Canonical.sortBy, which sorts HTTP headers and canonical map keys):
Pythonic
Both views below are rendered from the same accepted statement objects in the store. A sorting contract needs both laws: returning an empty list would be in order, so the second law requires every original element and its count to survive.
law sortBy_sorted(le: alpha -> alpha -> Bool, l: List(alpha)):
requires forall a: alpha, b: alpha, c: alpha :: (le(a, b) == true and le(b, c) == true) -> le(a, c) == true
requires forall a: alpha, b: alpha :: le(a, b) == true or le(b, a) == true
ensures Pairwise(fn(a: alpha, b: alpha) -> le(a, b) == true, sortBy(le, l))
law sortBy_perm(le: alpha -> alpha -> Bool, l: List(alpha)):
Perm(sortBy(le, l), l)Lean
theorem sortBy_sorted {α : Type} (le : α → α → Bool)
(trans : ∀ a b c, le a b = true → le b c = true → le a c = true)
(total : ∀ a b, le a b = true ∨ le b a = true) :
∀ l : List α, (sortBy le l).Pairwise (fun a b => le a b = true)
theorem sortBy_perm {α : Type} (le : α → α → Bool) :
∀ l : List α, (sortBy le l).Perm lExplanation
The first law (sortBy_sorted) promises that for any comparison function le that is transitive and total, every item in sortBy(le, l) is ordered before or equal to the items that follow it.
The second law (sortBy_perm) closes the loophole where a buggy implementation simply drops elements or returns an empty list: it promises that the output list is an exact permutation of the input list, preserving every element and its multiplicity.
Because both laws live in the content-addressed store as accepted statement objects, callers such as canonical HTTP header sorting depend only on these statement hashes, never on the internal sorting implementation or proof steps.
Why does sortBy need two laws (sortBy_sorted and sortBy_perm) instead of just one?
- If your contract only required
sortBy_sorted(“every element in the returned list is ordered before or equal to the elements after it”), a mischievous or buggy agent could writedef sortBy(le, l): return []. An empty list is vacuously sorted, so the first proof would succeed while deleting all of your user’s data. - Adding
sortBy_perm(Perm(sortBy(le, l), l)) closes that loophole completely: it requires the output list to be an exact permutation of the input listl, preserving every element and its exact duplicate count.
5. Inside a proof: how definitions, statements, and proofs split apart
Now look at a complete module that includes both an implementation and its proof. Click between the Lean, Pythonic, and Explanation tabs below:
Pythonic
This readable view shows the definition and the law’s statement. The Lean tab contains the complete module, including the proof.
def keep(n: Nat) -> Nat:
n
law keep_law(n: Nat):
keep(n) == nLean
namespace Lema
def keep (n : Nat) : Nat := n
theorem keep_law (n : Nat) : keep n = n := rfl
end LemaExplanation
keep returns its input unchanged. The law says this holds for every nonnegative integer.
The Lean module includes the proof rfl. Lean reduces keep n to n and checks that both sides are equal by definition. The Pythonic tab displays the same definition and statement, without the proof term.
In the Lean tab:
def keep (n : Nat) : Nat := nis the implementation: it takesnand returnsn.theorem keep_law (n : Nat) : keep n = n := rflis the theorem. Before the:=is the statement (keep n = nfor everyn : Nat), and after the:=is the proof term (rfl, which asks the Lean kernel to simplify both sides by definition and confirm they are identical).
When you switch to the Pythonic tab, notice that keep_law is rendered as law keep_law(n: Nat): keep(n) == n with the proof term omitted. Why? Because when Lema accepts keep_law into .lema/store, it splits the declaration into separate content-addressed objects:
Accepted declaration · keep_law
- Role in codebase
- Theorem proving keep(n) == n for all n : Nat
- Statement object
- Hashed from the logical claim alone (forall n: Nat :: keep(n) == n)
- Proof object
- Hashed from the deduction term (rfl) separately from the statement
- Axioms used
- [] (none)
Because the statement and the proof have separate SHA-256 hashes, human reviewers and downstream callers only ever depend on the statement hash. You never have to read a long tactic script to know what a theorem proves, because the pinned Lean 4.34.1 kernel has already checked the proof object and recorded a receipt.
6. Reusing a theorem across implementations
Splitting statements from proofs also opens up a major advantage for larger systems: you can prove a general rule once about any function that obeys a contract, and then reuse that theorem across different implementations.
Inspect the Lean, Pythonic, and Explanation tabs of this example:
Pythonic
This readable view shows the statements. The Lean tab contains the complete module with proof terms and its publication namespaces.
law twice_id(f: Nat -> Nat):
requires forall x: Nat :: f(x) == x
ensures forall x: Nat :: f(f(x)) == x
def keep(x: Nat) -> Nat:
x
law keep_law(x: Nat):
keep(x) == x
law keep_twice(x: Nat):
keep(keep(x)) == xLean
namespace Lema
namespace Reuse
theorem twice_id :
∀ (f : Nat → Nat), (∀ x, f x = x) → ∀ x, f (f x) = x :=
fun f law x => (congrArg f (law x)).trans (law x)
def keep (x : Nat) : Nat := x
theorem keep_law (x : Nat) : keep x = x := rfl
theorem keep_twice (x : Nat) : keep (keep x) = x :=
twice_id keep keep_law x
end Reuse
end LemaExplanation
If a function leaves every input unchanged, applying it twice also leaves every input unchanged. twice_id proves this once for any function with that property.
keep supplies a concrete implementation, and keep_law proves the required premise. keep_twice reuses twice_id with that implementation and evidence.
The Lean tab includes the proofs. The Pythonic view states the same promises without their proof terms.
Look at twice_id in the Pythonic tab:
law twice_id(f: Nat -> Nat):
requires forall x: Nat :: f(x) == x
ensures forall x: Nat :: f(f(x)) == xAnd compare it with the Lean tab:
twice_idtakes any functionf: Nat -> Natand a proof (requires forall x: Nat :: f(x) == x) thatfreturns its input unchanged. It proves once and for all that applyingftwice in a row (f(f(x))) also returnsx.keep_twiceproveskeep(keep(x)) == xin a single line (twice_id keep keep_law x) without unfoldingkeep’s implementation body.- If your coding agent later writes a second implementation (such as
addZero(x) = 0 + x) and provesaddZero_law, you can apply the exact sametwice_idtheorem toaddZerowithout changing a single character oftwice_id’s proof.
Next
You now know how to read Lema contracts in both Pythonic .lema and Lean syntax, how select tracks contract obligations from open to checked, and why content-addressed statements make working with AI coding agents safe and predictable.
- Continue to Lesson 2: Set up a machine for Lema to install the toolchain and create your first project.
- Or, if you want to explore the design concepts further without installing anything yet, read Types and contracts.
Lema v0.3.2 · Updated 29 October 2026 · Version and compatibility