# Lean 4 Engineering Standard This document sets out a Lean 4 engineering standard for software engineers and coding agents writing verified functional programs and proofs. It covers both practices that [Regula](README.md) checks automatically and practices that stay manual engineering discipline. In Lean 4, proofs live in `Prop` and type formers are computationally irrelevant; both are erased at compile time, so compiled binaries execute computationally relevant definitions directly. Pairing a coding agent that generates code and proofs at build time with Lean's kernel and a proved checker verifies properties over all inputs (`∀ x`) once before the program runs, running the compiled definitions directly with no runtime proof search. That workflow depends on two halves: writing definitions, types, and specifications so illegal states and proof complexity are minimized from the start, and closing the build-time and runtime gaps where a green `lake build` can still diverge from what a proof states. Regula enforces a proved subset of this standard today—eleven checks on Lean `v4.36.0`—and leaves design, specification, and intent review to engineers and agents. See [Enforcement status](#enforcement-status) for the exact boundary, [`README.md`](README.md) for usage and verdicts, and [`specification/README.md`](specification/README.md) for exact theorem statements and the trusted base. Each of Regula's verdicts is about a project's claim. The *claimed modules* are the modules of the root package's default targets plus each root-package module their imports reach, which is what `lake build` builds; a *claimed* constant, definition, or theorem is one of a claimed module. A dependency's or the toolchain's module is not claimed, and neither is a target that no default target reaches: a module with a `sorry` there was measured to pass until a default module imported it ([`README.md#the-checks`](README.md#the-checks), [`specification/README.md#decisions-of-this-specification`](specification/README.md#decisions-of-this-specification)). ## 1. Intrinsic typing at boundaries Prefer types that make illegal states unrepresentable over post-hoc checks or sentinel conventions. Enforce invariants once where state is admitted or written, rather than repeating defensive guards where state is read. When choosing how to enforce an invariant, prefer in order: 1. A type that makes an illegal state unrepresentable. 2. A relation true by construction. 3. An exhaustive check over a closed finite domain. 4. A machine-checked proof over the actual definition. 5. A runtime guard derived from the invariant. Concrete Lean 4 practices: - **Bound indices and preconditions in types:** Use `Fin n` or proof-bearing indexing (`xs[i]` with a bounds proof) instead of panicking operations (`xs[i]!`, `Option.get!`, `List.head!`). - **Admit untrusted inputs into proof-bearing types:** Validate external data once at the boundary into a `Subtype` (`{ x : α // P x }`), a `Sigma` type, or a proof-bearing admission structure. Downstream functions then take valid inputs by type and carry no dead error branches or external validity hypotheses. - **Model finite states with closed sum types:** Replace loosely coupled Boolean flags, parallel optional fields, or stringly-typed codes with `inductive` types so impossible combinations cannot be constructed and `match` exhaustiveness catches missing cases at compile time. ### Examples in Regula - **Proof-bearing admission ([`lean/Regula/Input.lean`](lean/Regula/Input.lean)):** `Regula.Closed.Draft` holds raw loaded environment data together with `Draft.unique` (distinct constant names, constructed by the loader from hash map keys). `Draft.admit : Draft → Except String Input` checks the remaining two invariants once and returns `Regula.Closed.Input`, which carries `Input.closed` (every mentioned constant is held) and `Input.claims` (`modules ≠ []`). [`specification/RegulaSpecification/Proofs/Verdict.lean`](specification/RegulaSpecification/Proofs/Verdict.lean) proves `admit_ok_iff` in both directions. Every rule takes `Tables i` for an admitted `i : Input` and has no case for an empty claim or an open mention. - **Dependent lookup tables ([`lean/Regula/Tables.lean`](lean/Regula/Tables.lean)):** `Regula.Closed.Tables (i : Input)` bundles lookup structures (`index`, `claimed`, `axiomReach`) with proof fields (`mem_index`, `mem_claimed`, `mem_axiomReach`) indexed by the exact input `i`. A table built for one input cannot be passed for another, and rule exactness proofs carry no separate table-consistency hypothesis. - **Closed sum types ([`lean/Regula/Input.lean`](lean/Regula/Input.lean), [`lean/Regula/Rule.lean`](lean/Regula/Rule.lean), [`lean/Regula/Verdict.lean`](lean/Regula/Verdict.lean)):** - `Regula.Closed.Safety` has constructors `safe`, `unsafe`, and `partial`; it cannot represent a constant that is both unsafe and partial. - `Regula.Closed.Report` has constructors `pass`, `fail (first : Finding) (rest : List Finding)`, and `incomplete (why : String)`; it cannot represent a pass with findings or a failure with none, and an incomplete report always carries a `String`, which the type does not require to be nonempty. - `Regula.Closed.Profile` and `Regula.Closed.Verdict` are closed enums with proved injective encodings (`Profile.spelling_injective`, `Profile.ofSpelling?_eq_some`, `Verdict.exitCode_injective`, `Verdict.exitCode_eq_zero_iff`). - **Proof-bearing invariant ([`lean/Regula/Rule.lean`](lean/Regula/Rule.lean)):** `Regula.Closed.Guidance` pairs `text : String` with `nonblank : text.toList.head?.any (!·.isWhitespace) = true`, so `Violation` and `Finding` cannot represent empty, whitespace-only, or leading-whitespace fix guidance. **Enforcement status:** Engineering discipline (human and agent review). Regula has no lint rule that judges data-model design. ## 2. Spec-first design, proof economy, and proved refinement Avoid "program, optimize, then try to prove." Write specifications independently before writing code, keep implementations simple, and optimize only through proved equivalence. - **Write specifications independently of the code:** State what a function must satisfy in terms other than its body—quantifiers, inductive relations, algebraic equations, or domain predicates—before implementing it. A specification transcribed from an implementation shares the implementation's mistakes. - **Prove non-vacuity before proving the implementation:** Exhibit a well-formed input with a subject that violates the property and a well-formed input with a subject that does not, and prove that degenerate implementations (such as reporting nothing, or reporting every candidate) fail the specification. - **Prove the definition that executes:** Prove behavioral theorems over the exact functions called at runtime, not over a simplified copy written apart from the program. - **Treat hard proofs as a design warning:** When a proof becomes much harder than the code it covers, simplify the code or narrow its input domain before adding proof machinery. - **Optimize via proved refinement, never unproved replacement:** Implement a clear specification or reference definition and prove an optimized version equal to it (`f = g`), or register a proved equality theorem with `@[csimp]` where appropriate under the proof verdict. Do not use `@[implemented_by]` or `@[extern]` on claimed constants, or `@[init]`/`@[builtin_init]` naming an initialization function on claimed definitions. For `@[implemented_by]` and a named initialization function Lean checks only type agreement; for `@[extern]` it checks neither the foreign code nor the foreign signature (`Lean/Compiler/ExternAttr.lean:44-73` at `v4.36.0`). In no case does Lean check behavioral equivalence. - *Exact `@[csimp]` scope:* RG1011 refuses any exported (`global` or `scoped`) `@[csimp]` entry registered in a claimed module whose theorem is not declared in any claimed module's `.olean` (`moduleData`), and the loader reports RG2001 (`incomplete`) if a claimed module's index is missing ([2026-11-20](specification/confirmation.md#2026-11-20-claimed-module-csimp-entries)). In Lean `v4.36.0`, registering `@[csimp]` requires the named declaration's type to have the equality form `@f = @g` (`isConstantReplacement?`, `Lean/Compiler/CSimpAttr.lean:40-49`, `add`, `:51-55`); none of the attribute's checks (`:40-55`, `:71-80`) requires a safe proved theorem, and Lean's documentation notes that an unsound one can be registered with `unsafe` or an axiom such as `sorryAx` (`:68-69`). Exported `@[csimp]` on a theorem declared in a claimed module—including a one-line claimed alias that restates the equality (`@[csimp] public theorem alias : @f = @g := Dep.thm`) or a merged theorem declared in a claimed module's own `moduleData`—is admitted by RG1011: under the proof verdict, kernel cone replay checks every safe theorem declared in a claimed module within the profile, RG1001–RG1005 check its axioms, and RG1006 refuses `unsafe` and `partial` claimed constants without an exempted form; a claimed theorem that Lean's import merges under an unclaimed module's index is no subject of those rules, and the loader checks the claimed module's copy instead, refusing the build as `incomplete` (RG2001) when it is no safe theorem within the profile. `attribute [local csimp]` is `.olean`-invisible (never persisted to `.olean`, `Lean/ScopedEnvExtension.lean:17-19,137-153,265-267`), and dependency-registered `@[csimp]` entries sit in unclaimed modules' `.olean` files and are not checked by RG1011; both stay outside the proof verdict ([`specification/README.md#rg1011-replaced-compiled-code`](specification/README.md#rg1011-replaced-compiled-code)). Under the full gate, RG1010 refuses `csimp` in each file it reads, because `csimp` is not in `Regula.Language.simpleAttributes` ([`lean/Regula/LanguageSet.lean`](lean/Regula/LanguageSet.lean)); a project with a `require` gets only the proof verdict, and the toolchain's own `@[csimp]` registrations stay trusted. ### Examples in Regula - **Non-vacuity harness ([`specification/RegulaSpecification/RuleRecord.lean`](specification/RegulaSpecification/RuleRecord.lean)):** `ruleRecord` states that a rule reports a subject iff its violation predicate holds. `Witnessed` supplies a well-formed input on which one subject violates the rule (`refused`, `bad`) and a well-formed input with one subject that does not (`admitted`, `fine`); other subjects of that input may still violate it. From these, `silent_fails` refutes the checker that reports nothing, and `adequate` discharges the record's obligations O2 to O5, with O5 at `SameReports` (the order and repetition of reported subjects stay free). `noisy_fails` refutes the checker that reports every candidate (`candidates`, the `support` list of each input) only under the further premise that `fine` is in `support admitted`. - **Independent rule spec and bidirectional proof ([`lean/Regula/Rules/RG1011.lean`](lean/Regula/Rules/RG1011.lean), [`specification/RegulaSpecification/Rules/RG1011.lean`](specification/RegulaSpecification/Rules/RG1011.lean)):** `Violates1011` (with `Replaced`, `Initialized`, and `ForeignCSimp`) states RG1011 independently of `Regula.Rules.RG1011.check`; `Witnesses.w1011` and `rg1011_adequate` discharge the record's obligations, and `rg1011_noisy` applies `noisy_fails` with its candidate premise supplied by `t_mem_support`; `Link.rg1011_exact` proves bidirectional equivalence over the executed `check` function, and `Link.rg1011_attributed` proves it of each reported constant together with the module printed with it, so each claimed module that registers a foreign `@[csimp]` theorem is reported and no other module is; `Link.check_eq_replaced` proves that an input with `i.csimps = []` (for loader output, no exported claimed-module `@[csimp]` entry) gets exactly what the check reported before that clause (`Regula.Rules.RG1011.replaced`), of which `replaced_exact`, `replaced_subject` and `rg1011_admits_neither` hold as before; and `rg1011_checker_reads_definitions`, `rg1011_checker_refuses_foreign_csimp`, and `rg1011_checker_admits_claimed_csimp` prove boundary behavior. - **Modular rule registry ([`lean/Regula/Rules.lean`](lean/Regula/Rules.lean), [`specification/RegulaSpecification/Rules.lean`](specification/RegulaSpecification/Rules.lean)):** Each rule lives in an isolated module pair (check below [`lean/Regula/Rules/`](lean/Regula/Rules/), specification and proofs below [`specification/RegulaSpecification/Rules/`](specification/RegulaSpecification/Rules/)); of the two packages, each rule imports only its shared core (`Regula.Rule` / `RegulaSpecification.Rule`) and its own check, and no rule imports another rule. `Regula.Closed.registry` with `spellings_nodup` and `report_pass_iff` proves once that a run passes iff no registered rule reports a subject; `registry_rules` proves the specification registry equal to the checker's, linking directly to `AllHold` (`findings_nil_iff`, `report_complete`). **Enforcement status:** Unexempted `@[implemented_by]` and `@[extern]` on claimed constants, `@[init]`/`@[builtin_init]` naming an initialization function on claimed definitions, and exported (`global` or `scoped`) `@[csimp]` entries registered in a claimed module targeting a theorem not declared in any claimed module are refused by **RG1011**, with hidden module-local entries and missing claimed module indices refused by the loader as **RG2001**. Spec-first development, non-vacuity proofs, proof economy, and reading theorem statements remain engineering discipline. ## 3. Certifying algorithms, total search, pure effects, and module boundaries Structure algorithms, proof automation, side effects, and module interfaces so the trusted and proof-heavy surfaces stay small. - **Use certifying algorithms when checking is simpler than finding:** When proving a complex search, solver, or optimizer directly is harder than verifying its output, split it into a witness producer and a small, total, formally proved checker (`check x w = true → Spec x w`). That proof makes every accepted witness sound, so for soundness only the checker needs a correctness proof. It does not show that the producer supplies a witness whenever one exists, so a guarantee that the property is decided needs a completeness proof as well. - **Use total exhaustive search where a complete decision is needed:** Checking one clean declaration does not establish that all reachable declarations avoid disallowed axioms; a certificate for such a universal property has to cover every reachable case, such as a set that holds the roots, is closed under every successor, and holds no disallowed axiom. Regula instead computes, for each axiom of the input, the set of constants that reach it by exhaustive search, and proves that set exact (`mem_axiomReach`). Implement such a search as a total function over a closed finite domain using structural recursion or a derived termination measure—never `partial`, `while`, or an arbitrary fuel guess—and prove both soundness and completeness. - **Use kernel-checked automation instead of native evaluation:** Rely on tactics that produce kernel-checked proof terms (`simp`, `omega`, `decide +kernel`, structural induction). Avoid `native_decide`, `decide +native`, and `bv_decide`, whose proofs can depend on an axiom that trusts the compiler rather than Lean's kernel. - **Separate pure effect programs from thin IO interpreters:** Represent effectful workflows as pure trees over a closed set of operations with explicit error responses (`Except`), rather than mixing decision logic directly into `IO`. Prove behavioral properties of the pure program across all possible responses—including failures and external mutations—keep the runtime interpreter a straight-line dispatch table with no branching, and record every reliance on Lean, Lake, or the OS in one exhaustive list. - **Keep module boundaries explicit with `module` files:** Start every Lean file with `module` so callers depend only on `public` declarations and explicitly exposed bodies (`@[expose]`, `abbrev`, or instances). Keep implementation bodies unexposed in library modules; when a separate proof package must unfold unexposed bodies, use `import all` in the proof package rather than widening the library's public surface. ### Examples in Regula - **Total reachability with a derived termination measure ([`lean/Regula/Reach.lean`](lean/Regula/Reach.lean), [`lean/Regula/Tables.lean`](lean/Regula/Tables.lean)):** `reachGo` recurses structurally on a fuel argument, with no `partial` or `while`, and `reach` runs it with the fuel `seeds.length + weight`. `mem_reach` proves `reach` sound and complete against the inductive `Reach` relation from the seeds under two hypotheses: a supplied list holds every name with a successor, and `weight` is at least the sum of those names' out-degrees. With less fuel the search can stop before it visits every reachable name. The measure behind that bound is `work.length + unseenWeight`: `unseenWeight_insert` proves that inserting an unseen name `n` that the list covers drops `unseenWeight` by at least `(next n).length`, so the sum falls by at least one on each step (`reachGo_closed`). In `Tables.lean`, `Input.cone` passes the summed `uses` lengths of the input's constants for the forward kernel-replay cone, where `mem_cone` in [`specification/RegulaSpecification/Proofs/Load.lean`](specification/RegulaSpecification/Proofs/Load.lean) discharges both hypotheses, while `Input.axiomReach` builds a compact integer-indexed reverse adjacency array (`declIdMap`, `forwardEdges`, `reverseEdges`) and runs total fuel-bounded `reachNat` (termination measure `work.size + countFalse seen`, proved sound and complete by `mem_reachNat` and `mem_axiomReach`, with parallel per-axiom `Task.spawn` proved equal to sequential `axiomReachSeq` by `axiomReach_eq_seq`, on which `Tables.mem_axiomSet` builds). - **Pure effect tree and straight-line interpreter ([`lean/Regula/Effect.lean`](lean/Regula/Effect.lean), [`lean/Regula/Table.lean`](lean/Regula/Table.lean), [`specification/RegulaSpecification/Proofs/Program.lean`](specification/RegulaSpecification/Proofs/Program.lean)):** `Regula.Effect.Op` lists the closed set of external operations, `Resp` types each response (representing failures as `Except` values), `Prog` builds pure decision trees, and `Prog.interpret` executes them in `BaseIO` through `Regula.Effect.table` and `LakeCalls`. `table_rows` (with `spawnLake_eq`, `importParsers_eq`, `replayParallel_eq`, and `replayPlanShard_eq`) proves each table entry matches its straight-line call sequence with no verdict-deciding branch beyond propagating failures of the proved pure planner and verifier (`Regula.ReplayPartition`), `executed_meets` links `Prog.interpret` to the trace specification, and [`specification/RegulaSpecification/Assumptions.lean`](specification/RegulaSpecification/Assumptions.lean) maps every `Op` constructor exhaustively to named assumptions (`Assumption.ofOp`, `readAt_pinned`). - **Explicit `module` boundaries ([`specification/README.md#module-files`](specification/README.md#module-files)):** Every Lean file in `lean/Regula/` and every claimed library file in `specification/` (`RegulaSpecification.lean` and every module below `RegulaSpecification/`) starts with `module`; only the standalone gate script `specification/RequiredGate.lean` (outside `defaultTargets`, executed via `lake env lean -DwarningAsError=true --run RequiredGate.lean`) omits `module`, and its `main` loads `RegulaSpecification` at `Lean.OLeanLevel.private` with `loadExts := true` (`header.isModule = false`) because `LeanIntent.Required.Read.check` refuses `module` environments so every imported module is read in full. Root modules keep rule `check` bodies unexposed and apply `@[expose]` only where callers or registry proofs need definitional unfolding (such as `Regula.Effect.Resp`, each rule's `rule`, `Report.verdict`, and `Report.findings`), while the specification package unfolds checker bodies through `import all`. **Enforcement status:** Dependence on a native-proof axiom is refused by **RG1004**, which reads the axiom and not the tactic (under the full gate, **RG1010** refuses `native_decide` and `decide +native` by their syntax, and any tactic outside its closed table); `unsafe` declarations (outside the verified compiler-generated `T.ctorIdx._impl` form), `partial` declarations (outside the exempted recursion-helper form, with no direct loop mention and no direct `Lean.Order.fix` mention in the value of a definition or opaque constant), forged `._unsafe_rec` names, direct `while`/`repeat` loop mentions, and direct `Lean.Order.fix` (`partial_fixpoint`) mentions in the values of claimed definitions and opaque constants are refused by **RG1006**. The full gate requires a `module` header before compilation (**RG1010**), and both verdicts check the compiled module flag for each claimed module (**RG1013**). Certifying-algorithm factoring, termination-measure design, and pure-effect architecture remain engineering discipline. ## 4. Closing the compile-time erasure, `Prop`-vs.-`Type`, and runtime gap A green `lake build` does not by itself establish that proofs are complete, sound within an intended axiom profile, or faithful to compiled execution. ### `Prop` erasure vs. `Type`-level computational witnesses - **`Prop` terms erase at compile time:** Proofs add zero runtime overhead, and Lean's compiler generates no executable code for `theorem` declarations. - **Carry runtime data in `Type`, invariants in `Prop`:** For a computationally relevant type `β`, a `Subtype` value `{ y : β // P x y }` retains its payload `y` at runtime while the proof `P x y` is erased (type formers such as `Regula.Effect.Resp : Op L E → Type` are erased alongside proofs by Lean's compiler). An existential proposition `∃ y, P x y` lives in `Prop`: extracting `y` into `Type` in general requires classical choice (`Classical.choose`), making the definition `noncomputable` so Lean generates no code for it. - **Keep executable surfaces computable and state foundation strength accurately:** Keep `noncomputable` definitions and `noncomputable section` confined to specification and proof surfaces; return `Type`-level witnesses (`{ y : β // P x y }` or `Sigma`) rather than `Classical.choose` on executable APIs, and wire computable entry points so Lean's compiler checks computability. Report exact axiom foundations (`kernel-only`: no axioms; `choice-free`: `propext` and `Quot.sound`; `standard-logical`: `propext`, `Quot.sound`, and `Classical.choice`) without treating foundation strength as a general ranking of software assurance. - **The `noncomputable` enforcement boundary:** Regula adds no rule or profile for `noncomputable` definitions ([2026-11-20](specification/confirmation.md#2026-11-20-noncomputable-definitions), [specification](specification/README.md#noncomputable-definitions)); specification packages such as `RegulaSpecification` define data-valued `noncomputable` witnesses. Lean `v4.36.0`'s compiler (`checkComputable`, `Lean/Compiler/LCNF/ToLCNF.lean:440-455`) already rejects, in each body that Lean compiles, a reference to a constant tagged `noncomputable` or whose `_unsafe_rec` helper is tagged `noncomputable` (as happens when compiling a recursive definition fails inside a `noncomputable section`, via `mkUnsafeRecName`) that is still in a computationally relevant position after rewriting (`constantReplacer`, `Lean/Compiler/LCNF/ToLCNF.lean:517-540`: `@[csimp]` and `@[macro_inline]`) and erasure, unless the referenced constant is `Quot.mk`, `Quot.lift`, or `withPtrEq`, or has `@[extern]` or `@[implemented_by]`. Lean compiles no code from the body of a definition with `@[extern]`, `@[implemented_by]` or an initialization function, so that check reads no reference there, and **RG1011** (with loader checks under **RG2001**) already refuses unexempted `@[implemented_by]` and `@[extern]` on claimed constants, `@[init]`/`@[builtin_init]` naming an initialization function on claimed definitions, and exported claimed-module `@[csimp]` entries targeting theorems not declared in any claimed module. Beyond erased positions, `@[csimp]` and `@[macro_inline]` rewriting, and dependency or toolchain constants, two cases with no compiled code were measured to pass `lake build --wfail` and `lake lint` under `standard-logical`: 1. **Uncalled `noncomputable` definitions** (which also pass the full gate under `standard-logical`; projects wanting strict constructivity can select `choice-free` or `kernel-only`, where **RG1005** refuses any claimed constant depending on `Classical.choice`). 2. **`noncomputable def main` (or `main` inside a `noncomputable section` calling a `noncomputable` definition) in a default `lean_exe` target:** `emitMainFnIfNeeded` (`Lean/Compiler/LCNF/EmitC.lean:1084-1152`) emits no C `main`, yet default static linking (`Lake/Build/Executable.lean:22-35`, `Lake/Build/Common.lean:963-969`, `Lean/Compiler/FFI.lean:49-50`) passes `-lLeanExport` on macOS arm64, resolving `_main` from `libLeanExport.a` (`src/LeanExport.lean:11`) so the compiled binary runs `lean4export` rather than the project's `main` (observed on macOS arm64; not measured on Ubuntu). Keep `main` computable and outside `noncomputable section`, and run built executables to verify their entry point; the full gate already refuses default `lean_exe` targets. ### Failure classes and the Regula checks that close them Each failure class below can slip past a plain `lake build` (or invalidate what a build establishes) unless closed by Lean flags and Regula's proved checks. All rules RG1001–RG1006 and RG1011–RG1013 are proved exact over the closed input (`rg1001_exact`–`rg1006_exact`, `rg1011_exact`–`rg1013_exact`) and linked to the loaded Lean environment (`pass_iff`, `pass_held` in [`specification/RegulaSpecification/Proofs/Load.lean`](specification/RegulaSpecification/Proofs/Load.lean)): - **Proof holes (`sorry`):** A plain `lake build` only warns on `sorry`. Pair `lake build --wfail` with **RG1002**, which refuses any claimed constant depending on `sorryAx` directly or through an import. - **Project and unknown axioms:** `lake check` ignores unused axioms. **RG1001** refuses any `axiom` declared in a claimed module even if unused; **RG1003** refuses transitive dependence on any unknown axiom outside Lean's `propext`, `Quot.sound`, and `Classical.choice` not named by RG1002 or RG1004. - **Compiler-trusted proofs (`native_decide`, `decide +native`, `bv_decide`):** **RG1004** refuses transitive dependence on native-proof axioms (`._native..`, the name form of the axioms these tactics add) and compiler-trust axioms (none declared in `v4.36.0`). *Limits:* RG1004 reads the axiom a proof depends on and not the tactic, so a use that leaves no such axiom is not reported: `bv_decide` returns with no certificate when its normalization closes the goal (`bvDecide'`, `Lean/Meta/Tactic/BVDecide/Main.lean:38-39` at `v4.36.0`). Under the full gate, RG1010 refuses `native_decide` and `decide +native` by their syntax, and any tactic outside its closed table. - **Axiom-profile creep:** **RG1005** refuses any claimed constant depending on an axiom outside the project's declared profile (`kernel-only`, `choice-free`, or `standard-logical`). Every axiom caught by RG1002, RG1003, or RG1004 also violates RG1005. - **Bypassed kernel checks and malformed builds (RG2001):** `debug.skipKernelTC` can accept an unsound theorem during `lake build`. Before giving a pass, the checker selects the claim's cone: each constant of a claimed module, the constants Lean's kernel builds into a term (`Input.kernelNames`), and every constant these reach through what each mentions. It submits to `Regula.Effect.replayParallel` (`lean/Regula/Table.lean`), into an empty kernel environment, each constant of that cone except `Quot.mk`, `Quot.lift`, and `Quot.ind` (which the kernel adds with `Quot`), plus each differing claimed-module copy of a merged theorem under a fresh name. Of that map `Regula.ReplayPartition` (`lean/Regula/ReplayPartition.lean`) skips each `partial` or `unsafe` constant (`isSafeReplayable`), builds a deterministic certified acyclic topological plan (`buildPlan`), checks every mutual inductive block and `Quot` once along a persistent-`PHashMap` spine via `Kernel.Environment.addDeclCore` while comparing every safe constructor, recursor, and quotient constant against what the kernel generated (`buildSpine`, `checkExpectedCtor`, `checkExpectedRec`, `checkExpectedQuot`), seeds predecessor declarations along the spine via `addDeclWithoutChecking`, and verifies every declaration micro-batch concurrently via `Task.spawn` and `verifyBatch` (`addDeclCore`) from its ancestor-closed prefix environment, failing closed on cycles, key/name mismatches, orphan or altered constructors/recursors, or kernel rejection. RG1006 refuses each `partial` or `unsafe` claimed constant except a `partial` recursion helper `b._unsafe_rec` meeting the exempted recursion-helper form or the unsafe half `T.ctorIdx._impl` of a verified compiler-generated `ctorIdx` pair (each mentioning no loop construct and, for a definition or opaque constant, no `Lean.Order.fix`), and that the kernel refuses a safe constant mentioning a `partial` or `unsafe` one is assumed (H6; [what a pass means](specification/README.md#what-a-pass-means)). A failed replay, an unreadable build, an empty claim, an open mention, an unshown constant that fails the loader's checks, a checker running on a Lean other than the pinned release (`Regula.Shell.supportsLean`), or (in the full gate) a case of [the closed list of refusals](specification/README.md#the-closed-list-of-refusals) with exit 2 produces `incomplete` (RG2001, exit 2). A project whose `lean-toolchain` names another release is a different case: the full gate refuses it as RG1010, exit 1 (below). - **Non-termination and unsafe escapes:** **RG1006** refuses claimed constants that are `unsafe`, `partial`, or named as a recursion helper (`b._unsafe_rec` via `Lean.Compiler.isUnsafeRecName?`) without an exempted form (either a `partial` constant `b._unsafe_rec` with neither `@[implemented_by]` nor `@[extern]` whose own base `b` is a safe total definition in the same module with neither, or the unsafe half `T.ctorIdx._impl` of a compiler-generated `ctorIdx` pair whose structural `Expr` matches Lean's `mkCtorIdx` on `getObjTagNat` beside a verified safe `T.ctorIdx` and safe non-single-constructor non-builtin non-`Prop` inductive `T` in the same module), or whose value directly mentions `Lean.Loop.mk` or `repeatM` (`while`, `repeat`, `repeat ... until`)—including a constant that otherwise meets an exempted form. **RG1006** also refuses any claimed definition or opaque constant whose value directly mentions `Lean.Order.fix` ([2026-11-20](specification/confirmation.md#2026-11-20-partial_fixpoint-under-rg1006))—including a constant that otherwise meets an exempted form—which `partial_fixpoint` definitions elaborate to even on non-monadic types via `FlatOrder.instCCPO` (`Lean/Elab/PreDefinition/PartialFixpoint/Main.lean:103-111,192,221`, `Lean/Meta/Order.lean:52-58`, `Init/Internal/Order/Basic.lean:486,964` at `v4.36.0`). *Limits:* RG1006 refuses a constant for none of these alone: `termination_by`, `for` over a list, a mention of `Lean.Order.fix` in a theorem's proof (as in a realized dependency `.eq_def` lemma), a mention of `Lean.Order.lfp_monotone` (`inductive_fixpoint`, `coinductive_fixpoint`, and `coinductive` predicates in `Prop`, which emit no runtime code), a loop or `partial_fixpoint` inside a dependency or the toolchain (such as `IO.iterate`), and a mention only in a type; a theorem with a recursion helper's name, or whose proof mentions a loop construct, is still refused; under the proof verdict, project build-time code could synthesize a constant of the exempted recursion-helper form (closed by RG1010 under the full gate, which also refuses `partial_fixpoint`, `inductive_fixpoint`, `coinductive_fixpoint`, and `coinductive` before compilation). - **Unproved replacement of compiled code:** **RG1011** reads the closed input and refuses any claimed constant with `@[implemented_by]` (other than the safe half `T.ctorIdx` of a verified compiler-generated `ctorIdx` pair) or `@[extern]`, any claimed *definition* for which `@[init]` or `@[builtin_init]` names an initialization function, and any exported (`global` or `scoped`) `@[csimp]` entry registered in a claimed module whose target theorem is not declared in any claimed module's `.olean` (`moduleData`). When Lean's import merges a name across modules and hides a claimed module's own attribute entries, or when a claimed module's index is missing in the loaded environment, the loader (`Facts.unshownFast` / `Facts.moduleAttrIndex`, proved equal to `Facts.unreplaced` and `Facts.uninitialized`, alongside `Facts.ctorIdxEntryOnly` and `Facts.moduleCSimps` in [`lean/Regula/Load.lean`](lean/Regula/Load.lean)) refuses the build as `incomplete` (**RG2001**, exit 2). *Limits:* `opaque` constants with an initialization function (`initialize x : T ← act`) are admitted because Lean's logic states nothing of their value; startup hooks (`@[init]`/`@[builtin_init]` naming no function) are not read; exported `@[csimp]` on a theorem declared in a claimed module (including a one-line claimed alias that restates the equality, `@[csimp] public theorem alias : @f = @g := Dep.thm`, and merged theorems declared in a claimed module's own `moduleData`) is admitted under RG1011 (its safe proof is replayed in the claim's cone and checked by RG1001–RG1006, or by the loader under RG2001 when Lean's import merges it under an unclaimed module's index); `attribute [local csimp]` is `.olean`-invisible (never written to `.olean`) and dependency-registered `@[csimp]` sits in unclaimed modules and is not checked by RG1011, so both stay outside the proof verdict (under the full gate RG1010 refuses `csimp` in each file it reads, a project with a `require` gets only the proof verdict, and the toolchain's own `@[csimp]` registrations stay trusted); calls into dependency or toolchain constants with those attributes pass. - **Hidden runtime panics:** In Lean's logic `panicCore` equals `default`, and its compiled code returns that same `default` and goes on, unless `LEAN_ABORT_ON_PANIC` is set or the program asked to exit on a panic; it prints a message only while panic messages are enabled (`lean_panic_impl`, `src/runtime/object.cpp:176-192` at `v4.36.0`). So a theorem can hold of the value returned while stating nothing of whether a panic occurred, and a proved function goes on after a panic with at most a message on the error stream. **RG1012** refuses any claimed definition or opaque constant whose value directly mentions Lean's four panic functions (`panicCore`, `panic`, `panicWithPos`, `panicWithPosWithDecl`) or any non-theorem constant whose macro-erased last string component contains `!` (covering `xs[i]!`, `Option.get!`, `List.head!`, `String.toNat!`, `Array.back!`, `Array.set!`, `panic!`, `unreachable!`, and `assert!`). *Limits:* `xs[i]?`, `dbg_trace`, and theorems are not refused; panics inside dependencies or the toolchain reached through constants without `!` (such as `outOfBounds`), C panics behind `@[extern]` without `!`, and mentions only in types stay outside RG1012. - **Unencapsulated non-`module` files:** **RG1013** refuses any claimed module whose `.olean` does not record it as a `module` file. It adds nothing to what a proof depends on. *Limits:* RG1013 reports claimed modules only; Lean itself refuses a `module` file that imports a non-`module` file, so dependencies imported by claimed modules must also be `module` files (`Mathlib.lean` and each file below `Mathlib/` at Mathlib's tag `v4.35.0` were measured as `module` files). - **Build-time code execution and metaprogramming escapes:** Under the in-tree proof verdict (`lake lint`, with `REGULA_FULL`, `REGULA_PROOF`, `REGULA_SHARD`, and `REGULA_RECEIPT_OUT` unset), `lake build --wfail` and `lake lint` both run in the project's own Lake, which executes project and dependency build-time code and starts the lint driver that the project's configuration names; even under the out-of-tree proof verdict (`REGULA_PROOF=DIR lake exe lint PROFILE`), the required `lake build --wfail` runs project build-time code beforehand. So the proof verdict holds only for a project that places no file or code aimed at the checker or the toolchain: a project aimed at the checker can forge a pass and exit 0 whatever its build holds ([a project aimed at the checker](specification/README.md#a-project-aimed-at-the-checker)). **RG1010** (full verdict only) reads `lean-toolchain`, `lakefile.toml`, and every reached Lean source file *before* anything compiles, admitting only a closed language subset (`lean/Regula/LanguageSet.lean`) and refusing a `lean-toolchain` that names another Lean release (exit 1; `refuses_another_toolchain` states the case of `v4.34.0`), `run_cmd`, `#eval`, `#guard`, `run_tac`, `by_elab`, `native_decide`, `decide +native`, `macro`, `syntax`, `notation`, `elab`, `initialize`, `lakefile.lean`, plugins, and any unlisted construct (`decision_admitted_iff`, `build_only_after_check`). The guarantee concerns project-written code: the toolchain's own tactics, deriving handlers, and `mkCtorIdx` elaboration that the closed set admits still run during the build (the runtime tag behavior of `mkCtorIdx` is tracked separately under `ctorIdxTag`). Applies only to standalone library projects with no `require` and no Mathlib imports, with the checker started via `REGULA_FULL=DIR lake exe lint PROFILE` (with no option of Lake's) from a Regula checkout built apart from the project, under hypotheses H1–H5 and the [trusted base](specification/README.md#the-trusted-base) at Lean `v4.36.0`. ## Enforcement status Each item in this standard falls into one of three categories: enforced, planned, or manual engineering discipline. RG1001–RG1006, RG1011 and RG1012 report claimed declarations. RG1013 reports claimed modules. When a claimed module exports a `global` or `scoped` `@[csimp]` entry for a theorem that no claimed module declares, RG1011 also reports that theorem with the module that registered it. Every check but RG1010 runs under both verdicts; under both the in-tree proof verdict (`lake lint`) and the out-of-tree proof verdict (`REGULA_PROOF=DIR lake exe lint PROFILE` against built zero-dependency `lakefile.toml` packages without `lakefile.lean` and with non-empty `lean_lib` `defaultTargets` and no shared-`leanLibDir` `[[require]]`), each holds only for a project that places no file or code aimed at the checker or the toolchain. | Practice or requirement | Status | Check or mechanism | Scope and limits | | --- | --- | --- | --- | | No declared project axioms | Enforced | RG1001 | Claimed modules, including unused axioms. | | No `sorry` / `sorryAx` dependencies | Enforced | RG1002 + `lake build --wfail` | Constants of claimed modules, directly or transitively through imports; a `sorry` that no claimed constant depends on is not reported. | | No unknown axioms | Enforced | RG1003 | Outside toolchain `propext`, `Quot.sound`, `Classical.choice`, RG1002, RG1004. | | No native-proof or compiler-trust axioms | Enforced | RG1004 (and RG1010 in full gate) | RG1004 reads the axiom a proof depends on, by the name form that `native_decide`, `decide +native`, and `bv_decide` add, not the tactic; RG1010 refuses `native_decide` and `decide +native` by syntax, and any tactic outside its closed table. | | Axioms restricted to declared profile | Enforced | RG1005 | `kernel-only`, `choice-free`, or `standard-logical`. | | No `unsafe`, `partial`, forged `._unsafe_rec`, or `while`/`repeat` | Enforced | RG1006 | A `partial` helper `b._unsafe_rec` meeting the exempted recursion-helper form for its own safe total base `b`, the unsafe half `T.ctorIdx._impl` of a verified compiler-generated `ctorIdx` pair (each mentioning no loop construct or `Lean.Order.fix`), and dependency loops stay outside RG1006. | | No direct `Lean.Order.fix` (`partial_fixpoint`) in claimed `def` / `opaque` values | Enforced | RG1006 | Refuses claimed definitions and opaque constants whose value directly mentions `Lean.Order.fix`, a constant of an exempted form included. A mention in a theorem's proof (as in a realized dependency `.eq_def` lemma), a mention of `Lean.Order.lfp_monotone` (`inductive_fixpoint`, `coinductive_fixpoint`, `coinductive`), dependency `partial_fixpoint` definitions, and mentions only in types are not refused by this clause, and RG1006's other clauses still read each claimed constant (dependency definitions are not claimed). In the full gate, RG1010 refuses the `partial_fixpoint`, `inductive_fixpoint`, `coinductive_fixpoint` and `coinductive` syntax before compilation; it admits a use of `Lean.Order.fix` by name, which RG1006 refuses after the build. | | Pre-build closed language subset (no project-written build-time code) | Enforced | RG1010 (full verdict only) | Standalone library projects with no `require` and no Mathlib, checked via `REGULA_FULL=DIR lake exe lint PROFILE` (with no option of Lake's) from a Regula checkout built apart from the project; under H1–H5 and trusted base. The toolchain's admitted tactics, deriving handlers, and `mkCtorIdx` elaboration still run. A `lean-toolchain` naming another release is refused here, exit 1. | | Kernel cone replay and closed-form build loading | Enforced | RG2001 | Exits 2 (`incomplete`) on failed replay, empty claim, open mention, unreadable build, or a checker running on a Lean other than the pinned release. `Regula.Effect.replayParallel` and `Regula.ReplayPartition` skip `partial` and `unsafe` constants, check mutual inductive blocks and `Quot` once along a persistent-`PHashMap` spine (comparing safe constructors, recursors, and quotients against what the kernel generated), and check declaration micro-batches concurrently in Lean's kernel via `Task.spawn`; sharded proof runs split declaration batches across `K` proof-route invocations via `Regula.Effect.replayPlanShard` and combine receipts in `verify_shards` under `Assumption.shardTransport` ([`README.md#sharded-proof-verdict-regula_shard-and-verify_shards`](README.md#sharded-proof-verdict-regula_shard-and-verify_shards)). | | No unexempted `@[implemented_by]` or `@[extern]` on claimed constants, no `@[init]`/`@[builtin_init]` naming an initialization function on claimed `def`s, and no exported claimed-module `@[csimp]` targeting a foreign theorem | Enforced | RG1011 (plus RG2001 in loader for hidden module-local entries and missing claimed module indices) | The safe half `T.ctorIdx` of a verified compiler-generated `ctorIdx` pair, `initialize` (`opaque`), bare `@[init]`/`@[builtin_init]` startup hooks naming no function, and exported `@[csimp]` on a theorem declared in a claimed module (including a one-line claimed alias) pass RG1011. Under the proof verdict, `attribute [local csimp]` is `.olean`-invisible (never persisted to `.olean`) and dependency-registered `@[csimp]` sits in unclaimed modules and is not checked by RG1011 (RG1010 refuses `initialize`, `@[init]`/`@[builtin_init]`, and `@[csimp]` in each file the full gate reads). Dependency/toolchain constants pass. | | No direct panic forms in claimed `def` / `opaque` values | Enforced | RG1012 | Theorems, `xs[i]?`, `dbg_trace`, and non-`!`-named dependency panics stay outside RG1012. | | Reached Lean source files have a `module` header | Enforced | RG1010 | Full gate only, before compilation. | | Claimed modules have the `module` flag in their `.olean` files | Enforced | RG1013 | Both the proof verdict and the full verdict check this flag. Lean refuses `module` files importing non-`module` dependencies. | | Actionable fix guidance in diagnostics | Enforced | RG1001–RG1006, RG1011–RG1013 (`Regula.Closed.Guidance`, `Regula.Shell.guidanceLine`) | Every registered rule emits non-blank, branch-tailored Lean `v4.36.0` fix guidance on a 2-space-indented ` fix: ...` line beneath each finding, passed through `Regula.Closed.detailText` and `say` (`finding_guidance_nonblank`, `detailText_guidanceLine`, `say_guidanceLine_spec`). Proof-verdict-only suggestions (`grind`, `@[csimp]`, `initialize`, `import all`) note that RG1010 refuses them in the full gate. | | Additional design, refactoring, and architecture checks | Planned | None yet | Same specification, proof, and simplicity admission bar. | | Theorem statements match human intent | Engineering discipline | Human review | No checker can validate unformalized intent. | | Intrinsic typing at boundaries (`Fin`, `Subtype`, closed sums) | Engineering discipline | Code review | Exemplars: `Input.lean`, `Tables.lean`, `Rule.lean`. | | Spec-first workflow, non-vacuity, proving executed definitions, proof economy | Engineering discipline | Code and proof review | Exemplars: `RuleRecord.lean`, `Rules/RG1011.lean`. | | Certifying algorithms vs. total search with derived termination | Engineering discipline | Code and proof review | Exemplar: `Reach.lean`. | | Pure effect trees, thin IO tables, exhaustive assumption lists | Engineering discipline | Code and proof review | Exemplars: `Effect.lean`, `Table.lean`, `Assumptions.lean`. | | `Prop`-vs.-`Type` witnesses and computable executable surfaces | Engineering discipline | Lean compiler + code review | No Regula rule or profile refuses `noncomputable` ([2026-11-20](specification/confirmation.md#2026-11-20-noncomputable-definitions)). In each body that it compiles, Lean's compiler refuses a computationally relevant reference to a constant tagged `noncomputable` (or whose `_unsafe_rec` helper is tagged) that remains after rewriting and erasure unless the referenced constant is `Quot.mk`, `Quot.lift`, or `withPtrEq`, or has `@[extern]` or `@[implemented_by]`; RG1011 refuses unexempted replacement attributes on claimed code, and `choice-free` / `kernel-only` refuse `Classical.choice` via RG1005. Under `standard-logical`, uncalled `noncomputable` definitions and `noncomputable def main` in a default `lean_exe` (which links `_main` from `libLeanExport.a` on macOS arm64) pass both `lake build --wfail` and `lake lint`; the full gate already refuses default `lean_exe` targets. | | Auditing dependencies, toolchain code, `attribute [local csimp]`, and dependency-registered `@[csimp]` | Engineering discipline | Manual audit | Outside Regula's proof-verdict contract (`local csimp` is never written to `.olean`); RG1010 refuses `@[csimp]` in each file the full gate reads, and the toolchain's own registrations stay trusted. | ## Applying this standard with coding agents When using coding agents on a Lean 4 codebase: 1. **Start files with `module` and keep interfaces narrow:** Export only the types, statements, and `@[expose]` bodies callers need; keep implementation bodies unexposed. 2. **Validate at boundaries into proof-bearing types:** Replace repeated guards and `!` operations with `Fin`, `Subtype`, closed sum types, or explicit `Option`/`Except` results. 3. **Write specs before code and watch proof complexity:** Prove non-vacuity and prove the actual executed definition; when a proof grows much harder than the code, simplify the code or factor out a small proved checker. 4. **Run Regula on the pinned toolchain (`leanprover/lean4:v4.36.0`):** Use `lake build --wfail` and `lake lint` on one build, from the project's own directory with no option of Lake's and `REGULA_FULL`, `REGULA_PROOF`, `REGULA_SHARD`, and `REGULA_RECEIPT_OUT` unset, for the in-tree proof verdict; for built zero-dependency `lakefile.toml` packages without `lakefile.lean` and with non-empty `lean_lib` `defaultTargets` (including metaprogramming, `macro`, or deriving code outside `RG1010`), run `lake build --wfail` in the package and `REGULA_PROOF=DIR lake exe lint PROFILE` (with `REGULA_FULL`, `REGULA_SHARD`, and `REGULA_RECEIPT_OUT` unset) from a Regula checkout built apart from the project without editing `DIR/lakefile.toml` or `DIR/lake-manifest.json` (path `[[require]]` packages sharing the root `leanLibDir` remain outside this contract); for large builds distributed across CI runners, use sharded proof runs with `REGULA_SHARD`/`REGULA_RECEIPT_OUT` and `verify_shards` ([`README.md#sharded-proof-verdict-regula_shard-and-verify_shards`](README.md#sharded-proof-verdict-regula_shard-and-verify_shards)). Proof-verdict routes hold only for a project that places no file or code aimed at the checker or the toolchain, because project build-time code runs before the check (and if any of `REGULA_FULL`, `REGULA_PROOF`, `REGULA_SHARD`, or `REGULA_RECEIPT_OUT` stays set, `lake lint` dispatches on those variables or refuses invalid/conflicting combinations). For a standalone library project without metaprogramming outside `RG1010` that may be aimed at the checker, run the full gate (`REGULA_FULL=DIR lake exe lint PROFILE`, with no option of Lake's and `REGULA_PROOF`, `REGULA_SHARD`, and `REGULA_RECEIPT_OUT` unset) from a Regula checkout built apart from the project ([`README.md#use-it`](README.md#use-it), [`README.md#the-full-gate`](README.md#the-full-gate)). 5. **Read every claimed theorem statement by hand:** Regula's verdicts hold only for [the named configurations](specification/README.md#the-named-configurations) under [the trusted base](specification/README.md#the-trusted-base), and no pass checks that a theorem states what you meant. For rules that govern changes to Regula itself, see [`CONTRIBUTING.md`](CONTRIBUTING.md).