On building · AI-assisted engineering
Mathematically Correct Programs
Let the AI write the code however it likes. A checker with no AI in it decides whether the code keeps the policy, and leaves a record anyone can rerun.
Ask an AI to write the same program twice and you get two different programs. Close the chat and it forgets why it wrote either one. That is fine for a weekend project. It isn’t fine for code that pays people, approves expenses or runs a regulated process.
The question I want to answer is whether you can put a deterministic checker around a nondeterministic process, and keep a result that survives the conversation. You can. Here is the whole loop, start to finish, for one small expense policy: the policy is written down, the AI writes the code and a proof, the record goes green, the policy changes, the record goes red, and the AI brings it back to green.

01Charlie’s policy, in his words and in Lean
Alice works in sales and submits a $48 train fare. Bob, her manager, approves it. Charlie runs finance and owns the expense policy. Deborah is the engineer who owns the code repository where the AI works.

Here is Charlie’s policy as he wrote it:
- An expense can be approved only by the submitter’s manager, and only up to that manager’s approval limit. No one approves their own expense.
- When the manager approves an expense within their limit, it goes through.
Rule 2 matters because a system that rejects everything keeps rule 1 perfectly. The AI translates both rules into Lean, a language for stating things precisely and checking proofs of them. This file holds no approval code, only the rules and the terms they use:
-- Policy.lean (version 1, confirmed by Charlie)
structure Employee where
id : Nat
manager : Option Nat -- the id of the person they report to
limit : Nat -- the largest expense they may approve, in dollars
structure Expense where
submitter : Employee
amount : Nat -- in dollars
inductive Decision where
| approve
| reject
structure Policy (approve : Employee → Expense → Decision) : Prop where
-- Rule 1: only the submitter's manager, who is someone else, within their limit.
only_manager_approves :
∀ a e, approve a e = .approve →
e.submitter.manager = some a.id ∧ a.id ≠ e.submitter.id ∧ e.amount ≤ a.limit
-- Rule 2: when those conditions hold, the approval goes through.
manager_can_approve :
∀ a e, e.submitter.manager = some a.id → a.id ≠ e.submitter.id →
e.amount ≤ a.limit → approve a e = .approve
Charlie doesn’t need to read Lean fluently. He reads each rule next to his own sentence, with Deborah walking him through it. Writing the rules down also turned up a clash his words left open. The CEO’s record lists her as her own manager. Rule 2 says that when she approves her own expense within her limit, it goes through. Rule 1 says no one approves their own expense. No program can do both, so the AI came back with that example instead of a proof. Charlie’s answer was that rule 1 wins, because the board handles her expenses outside this system. That answer is the a.id ≠ e.submitter.id in rule 2.
Charlie confirms the file, and from now on it changes only with his sign-off. The repository enforces that: Charlie is a required reviewer on any change to Policy.lean.

02The AI writes the code and the proof
Charlie’s file says what must be true. It doesn’t say how. The AI writes the approval function in a second file:
-- Approval.lean (written by the AI)
import Policy
def approve (approver : Employee) (e : Expense) : Decision :=
if approver.id = e.submitter.id then .reject -- your own expense
else if e.submitter.manager = some approver.id then
if e.amount ≤ approver.limit then .approve else .reject -- your report: check the limit
else .reject -- not your report
def alice : Employee := { id := 1, manager := some 2, limit := 0 }
def bob : Employee := { id := 2, manager := some 3, limit := 1000 }
def fare : Expense := { submitter := alice, amount := 48 }
/-- info: Decision.approve -/
#guard_msgs in #eval approve bob fare
/-- info: Decision.reject -/
#guard_msgs in #eval approve alice fare
Lean is also a programming language. approve compiles to ordinary native code, and the expense service calls it like any other function.
The last four lines are tests. Each runs the function on one expense and states the answer it must give, and the build fails if the answer changes. They show Bob can approve the fare and Alice can’t, for this one fare. The proof covers every employee and every expense. It is a value of type Policy approve, with one part for each of Charlie’s rules:
theorem certified : Policy approve where
only_manager_approves a e h := by
unfold approve at h
by_cases h1 : a.id = e.submitter.id
· rw [ite_eq_left h1] at h; contradiction
· rw [ite_eq_right h1] at h
by_cases h2 : e.submitter.manager = some a.id
· rw [ite_eq_left h2] at h
by_cases h3 : e.amount ≤ a.limit
· exact ⟨h2, h1, h3⟩
· rw [ite_eq_right h3] at h; contradiction
· rw [ite_eq_right h2] at h; contradiction
manager_can_approve a e hm hne hlim := by
unfold approve
rw [ite_eq_right hne, ite_eq_left hm, ite_eq_left hlim]
Nobody has to read the proof, and that is the point. Run the AI again and it might write a different function and a different proof. It might try fifty versions before one works. None of that matters, because every version has to pass the same check against Charlie’s file, and only one whose proof goes through can pass. Charlie’s two rules also settle every case, so every version that passes gives the same answer for every expense, and Lean can prove that too. The programs differ; their answers don’t.

