codex/skills/lean/SKILL.md
Use for deliberate Lean 4 work: proof repair, theorem development, verified programs, model/specification design, external-code models, state-machine or trace invariants, termination proofs, Std/mathlib theorem discovery, Lake/toolchain diagnosis, and high-assurance trust audits. Do not use for Lean management/process-improvement, Coq/Isabelle/Agda/Rocq work, or informal pseudocode unless comparison or translation to Lean 4 is requested.
npx skillsauth add tkersey/dotfiles leanInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
You are working in Lean 4. The default deliverable is a checked Lean artifact: a compiling file, theorem, definition, model, or precise diagnostic. Prose is secondary and must not overclaim what Lean checked.
lean-toolchain, Lake configuration, lock/manifest state, imports, and nearby style as authoritative. Do not upgrade Lean, Std, mathlib, or dependencies unless the user explicitly asks or the task is otherwise impossible and the tradeoff is stated.#check, #print, dependency source, or documentation matching the pinned version.sorry, admit, new axioms, unsolved goals, intentionally broken declarations, or scratch examples unless the user explicitly requests a sketch. Report any remaining placeholders.unsafe, partial, noncomputable, native_decide, decide +native, @[implemented_by], @[csimp], external code, generated code, IO, FFI, clocks, filesystems, networks, randomness, concurrency, and adapters must be isolated or reported when relevant to the claim.Classify the task before editing.
impl = spec, soundness, completeness, refinement, round trip, idempotence, or invariant preservation.When inside a repository, inspect before proposing version-sensitive code:
cat lean-toolchain 2>/dev/null || true
ls lakefile.lean lakefile.toml lake-manifest.json 2>/dev/null || true
find . -maxdepth 3 -name '*.lean' | head
Then inspect the target file's imports, namespace, nearby theorems, existing tactics, and CI/build commands. Prefer the smallest command that checks the changed artifact:
lake env lean path/to/File.lean
lake build +Module.Name
lake build
Use lake env lean --run path/to/File.lean only for executable scripts or examples with main. Use plain lean only for toy files outside a Lake project. For mathlib-heavy projects with missing compiled dependencies, consider lake exe cache get before treating dependency build time as a proof failure.
For verification tasks, keep this card current:
Artifact under proof: Lean implementation | Lean spec/model | generated code | external adapter/tests | theorem library
Claim type: equality | refinement | soundness | completeness | invariant preservation | round trip | idempotence | case obligation | trace safety
Top-level theorem(s): ...
Trusted assumptions: Lean kernel, imported axioms, classical choice, native evaluation, compiler/runtime, external correspondence, IO/FFI/environment, adapters/tests
Not proved: ...
Allowed claim shapes:
Never write "the software is proved correct" unless the production implementation is itself in Lean, generated from verified Lean under stated assumptions, or connected to the Lean artifact by a checked refinement/semantics theorem.
Reproduce the first real failure on the smallest declaration or example that still fails.
Interrogate the environment:
#check name
#print name
#print axioms theorem_name
#eval expression
#eval is exploration, not proof. Use it only for executable pure code or harmless diagnostics.
Normalize before searching for clever tactics:
rfl
simp
simpa
simp_all
Structure the proof explicitly:
intro h
constructor
cases h
rcases h with ⟨a, b, c⟩
refine ⟨_, _⟩
have h1 : P := by ...
suffices h2 : Q by ...
change NewGoal
show NewGoal
Use deliberate rewrites when they are the proof idea:
rw [h]
rw [← h]
nth_rewrite 1 [h]
Choose induction to match the theorem:
Escalate to domain tactics only after simplifying the goal, and only when available under local imports:
omega
linarith
nlinarith
ring
norm_num
decide
exact?
apply?
aesop?
grind
Replace fragile broad automation with helper lemmas when the theorem supports a correctness claim.
Re-run the project-aware check command after each meaningful proof repair.
Use the spec/implementation/proof split aggressively:
def spec (i : Input) : Output := ...
def impl (i : Input) : Output := ...
theorem impl_eq_spec (i : Input) :
impl i = spec i := by
...
For abstract or nondeterministic behavior, use a relation:
def SpecRel (i : Input) (o : Output) : Prop := ...
def impl (i : Input) : Except Error Output := ...
theorem impl_sound (i : Input) (o : Output) :
impl i = .ok o -> SpecRel i o := by
...
Only prove completeness if the relation is functional enough and the implementation truly returns every admitted output. For optimized code, first prove a simple model, then prove the optimized helper/array/loop/accumulator implementation refines that model. Keep IO at the boundary and prove the pure core.
Use auditable theorem names:
_eq_spec_refines_spec_sound_complete_correct_preserves_inv or _preserves_invariant_roundtrip_idempotent_normalized_terminatescase_...When implementation code is not Lean:
Default to pure transition modeling:
structure State where
-- fields
structure StepResult where
output : Output
state' : State
trace : List Event
def step (s : State) (i : Input) : Except Error StepResult := ...
def Inv (s : State) : Prop := ...
theorem step_preserves_inv
(s : State) (i : Input) (r : StepResult) :
Inv s ->
step s i = .ok r ->
Inv r.state' := by
...
For many-step properties, prove one-step preservation first, then lift over traces/input lists by induction.
Prefer total definitions. Repair recursion in this order:
termination_by and decreasing_by with a clear measure;Avoid partial for logic-facing definitions. If runtime partiality is intended, isolate it behind a total model and prove properties of the model.
Search by head symbols, constructors, namespaces, and nearby naming conventions. Prefer local source and .lake/packages over web examples because they match the pinned version. Before relying on any theorem:
#check Theorem.name
#print Theorem.name
Use simp with intent:
simp [foo, bar]
simpa using h
simp at h
simp_all
simp only [lemma1, lemma2, theorem3]
Add [simp] only for canonical, directionally simplifying, terminating, broadly useful lemmas. Do not mark expansive, reversible, or one-off rewrites as [simp].
Run this lane for production verification, high assurance, proof certificates, external-code claims, generated-code claims, or any user request involving "audit", "prove correct", "sound", "no assumptions", or "trust".
Scan changed Lean files:
rg -n --glob '*.lean' --glob '!.lake/**' --glob '!lake-packages/**' \
'\b(sorry|admit|axiom|unsafe|partial|noncomputable|native_decide)\b|@\[(implemented_by|csimp)\]|implemented_by|csimp|decide \+native' .
If this replacement skill's script is available, prefer:
scripts/lean_trust_audit.sh path/to/file-or-directory
For each theorem supporting the final claim, temporarily inspect:
#print axioms theorem_name
Classify the footprint:
sorryAx / incomplete proof dependency;Lean.trustCompiler or native-computation assertion axioms;For adversarial or high-risk proof artifacts, consider the stronger validation ladder: clean build, #print axioms, lean4checker --fresh Module.Name if available, and external checker/comparator workflows when the environment and risk justify them.
Do not treat a dependency download/build failure as a theorem failure. Separate:
.lake build products;lean-toolchain;lake-manifest.json;Use lake update only when dependency resolution changes are intended. For proof repair and local correctness work, preserving the lock state is usually the right answer.
Use this order:
show or change.simp [foo] or unfold foo.example.For ordinary Lean edits:
Changed: ...
Checked with: ...
Result: ...
Theorems/definitions: ...
Placeholder status: ...
Notes: ...
For verification tasks:
Verification boundary: ...
Formal artifacts: ...
Top theorem names: ...
Build/check command: ...
Result: ...
Placeholder status: ...
Axiom/trust status: ...
What Lean proved: ...
What Lean did not prove: ...
If a proof cannot be completed in the current response, still provide the strongest checked partial artifact, the exact remaining goal/error, and the next local lemma or theorem-shape change needed. Do not promise background work.
Read selectively:
references/verification-boundaries.mdreferences/external-code-verification.mdreferences/trust-audit.mdreferences/setup-and-workflow.mdreferences/proof-playbook.mdreferences/program-correctness.mdreferences/mathlib-search-and-style.mdreferences/version-sensitive-features.md$lean: references/start-prompts.mdThe pinned project, local imports, and actual Lean errors are authoritative over all references.
tools
Invokes Apple's macOS 27 fm command-line tool from a local Mac to use the on-device system model or Private Cloud Compute, including instructions, image prompts, schema-constrained JSON, and noninteractive automation. Use when the user asks to run Apple Foundation Models through fm, compare system versus pcc, generate structured output, or automate fm without Swift or an app.
development
Compile historical Codex sessions into governed counterfactual evidence, evaluate an existing owner-applied candidate through blinded paired HCTP trials, and fold observable evidence into RUN, OBSERVE, or STOP. Use for `$hylo`, CRF extraction, counterfactual replay, source-governed direct or historical trials, sealed evidence, paired baseline/candidate evaluation, causal frontiers, or evidence-governed improvement.
testing
Ensure a `ledger` command is available on PATH; materialize, validate, record, replay, and project requested Actuating artifacts without taking semantic or execution authority; coordinate the shared Learnings/Synesthesia/Negative Ledger lifecycle checkpoint and repo-local source-memory reconciliation; address Universalist plans and receipts; and perform pure artifact validation.
testing
Classify and quotient review findings, failing tests, incidents, bug reports, migration failures, and other witnessed falsifiers against accepted intent and the current Construction. Author counterexample-set/v1 without selecting repairs, counting review credit, or granting mutation.