Skills for developing with Lean 4

GitHub stars
84

Install

/plugin install lean@leanprover

Run it inside Claude Code after adding the marketplace with /plugin marketplace add leanprover/skills.

Contents

Discovered from source

Skills 9

Bisecting Lean Toolchains

Use the lean-bisect script (in the lean4 repo at script/lean-bisect) to find which commit introduced a behavior change.

Test File Requirements

Test files must be self-contained with no Mathlib imports (Mathlib is pinned to specific toolchains and will fail on most versions tested). See the minimization skill if you need to reduce a Mathlib test case to a standalone one.

Usage

# Auto-find regression
script/lean-bisect /tmp/test.lean

# Bisect up to a given nightly
script/lean-bisect /tmp/test.lean ..nightly-2024-06-01

# Between nightlies
script/lean-bisect /tmp/test.lean nightly-2024-01-01..nightly-2024-06-01

# Between commits
script/lean-bisect /tmp/test.lean abc1234..def5678

# With timeout
script/lean-bisect /tmp/test.lean --timeout 30

Pass/Fail Determination

The script compares a "signature" of exit code + stdout + stderr. It bisects to find where this signature changes. Use --ignore-messages to only consider exit code.

Test File Patterns

Using exit code

axiom G : Type
axiom op : G -> G -> G

example : ... := by
  <the failing tactic call>

Using #guard_msgs

/--
error: the specific error that should appear
-/
#guard_msgs in
example : ... := by ...

Options

  • --timeout N: Timeout in seconds per test
  • --ignore-messages: Only compare exit codes
  • --nightly-only: Only test nightly releases when bisecting commits
  • --selftest: Verify the script works
  • --clear-cache: Clear ~/.cache/lean_build_artifact/

Workflow for Mathlib Issues

When the issue requires Mathlib:

  1. Create a minimal test case
  2. Use https://github.com/kim-em/mathlib-minimizer to produce a Mathlib-free version (see lean-mwe skill)
  3. Run lean-bisect on the minimized file

Tips

Verify endpoints of the range show different behavior before bisecting. Keep tests fast — each bisection step runs the full test.

Minimizing Lean Errors