03The checker, and the record that outlives the chat
The check is a short script with no AI in it. Same files in, same answer out, every time:
# Stop at the first check that fails.
set -e
# Are these the files Charlie and Deborah confirmed?
sha256sum -c confirmed.sha256
# Do the code, the proof and the tests compile against them?
lake build
# Do Approval's proofs replay through Lean's kernel?
lake env leanchecker Approval
# Is it Charlie's policy, using only Lean's standard axioms?
lake env lean Check.lean
The AI edits Approval.lean and nothing else. confirmed.sha256 covers the rest: Policy.lean, Check.lean, the build file and the file that pins the Lean version. Hashing Policy.lean alone isn’t enough, because one changed line in the build file can make Lean compile a different policy while Policy.lean’s hash still matches.
The build runs whatever Approval.lean asks, and Lean code can add a “proof” that the kernel never checked. leanchecker replays Approval’s proofs through the kernel again, so an invalid proof added that way turns the check red. Check.lean, which the checker owns, does the rest:
-- Check.lean (owned by the checker, not the AI)
import Approval
import Lean
open Lean Elab Command
run_cmd do
let env ← getEnv
-- The theorem states Charlie's `Policy` about `approve`, compared as Lean terms, not as text.
unless (← getConstInfo `certified).type == mkApp (mkConst `Policy) (mkConst `approve) do
throwError "certified does not state Charlie's policy"
-- Every declaration outside Lean itself and Charlie's file:
for i in [0:env.header.moduleNames.size] do
let m := env.header.moduleNames[i]!
unless m == `Policy || [`Init, `Std, `Lean, `Lake].contains m.getRoot do
for n in env.header.moduleData[i]!.constNames do
-- uses Lean's three standard axioms at most: no `sorry`, nothing the AI assumed,
for ax in ← liftCoreM (collectAxioms n) do
unless [``propext, ``Classical.choice, ``Quot.sound].contains ax do
throwError m!"{n} relies on {ax}"
-- and runs the code that was proved, not other code in its place.
if (Compiler.getImplementedBy? env n).isSome || isExtern env n then
throwError m!"{n} runs different code from the code that was proved"
Lean lets you write sorry in place of a proof you haven’t finished, and the build still passes. Check.lean catches that: a sorry in certified, or in anything else Approval.lean defines, shows up as an axiom named sorryAx, and the check fails. Lean also lets code name other code to run in its place, usually for speed. The proof would then be about one function while the service runs another, so the check refuses any swap that isn’t itself proved. And it compares the theorem’s statement as Lean terms, not as text, because Approval.lean can change what text means.
Each of those shortcuts was tried on purpose, along with a policy swapped in through the build file, and each turned the check red. That makes it a good check against mistakes and shortcuts, the kind an AI takes when it is stuck. It is not a defence against an AI that is trying to fool it. Building Lean code runs that code, so code written to cheat could rewrite the checker while it builds. Lean’s guide to validating proofs counts un-reviewed AI-written proofs and programs as possibly malicious. For that case it recommends lake comparator --paranoid, which builds the code in a sandbox and checks the exported proof outside it, against a statement the AI never touches, with Lean’s kernel and five other checkers.
When all four lines pass, CI writes a record into the repository. The AI never writes it:
{
"policy": { "file": "Policy.lean", "version": 1, "sha256": "0ebbe47a…",
"confirmed_by": "Charlie (Finance), required reviewer" },
"code": { "file": "Approval.lean", "commit": "9a2e41c" },
"theorem": "certified : Policy approve",
"axioms": "none",
"status": "green"
}
This file is what persists. The confirmed_by line only points at Charlie’s sign-off; the sign-off itself is his approving review, which the repository requires. Next week a new AI session, or a new engineer, opens the repository with no memory of how the proof was found. If the confirmed files still match their hashes and Approval.lean matches the recorded commit, they run the same script and get the same answer. If any file has changed, the old result belongs to the old files, and the status is pending until the check runs again.
04Charlie changes the policy
Six weeks later Charlie adds a rule: expenses over $500 also need sign-off from finance. The AI’s first draft added his sentence and changed nothing else. Then a $700 hotel bill within Bob’s $1,000 limit, with no finance sign-off, would have to be approved under rule 2 and rejected under rule 3. No program can do both. As with the CEO, the AI came back with that $700 example rather than a proof, and Charlie decided which rule gives way: rule 2 now covers only expenses that rule 3 allows. Charlie confirms the corrected file, and Deborah merges it:
@@ structure Expense @@
submitter : Employee
amount : Nat -- in dollars
+ financeSignoff : Bool := false
@@ structure Policy @@
manager_can_approve :
∀ a e, e.submitter.manager = some a.id → a.id ≠ e.submitter.id →
- e.amount ≤ a.limit → approve a e = .approve
+ e.amount ≤ a.limit → (e.amount ≤ 500 ∨ e.financeSignoff = true) →
+ approve a e = .approve
+ -- Rule 3: over $500 also needs sign-off from finance.
+ finance_over_500 :
+ ∀ a e, approve a e = .approve → e.amount > 500 → e.financeSignoff = true

Nothing in Approval.lean has changed, but the next build fails:
$ lake build
✖ [5/7] Building Approval
error: Approval.lean:19:35: Fields missing: `finance_over_500`
error: Approval.lean:31:41: unsolved goals
…
⊢ e.amount ≤ 500 ∨ e.financeSignoff = true → Decision.approve = Decision.approve
…
error: build failed
The proof has nothing for rule 3, and its proof of rule 2 no longer fits: the new rule 2 has one more condition. The record turns red. The old proof still proves what it always proved, which is version 1 of the policy. It says nothing about rule 3, and the checker won’t let the record claim otherwise.
05Back to green
The AI changes one condition in the approval function:
else if e.submitter.manager = some approver.id then
- if e.amount ≤ approver.limit then .approve else .reject -- your report: check the limit
+ if e.amount ≤ approver.limit ∧ (e.amount ≤ 500 ∨ e.financeSignoff = true)
+ then .approve else .reject
It adds tests for the new case:
def hotel : Expense := { submitter := alice, amount := 700 }
/-- info: Decision.reject -/
#guard_msgs in #eval approve bob hotel
/-- info: Decision.approve -/
#guard_msgs in #eval approve bob { hotel with financeSignoff := true }
And it writes a new proof, this time in a different style. That doesn’t matter either:
theorem certified : Policy approve where
only_manager_approves a e h := by
unfold approve at h
by_cases h1 : a.id = e.submitter.id <;> simp_all
by_cases h2 : e.submitter.manager = some a.id <;> simp_all
manager_can_approve a e hm hne hlim hfin := by
simp [approve, hne, hm, hlim, hfin]
finance_over_500 a e h hbig := by
unfold approve at h
by_cases h1 : a.id = e.submitter.id <;> simp_all
by_cases h2 : e.submitter.manager = some a.id <;> simp_all
The checker runs the same script. Every rule in version 2 is proved, using only Lean’s three standard axioms, so the record gets a new policy hash (a4eff4b8…), a new commit and a green status.

The record never says the code is correct in general. It says the code is correct against one version of Charlie’s policy: this policy and this code, checked together. When either one changes, the green stays with the old versions, and the new pair is pending until the check runs again.
06What the proof doesn’t cover
The proof says approve keeps Charlie’s rules for every employee and every expense in the model. It says nothing about whether the model matches the company. Suppose Bob has a second login, set up as a contractor who reports to him. He submits his own $300 dinner from it and approves it from his main login. Every rule holds: the submitter’s manager approved it, within his limit, and the two ids differ. The theorem still holds, and Bob has approved his own expense. Each remaining question needs its own owner:
| Question | Answered by |
|---|---|
| Does Policy.lean say what Charlie meant? | Charlie, reading it beside his own words |
| Does the code keep every rule in Policy.lean? | The checker |
| Do the web form, the bulk import and the retry path all call this code, as the signed-in person, and obey its answer? | Integration tests |
| Do ids, managers and limits come from the employee directory, one login per person? | A check against the employee directory |
| Can anyone but finance set the sign-off, and does editing the expense clear it? | Access control, and tests that an edit clears the sign-off |
| Can a $700 bill be split into two $350 bills? | Charlie: rule 3 looks at one expense at a time |
| How do cents and currencies become whole dollars, so $500.99 doesn’t count as $500? | Charlie, and tests on the conversion |
| Who can change Policy.lean, and who writes the record? | Branch protection: Charlie reviews the policy, CI writes the record |
| Is the service running the build that was checked? | Deployment records |
Only the second row is new. The others existed before, but now each has a precise edge to test against.
07Who decides what
The AI is allowed to be nondeterministic. It can write the code differently every time, fail fifty times, and forget the whole conversation. Charlie decides what the rules are, the checker decides whether the code keeps them, and the record holds both decisions where the next person can find them.
Here is the test I’d apply to any system an AI builds. Close the chat. Hand the repository to someone who wasn’t there. They should be able to see which policy Charlie confirmed, rerun the check and get the same answer, and read in one table what is still open.
All the Lean in this essay builds on Lean 4.36.