Workflow

  1. Set up the guard (#guard_msgs or #guard_panic)
  2. Run lake exe minimize
  3. Review and polish the output

Repository Setup

For Mathlib-related bugs:

cd /tmp
git clone https://github.com/kim-em/mathlib-minimizer.git
cd mathlib-minimizer
lake exe cache get

For pure Lean 4 bugs:

cd /tmp
git clone https://github.com/kim-em/lean-minimizer.git
cd lean-minimizer

Step 1: Create the Test File

For Regular Errors

Use #guard_msgs to capture the exact error:

import Mathlib.SomeModule

/--
error: the exact error message
goes here verbatim
-/
#guard_msgs in
example : ... := by some_tactic

For Panics

import Mathlib.SomeModule

#guard_msgs in
#guard_panic in
some_command_that_panics

Step 2: Verify the Guard Works

lake env lean YourFile.lean

No output = success (guard passed). Error output = guard failed, and you need to redesign the test case.

Step 3: Run the Minimizer

lake exe minimize YourFile.lean

Output is written to YourFile.out.lean.

Useful Options

  • --resume: Continue from the output file if interrupted
  • --quiet: Suppress progress output
  • --only-delete: Only run the deletion pass
  • --only-import-inlining: Only inline imports

Never use --no-import-inlining. The entire point is to produce a self-contained file.

For Long-Running Minimizations

Use --resume to continue from where you left off:

# Initial run (Ctrl-C if needed)
lake exe minimize YourFile.lean

# Resume later
lake exe minimize YourFile.lean --resume

After manually editing the .out.lean file, always use --resume to continue from the edited state.

Step 4: Review the Output

lake env lean YourFile.out.lean

Checklist Before Filing

  • The .out.lean file compiles with the expected error/panic
  • No Mathlib imports remain (ideal) or minimal imports remain
  • The error message in #guard_msgs matches exactly

Lean PR Conventions

Commit Message Format

All PR titles must follow the format:

<type>: <subject>

<type> is one of:

  • feat — feature
  • fix — bug fix
  • doc — documentation
  • style — formatting
  • refactor
  • test — adding missing tests
  • chore — maintenance
  • perf — performance improvement

<subject>: imperative present tense, lowercase, no period.

For feat/fix PRs, begin the description with "This PR " — the first paragraph is automatically used in release notes.

Changelog Labels

Every feat or fix PR must have a changelog-* label:

LabelCategory
changelog-languageLanguage features and metaprograms
changelog-tacticsUser-facing tactics
changelog-serverLanguage server, widgets, and IDE extensions
changelog-ppPretty printing
changelog-libraryLibrary
changelog-compilerCompiler, runtime, and FFI
changelog-lakeLake
changelog-docDocumentation
changelog-ffiFFI changes
changelog-otherOther changes
changelog-noDo not include in changelog

Module System for src/ Files

Files in src/Lean/, src/Std/, and src/lake/Lake/ must have both module and prelude declarations. With prelude, nothing is auto-imported — you must explicitly import Init.* modules.

module

prelude
import Init.While
import Init.Data.String.TakeDrop
public import Lean.Compiler.NameMangling

Check existing files in the same directory for the pattern.

Files outside these directories (e.g. tests/, script/) use just module.

Copyright Headers

New files in src/ require a copyright header:

/-
Copyright (c) YYYY Author or Organization. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Author Name
-/

Check other recent files in the repository to determine the correct copyright holder. Test files (in tests/) do not need copyright headers.

PR Conventions

Keep descriptions concise:

  • Start with a paragraph beginning "This PR ..." — no section headers
  • No "## Summary" header — just start with the text
  • No "Test plan" section — we rely on CI
  • No "Implementation details" section — the code speaks for itself

Lean Proof Methodology

These are non-negotiable constraints for writing Lean proofs correctly.

One Step at a Time

Write one tactic, check diagnostics (use done to see unsolved goals), repeat. Never write multiple tactics before checking.

by sorry is acceptable: For placeholders you're not actively working on. done is required: When you expect there to be next steps in an active proof.

Error Priority

Fix errors in this order — higher-priority errors make lower-priority ones unreliable:

  1. Syntax errors → 2. Type errors → 3. Unsolved goals / tactic failures → 4. Linter warnings

"Unsolved goals" errors appear on by or => lines, NOT where you add tactics. If there's an "unsolved goals" on line 59 but a tactic error on line 65 — fix line 65 FIRST.

Stop writing tactics after any error.

Work on the Hardest Case First

Across Theorems

Go directly to the target theorem. Don't fill in sorrys in helper lemmas first — Lean treats sorry as an axiom, so dependent theorems still work.

Move sorries earlier in the file by replacing a sorry proof with references to simpler lemmas:

-- Before:
theorem main_theorem : A = C := by sorry

-- After:
theorem lemma1 : A = B := by sorry
theorem lemma2 : B = C := by sorry
theorem main_theorem : A = C := by
  rw [lemma1, lemma2]

Within a Proof

When a proof has multiple cases, sorry the easy cases and work on the hardest one first. If the hard case fails, effort on easy cases is wasted.

match n with
| 0 => sorry -- fill in later
| 1 => sorry -- fill in later
| n + 2 => -- WORK ON THIS FIRST

Proof Cleanup

After getting a proof to work, clean it up immediately:

  • Combine redundant steps (rw [a]; rw [b] → rw [a, b])
  • Test if simp can handle more (remove earlier steps one by one)
  • Find the truly minimal proof

Dependent Type Rewriting Issues

When you encounter "motive is not type correct" or similar errors during rewriting:

The Problem

Rewriting a term b that appears in dependent types (like hab : a ≤ b) fails because the motive cannot abstract over the dependencies.

have hb : b = f x
rw [hb]  -- Error: motive is not type correct

The Solution: Generalize First, Instantiate Last

Prove a generalized statement for an arbitrary parameter, then instantiate:

suffices ∀ s, statement_about s by
  have h_specific := the_equality_you_have
  convert this ?_ <;> exact h_specific
intro s
-- Now prove the general statement for arbitrary s

This works because the generalized statement has no dependencies on the problematic term, and convert handles the dependent type coercions at the end.

Verification

Never declare a proof complete while sorry placeholders or error diagnostics remain.

Lean 4 Repository Setup

The first time you build in a lean4 repository clone, you need to run

cmake --preset release
make -j -C build/release

The cmake command is not needed on subsequent builds.

Tests

Running a Single Test

cd tests/lean/run
./test_single.sh example_test.lean

Running the Full Test Suite

make -j -C build/release test ARGS="-j$(nproc)"

Writing Tests

  • All new tests should go in tests/lean/run/
  • These tests don't have expected output files — they run on a success/failure basis
  • Use #guard_msgs to check for specific messages

Lean 4 repositories for interactive use

If you are cloning or repairing the leanprover/lean4 repository for a user to work in, you need to do further set up. First, do an initial build according to the instructions above. Then you'll need to pick a toolchain name. If this is the only clone of lean4 on the machine, just use lean4. Otherwise you might use something like lean4-XYZ.

Then run the following commands:

elan toolchain link lean4-XYZ build/release/stage1
elan toolchain link lean4-XYZ-stage0 build/release/stage0
echo lean4-XYZ > lean-toolchain
echo lean4-XYZ > script/lean-toolchain
echo lean4-XYZ > tests/lean-toolchain
echo lean4-XYZ-stage0 > src/lean-toolchain

After setting up the toolchains, verify it worked:

cd tests/lean/run
lean --version  # Should show the commit hash from your clone, not a release version

When done with the clone, remove the toolchains:

elan toolchain uninstall lean4-XYZ
elan toolchain uninstall lean4-XYZ-stage0
  • The tests/ directory needs stage1 because tests run against the full Lean system
  • The src/ directory needs stage0 because it's rebuilding the stdlib itself

Building Mathlib

Fetch the Mathlib olean cache before build:

lake exe cache get

Use lake exe cache get! (with !) to force re-download if the cache appears corrupt.

When building Mathlib reduce verbosity to save on tokens:

lake build -q --log-level=info

For merge conflict resolution or small fixes build only the affected files: lake build Mathlib.Foo.Bar -q --log-level=info. Often it is fine to leave a complete build to CI. If you need a thorough local build, use lake build Mathlib MathlibTest Archive Counterexamples && lake exe runLinter.

Mathlib PR Conventions

Commit Message Format

PR titles follow <type>(<scope>): <subject>.

Types: feat, fix, doc, style, refactor, test, chore, perf, ci

Scope is the module path with the Mathlib/ prefix stripped — e.g. Data/Nat/Basic, Topology/Constructions.

Subject uses imperative present tense, no capitalized first letter, no trailing period.

Full conventions: https://leanprover-community.github.io/contribute/commit.html

Workflow

  • PRs must come from forks, not branches on the main repo.
  • Run lake exe mk_all when adding or removing files (updates the import root).
  • PR dependencies use checkbox syntax in the description: - [ ] depends on: #XXXX
  • Comment !bench on a PR to trigger performance benchmarking.

Labels

Labels are added/removed via GitHub comments.

Author-managed:

  • awaiting-author — reviewer feedback needs addressing
  • WIP — work in progress
  • easy — trivial PRs (single lemma, typo fix, <25 line diff)
  • help-wanted, please-adopt — requesting help

Topic: t-topology, t-algebra, t-combinatorics, etc.

Downstream projects: carleson, FLT, etc.

Automated: merge-conflict is added/removed automatically when conflicts are detected or resolved.

Merge Process

  1. Reviewer approves and adds maintainer-merge
  2. Maintainer adds ready-to-merge
  3. Bors bot merges the PR

For delegated PRs (maintainer trusts author to finalize): the author comments bors merge to trigger the merge.

The review queue is at https://leanprover-community.github.io/queueboard/ — PRs with merge conflicts or pending CI don't appear there.

Style and Naming

Before submitting, read the relevant guides — these are the authoritative references:

Mathlib PR Review

Attributes and API

  • New definitions should come with associated lemmas and appropriate attributes (@[simp], @[ext], etc.).
  • Watch for instance diamonds.
  • Prefer bundled morphisms, FunLike API for morphism classes, SetLike API for subobject classes.

Style Points Specific to Mathlib

  • Simp squeezing: Terminal simp calls should NOT be squeezed (replaced with simp only [...]) unless there's a measured performance problem. Unsqueezed simp is more maintainable and doesn't break when lemmas are renamed.
  • Normal forms: Prefer s.Nonempty over alternatives. Use hne : x ≠ ⊥ in hypotheses (easier to check), hlt : ⊥ < x in conclusions (more powerful).
  • Transparency: Needing erw, or rfl after simp/rw usually means the API is missing lemmas.
  • File size: Consider splitting files that exceed ~1000 lines or cover multiple topics.

Reference Guides

The full review guide and style references:

Nightly Testing

Lean 4 publishes nightly toolchain builds from master. Batteries and Mathlib each have a nightly-testing branch that tracks these nightlies and runs CI against them. When CI passes, a nightly-testing-YYYY-MM-DD tag is created. When it fails, fixes are needed before the new toolchain can be adopted.

The mathlib4-nightly-testing Fork

Mathlib's nightly testing lives in a separate fork: leanprover-community/mathlib4-nightly-testing, not on the main leanprover-community/mathlib4 repo. This keeps experimental toolchain branches out of the main repository. When Lean PRs affect Mathlib, lean-pr-testing-NNNN branches are created here automatically.

Key Branches

  • nightly-testing — tracks the latest Lean nightly. CI runs here determine whether a nightly is usable.
  • nightly-with-mathlib — points to the latest nightly that passes Mathlib CI. Lean PRs that may affect downstream should base off this branch.
  • bump/v4.X.Y — accumulates reviewed adaptations for an upcoming Lean release. Adaptation PRs merge nightly-testing changes into this branch, and master is regularly merged in during release cycles.
  • lean-pr-testing-NNNN — created automatically to test specific Lean PRs against Mathlib.

Zulip

https://leanprover.zulipchat.com/#narrow/channel/nightly-testing has up-to-date status on nightly builds, failures, and adaptation work.

Full Details

The canonical reference for branch and tag conventions across lean4, Batteries, and Mathlib is: https://leanprover-community.github.io/contribute/tags_and_branches.html. If you are asked to work on nightly-testing, or lean-pr-testing-NNNN branches, you should read that page.

Sponsors

Details

Marketplace
leanprover/skills
Category
Community