Unified Lean 4 plugin (draft, formalize, autoformalize, prove, autoprove, disprove, checkpoint, review, refactor, golf, learn, diagnose) — LSP-first, scripts fallback

GitHub stars
489

Install

/plugin install lean4@lean4-skills

Run it inside Claude Code after adding the marketplace with /plugin marketplace add cameronfreer/lean4-skills.

Contents

Discovered from source

Skills 1

Lean 4 Theorem Proving

Use this skill whenever you're editing Lean 4 proofs, debugging Lean builds, formalizing mathematics in Lean, or learning Lean 4 concepts. It prioritizes LSP-based inspection and mathlib search, with scripted primitives for sorry analysis, axiom checking, and error parsing.

Core Principles

Search before prove. Many mathematical facts already exist in mathlib. Search exhaustively before writing tactics.

Build incrementally. Lean's type checker is your test suite—if it compiles with no sorries and standard axioms only, the proof is sound.

Respect scope. Follow the user's preference: fill one sorry, its transitive dependencies, all sorries in a file, or everything. Ask if unclear.

Use 100-character line width for Lean files. Do not wrap lines at 80 characters — Lean and mathlib convention is 100. If a line fits within 100 characters, keep it on one line. See mathlib-style for breaking strategies when lines exceed 100.

Mathlib style quick check. For ordinary mathematical lambdas, write fun x ↦ ... (\mapsto), not fun x => .... Use => for match/do branches and metaprogramming callback idioms. Prefer show P by tac for tactic proofs; use show P from term only for term proofs. See mathlib-style.

Preserve statements and signatures — they're the file's contract. Theorem/lemma statements and type signatures are off-limits unless the user explicitly requests changes; changing them can break callers or alter the theorem being proved. If a proof seems to require changing a statement or adding a custom axiom, stop and discuss first because that changes the contract or the proof's trust basis. Exception: within synthesis wrappers (/lean4:formalize, /lean4:autoformalize), session-generated declarations may be redrafted under the outer-loop statement-safety rules; see cycle-engine.md.

Docstrings are scoped by workflow. Existing docstrings are API. The default is Rule A — any workflow that mutates existing declarations follows it unless the user explicitly requests docstring changes:

ModeMay doBoundary
A — editing existing declarations (e.g. /lean4:prove, sorry-filler-deep, golf, refactor, any agent editing existing decls)adjust inline comments in proof bodiesnever rewrite an existing docstring — explicit user request only
B — review (/lean4:review)flag weak/missing docstrings and propose replacement text in the reportread-only — never mutates files
C — new-file / new-decl generation (/lean4:draft, /lean4:formalize, /lean4:autoformalize)emit module/declaration docstrings on files or declarations it newly createsexisting docstrings stay under Rule A

Per-command policy lives in each command's doc. The docstring split applies in every project; when the mathlib Template Gate selects the mathlib header, Rule C fills its module-docstring slot — Rule C neither selects nor redefines the template.

Commands

CommandPurpose
/lean4:draftDraft Lean declaration skeletons from informal claims
/lean4:formalizeInteractive formalization — drafting plus guided proving
/lean4:autoformalizeAutonomous end-to-end formalization from informal sources
/lean4:proveGuided cycle-by-cycle theorem proving with explicit checkpoints
/lean4:autoproveAutonomous multi-cycle theorem proving with explicit stop budgets
/lean4:disproveGuided counterexample search with certified refutation
/lean4:checkpointSave progress with a safe commit checkpoint
/lean4:reviewRead-only code review of Lean proofs
/lean4:refactorLeverage mathlib, extract helpers, simplify proof strategies
/lean4:golfImprove Lean proofs for directness, clarity, performance, and brevity
/lean4:learnInteractive teaching and mathlib exploration
/lean4:diagnoseDiagnostics, cleanup, and migration help

/lean4:* names are the native plugin's command aliases and also serve as stable workflow names throughout this documentation. On hosts without command registration (skill-only or portable installs), invoke the lean4 skill with your host's normal syntax and ask for the named workflow — e.g., "Use the guided prove workflow on Foo.lean:42."

This plugin ships a host-agnostic parser (lib/command_args/) that covers the parser-decidable startup rules of the seven parameter-heavy commands (draft, learn, formalize, autoformalize, prove, autoprove, disprove). A small set of documented startup rules in these commands depend on runtime context (repo- level search, interactive prompting) and are applied by the command after reading the parser's output. The other commands (checkpoint, review, refactor, golf, diagnose) remain model-parsed. When a host adapter installs the UserPromptSubmit hook, the parser runs before the model sees a /lean4:* prompt matching one of the seven covered commands, injects a validated-invocation block into context, and rejects invalid invocations at the hook level; invocations of the other commands pass through unchanged. Hosts without the hook fall back to model-parsed startup via the shared command-invocation.md contract. Commands always announce resolved inputs, reject invalid startup configs before doing work, and treat wall-clock budgets like --max-total-runtime as best-effort.

Which Command?

SituationCommand
Draft a Lean skeleton (skeleton by default)/lean4:draft
Draft + prove interactively/lean4:formalize
Filling sorries (interactive)/lean4:prove
Filling sorries (unattended)/lean4:autoprove
Searching for a counterexample to refute a claim/lean4:disprove
Save point (per-file + project build, best-effort axiom scan, commit)/lean4:checkpoint
Quality check (read-only)/lean4:review
Simplify proof strategies (mathlib leverage, helpers)/lean4:refactor
Optimizing compiled proofs/lean4:golf
New to this project / exploring/lean4:learn --mode=repo
Navigating mathlib for a topic/lean4:learn --mode=mathlib
Something not working/lean4:diagnose
Formalize + prove end-to-end (unattended)/lean4:autoformalize --source=... --claim-select=first --out=...

Contributing (lean4-contribute plugin)

If the lean4-contribute plugin is installed, you may suggest these commands at natural stopping points. Rules:

  • Suggest first, never invoke unprompted. Offer a one-line question; do not start the command flow.
  • Only invoke after explicit user opt-in in the current conversation. Silence, topic change, or implicit frustration do not count as consent.
  • At most once per topic per session unless the user engages.
  • Never mid-proof. Wait for a natural stopping point.
SituationSuggest
Problem appears to be in lean4-skills itself (wrong command behavior, contradictory docs, broken lint, bad guardrail, confusing plugin UX) — not ordinary Lean/mathlib/user-proof problems"This looks like a lean4-skills bug. Want me to draft a bug report?" → /lean4-contribute:bug-report
User wants a workflow the plugin doesn't support, says a command should behave differently, or you must recommend awkward manual steps due to a missing feature"This looks like a plugin workflow gap. Want me to draft a feature request?" → /lean4-contribute:feature-request
Result seems reusable beyond the current task: tactic-selection heuristic, mathlib search pattern, anti-pattern, documentation gap with a clear lesson — not one-off theorem facts or private repo details"That seems reusable beyond this task. Want me to draft a shareable insight?" → /lean4-contribute:share-insight

If the plugin is not installed and the user clearly hit a lean4-skills bug, workflow gap, or reusable insight (same criteria as above — not ordinary Lean/mathlib issues), you may offer the install hint once:

  • At most once per session. Do not repeat if the user declined, ignored it, or moved on.
  • Never mid-proof or during an active debugging loop.
  • One short line, not a pitch: "If you want, install the lean4-contribute plugin and I can draft that report for you here." See the lean4-contribute README for setup.

Typical Workflow

┌─ Entry points (pick one) ──────────────────────────────────────────────────────────┐
│ /lean4:draft              Skeleton by default (--mode=attempt for shallow proof)   │
│ /lean4:formalize          Interactive: draft + guided proving                      │
│ /lean4:autoformalize      Autonomous: draft + autonomous proving                   │
└────────────────────────────────────────────────────────────────────────────────────┘
        ↓ (if sorries remain)
/lean4:prove / autoprove    Proof engines (sorry filling, no header edits)
        ↓
/lean4:refactor            Leverage mathlib, extract helpers (optional)
        ↓
/lean4:golf                Improve proofs (optional)
        ↓
/lean4:checkpoint          Save point (per-file + project build)

Use /lean4:learn at any point to explore repo structure or navigate mathlib. Three entry points: /lean4:draft for skeletons, /lean4:formalize for interactive synthesis (draft + guided proving), /lean4:autoformalize for unattended source-to-proof.

Refutation branch: Use /lean4:disprove <target> when the goal is to refute a statement rather than prove it. Always interactive; runs a 6-phase cycle (Plan → Work → Checkpoint → Review → Accumulate → Continue/Stop) where Phase 1 generates dynamic Step 0 / Step 1 / Step 2 menus seeded by accumulated evidence (Phase 5 — Accumulate — replaces prove's Replan). Each cycle is a widening search pass over the same target. Append-only — it adds a T_counterexample theorem alongside the original sorry, never rewrites the original declaration. Requires Python 3.11+ (registry loader). See disprove-engine.md, incl. its Implementation Status table (deterministic vs model-mediated vs deferred).

Notes:

  • /lean4:prove asks before each cycle; /lean4:autoprove loops autonomously with explicit stop budgets
  • Both trigger /lean4:review at configured intervals (--review-every)
  • When reviews run (via --review-every), they act as gates: review → replan → continue. In prove, replan requires user approval; in autoprove, replan auto-continues
  • Review supports --mode=batch (default) or --mode=stuck (triage); review is always read-only
  • /lean4:autoformalize wraps draft+autoprove in a single command (source → claims → skeletons → proofs); replaces autoprove --formalize=auto
  • Proof engines (prove/autoprove) never modify declaration headers (header fence)
  • /lean4:disprove reports REFUTED only when Lean typechecks the negation; otherwise WITNESS_UNCERTIFIED or INCONCLUSIVE
  • If you hit environment issues, run /lean4:diagnose to diagnose

LSP Tools (Preferred)

Sub-second feedback and search tools (LeanSearch, Loogle, LeanFinder) via Lean LSP MCP:

lean_goal(file, line)                           # See exact goal
lean_hover_info(file, line, col)                # Understand types
lean_local_search("keyword")                    # Fast local + mathlib (unlimited)
lean_leanfinder("goal or query")                # Semantic, goal-aware (10/30s)
lean_leansearch("natural language")             # Semantic search (3/30s)
lean_loogle("?a → ?b → _")                      # Type-pattern (unlimited if local mode)
lean_hammer_premise(file, line, col)            # Premise suggestions for simp/aesop/grind (3/30s)
lean_state_search(file, line, col)              # Goal-conditioned lemma search (3/30s)
lean_multi_attempt(file, line, snippets=[...])  # Test multiple tactics
lean_diagnostic_messages(file)                  # Per-file error/warning check
lean_code_actions(file, line)                   # Resolve "Try this" suggestions to edits

lean_run_code is for isolated scratch experiments, not a substitute for live proof-state inspection via lean_goal/lean_multi_attempt/lean_diagnostic_messages. Prefer live-file tools when the question depends on actual file context.

Capabilities

CapabilityRequiredCheckFallback
Lean / Lakeyeslean --version, lake --versionnone — run /lean4:diagnose
Python 3yes (scripts)python3 --version or persistent $LEAN4_PYTHON_BINnone for script-dependent operations
Helper runtime pathyes (scripts)trusted Codex bin_dir/scripts_dir, or persistent $LEAN4_SCRIPTSuse the diagnose workflow; stay LSP-only if unresolved
Lean LSP MCPnotry lean_goal on any .lean filescripts + lake env lean (file-level only)
lean_run_codenotry calling itlake env lean on temp file
lean_code_actionsnotry calling itmanual "Try this" application
Subagent dispatchnohost-dependentrun work in main thread
Slash commandsnohost-dependentfollow skill instructions directly

Operating Profiles

The skill adapts to what's available. Determine your profile by checking capabilities above, then follow the corresponding guidance.

Runtime path resolution

Resolve the helper runtime in this order:

  1. Trusted native Codex plugin: SessionStart context contains lean4_plugin_runtime=codex, absolute bin_dir / scripts_dir paths, and shell_env_persistent=false. Substitute those literal absolute paths into helper commands. They are context values, not shell variables: invoke /absolute/bin/lean4-skills-…, never $bin_dir/…, and do not expect bare wrappers on PATH.
  2. Persistent environment: use $LEAN4_PLUGIN_ROOT, $LEAN4_SCRIPTS, $LEAN4_REFS, and bare wrappers verified on PATH.
  3. No helper runtime: remain in the LSP-backed core skill and skip script-dependent steps until the installation is repaired or upgraded.

Do not emit $LEAN4_BIN/... or $LEAN4_SCRIPTS/... commands when those shell variables are unset. A trusted Codex absolute path is a complete alternative, not evidence that persistent variables exist.

full (all capabilities)

MCP + subagents + commands. Full workflow with live goal inspection, tactic testing, and parallel subagent dispatch (requires disjoint owned-file sets per agent, or separate worktrees). Subagents get pre-collected MCP context per cycle-engine.md § Pre-flight Context. If lean_run_code is unavailable, use /tmp scratch files with lake env lean for isolated experiments.

mcp_main_only (MCP available, no subagent dispatch)

MCP works in the main thread. Run all proof work directly — do not delegate to subagents. All cycle-engine phases execute in-thread. If lean_run_code is unavailable, use /tmp scratch files with lake env lean for isolated experiments.

scripts_only (no MCP, no subagents)

Use the resolved helper runtime (scripts_dir under native Codex, $LEAN4_SCRIPTS under a persistent environment) for search and use lake env lean / lake build for validation. Key limitations in this mode:

  • No live goal inspection — lean_goal is unavailable; you can read the file and check compilation output, but cannot see proof state at a specific line
  • No tactic testing — lean_multi_attempt is unavailable; edits must be validated by compiling the file (lake env lean)
  • No real-time diagnostics — lean_diagnostic_messages is unavailable; use lake env lean <file> (from project root) for compilation errors, but feedback is file-level, not line-level
  • Search is script-based — lean4-skills-smart-search replaces LSP search tools

This mode is functional for straightforward proofs but significantly slower and less precise than MCP-backed workflows.

review_only (read-only, no edits)

Read proof state and assess quality. No edits, no commits, no subagent dispatch.

File Handling Rules

Scratch-work ladder (in preference order):

  1. Live file + MCP tools (lean_goal, lean_multi_attempt, lean_diagnostic_messages)
  2. lean_run_code for isolated experiments
  3. /tmp scratch files only when lean_run_code is unavailable and the experiment must not touch the live file
  4. Never create scratch files in the repo root

File inspection: Use direct file-read and search tools for source files — for example Read/Grep when available, or line-range reads and rg in shell. Do not spin up Python scripts, temp files, or cat pipelines just to read accessible lines; reserve scripts for real parsing, transformation, or multi-file analysis that direct read/search tools cannot handle cleanly.

Staging: Stage only files touched during the current session. Never use git add -A or broad glob patterns. Print the exact staged set before committing.

See sorry-filling.md for the full scratch-work preference order.

Core Primitives

ScriptPurposeOutput
sorry_analyzer.pyFind sorries with contexttext (default), json, markdown, summary
check_axioms_inline.shBest-effort axiom scan (top-level declarations)text
smart_search.shMulti-source mathlib searchtext
find_golfable.pyDetect optimization patternsJSON
find_usages.shFind declaration usagestext

Usage: Invoked by commands automatically. See references/ for details.

Invocation contract. Preferred model-facing form:

  • Use lean4-skills-* wrappers for the supported helper scripts (lean4-skills-sorry-analyzer, lean4-skills-check-axioms-inline, lean4-skills-find-golfable, lean4-skills-find-exact-candidates, lean4-skills-analyze-let-usage, lean4-skills-find-usages, lean4-skills-search-mathlib, lean4-skills-smart-search, lean4-skills-cycle-tracker, lean4-skills-disprove-artifact-txn, lean4-skills-disprove-emit-artifact, lean4-skills-disprove-method-probe, lean4-skills-disprove-target-profile, lean4-skills-disprove-target-resolve, lean4-skills-file-baseline, lean4-skills-project-context, lean4-skills-checkpoint-mathlib-roots, lean4-skills-validate-review-output, lean4-skills-run-store, lean4-skills-run-persist). In a persistent environment these are bare commands on PATH. In a trusted native Codex plugin, prefix the wrapper name with the literal absolute bin_dir from SessionStart (for example /installed/plugin/bin/lean4-skills-sorry-analyzer). Do not use $LEAN4_SCRIPTS, ${LEAN4_PYTHON_BIN:-python3}, ~, or command substitution to locate a wrapped executable. Ordinary output capture around a wrapper is fine (e.g. txn=$(lean4-skills-disprove-artifact-txn begin)). Stable invocation surface that sandboxed hosts can statically allowlist.
  • Report-only calls: add --report-only to lean4-skills-sorry-analyzer, lean4-skills-check-axioms-inline (and unused_declarations.sh if invoked via env-var fallback) — suppresses exit 1 on findings; real errors still exit 1. Do not use in gate commands like /lean4:checkpoint.
  • Keep stderr visible for Lean script invocations (no /dev/null redirection). The guardrails detector recognizes both wrapper and env-var call forms; suppressing stderr is blocked either way.

Compatibility fallback (when a wrapper is unavailable):

  • Under trusted native Codex, use the literal absolute bin_dir path supplied by SessionStart; lack of a bare PATH entry is expected, not a failure.
  • For persistent-environment hosts, if lean4-skills-* is not resolvable on PATH, repair the documented $LEAN4_PLUGIN_ROOT/bin setup; see the repository's INSTALLATION.md.
  • Only as a last resort for an unwrapped script, use the explicit env-var form: bash "$LEAN4_SCRIPTS/script.sh" … or ${LEAN4_PYTHON_BIN:-python3} "$LEAN4_SCRIPTS/script.py" ….

If neither trusted Codex absolute paths nor $LEAN4_SCRIPTS are available, run the diagnose workflow (/lean4:diagnose where that command is installed); on a skill-only install follow the repository's INSTALLATION.md. Stay LSP-only until resolved.

Automation

/lean4:prove and /lean4:autoprove handle most tasks:

  • prove — guided, asks before each cycle. Ideal for interactive sessions.
  • autoprove — autonomous, loops with explicit stop budgets. Ideal for unattended runs.

Both share the same cycle engine (plan → work → checkpoint → review → replan → continue/stop) and follow the LSP-first protocol: LSP tools are normative for discovery and search; script fallback only when LSP is unavailable or exhausted. Compiler-guided repair is escalation-only — not the first response to build errors. For complex proofs, they may delegate to internal workflows for deep sorry-filling (with snapshot, rollback, and scope budgets), proof repair, or axiom elimination. You don't invoke these directly.

Skill-Only Behavior

When editing .lean files without invoking a command, the skill runs one bounded pass:

  • Read the goal or error via lean_goal/lean_diagnostic_messages

  • Search mathlib with up to 2 LSP tools (e.g. lean_local_search + lean_leanfinder/lean_leansearch/lean_loogle)

  • Try the Automation Tactics cascade

  • Validate with lean_diagnostic_messages (no project-gate lake build in this mode)

  • No looping, no deep escalation, no multi-cycle behavior, no commits

  • If one goal resists the pass, follow the Blocked-Goal Triage loop in references/sorry-filling.md before escalating

  • End with suggestions:

    Ask me to run the guided prove workflow for cycle-by-cycle help. Ask me to run the autonomous autoprove workflow for unattended cycles with stop safeguards.

    (On a host with the plugin's commands installed, those are /lean4:prove and /lean4:autoprove.)

Quality Gate

A proof is complete when:

  • lake build passes
  • Zero sorries in agreed scope
  • Only standard axioms (propext, Classical.choice, Quot.sound)
  • No statement changes without permission

Verification ladder: lean_diagnostic_messages(file) per-edit → lake env lean <path/to/File.lean> file gate (run from project root; checks against built imports only — after a cross-file edit use lake lean <path/to/File.lean>, see File Gate Scope) → lake build project gate only. See cycle-engine: Build Target Policy.

Common Fixes

See compilation-errors for error-by-error guidance (type mismatch, unknown identifier, failed to synthesize, timeout, etc.).

Type Class Patterns

-- Local instance for this proof block: plain `have`/`let` already register a
-- class-typed local for synthesis in Lean 4
have : MeasurableSpace Ω := inferInstance
let inst : Fintype α := ⟨...⟩   -- `let` when the VALUE must stay visible (data)

-- Scoped instances (affects current section)
open scoped Topology MeasureTheory

haveI / letI rule (Lean 4): have and let register local instances themselves; haveI/letI differ only by inlining the value into the term. In a tactic proof of a proposition that inlining can have no effect (proof irrelevance), so haveI/letI are never needed there — Mathlib's haveI/letI linter flags them. Reserve letI for definitions where the instance value must be inlined into data. Before adding any local instance, check whether synthesis already succeeds (many "provide the instance" idioms predate the corresponding Mathlib instance).

Order matters: provide outer structures before inner ones.

omit [Inst] in removes an unused section instance from the following declaration. Place it before the declaration docstring; putting it between the docstring and lemma/theorem makes Lean parse it as a separate omit command.

variable {α : Type*} [MeasurableSpace α]

omit [MeasurableSpace α] in
/-- doc -/
theorem foo : True := trivial

See domain-patterns for more.

Automation Tactics

Try in order (stop on first success): rfl → simp → ring → linarith → nlinarith → omega → exact? → apply? → grind → aesop

Note: exact?/apply? query mathlib (slow). grind and aesop are powerful but may timeout. See grind-tactic for interactive workflows, annotation strategy, and simproc escalation.

Troubleshooting

If LSP tools aren't responding, check your operating profile above. In scripts_only mode, the resolved helper runtime provides search and lake env lean provides file-level compilation feedback, but live goal inspection, tactic testing, and line-level diagnostics are unavailable. If no helper runtime path is available, run the diagnose workflow to diagnose it.

Script environment check:

# Trusted native Codex: use the absolute path from SessionStart.
/absolute/plugin/root/bin/lean4-skills-preflight --codex
# Persistent environment:
echo "$LEAN4_SCRIPTS"
command -v lean4-skills-sorry-analyzer
# One-pass discovery for troubleshooting (human-readable default text):
lean4-skills-sorry-analyzer . --report-only
# Structured output (optional): --format=json
# Counts only (optional): --format=summary

Cold start / fresh worktree:

  • Fresh worktree or after lake clean? Prime the cache in that worktree before the first real build.
  • Use the project's cache command: lake cache get on newer Lake, or lake exe cache get where the project still uses the mathlib cache executable.
  • If Lean LSP is cold or timing out on first use, run one lake build to bootstrap the workspace.
  • After bootstrap, return to the normal verification ladder: lean_diagnostic_messages(file) → lake env lean <path/to/File.lean> (from project root; built imports only, see File Gate Scope) → lake build only at checkpoint/final gate.
  • Do not symlink another worktree's .lake/build; use Lake cache/artifact mechanisms instead.

References

Cycle Engine: cycle-engine — shared prove/autoprove logic (stuck, deep mode, falsification, safety)

Handoff Contract: handoff-contract — run-contract/v1 dispatch + handoff records and the rerun guard (don't relaunch the same mode on the same blocker_signature without new evidence; route to review --mode=stuck, formalize, or human handoff)

Run Store: run-store — run-store/v1, the storage primitive for those records (lean4-skills-run-store: immutable manifest, append-only journal, disposable handoff cache; historical evidence, never certification). prove/autoprove --persist write runs through lean4-skills-run-persist per cycle-engine § Run Persistence (#82B); prior-run reuse: --prior-run (#82C) per cycle-engine § Prior-Run Reuse; resume/inspect remain open under #82.

LSP Tools: lean-lsp-server (quick start), lean-lsp-tools-api (full API — grep ^## for tool names)

Search: mathlib-guide (read when searching for existing lemmas), lean-phrasebook (math→Lean translations)

Review: mathlib-review-taxonomy (what mathlib reviewers ask for — the nine review buckets)

Errors: compilation-errors (read first for any build error), instance-pollution (typeclass conflicts — grep ## Sub- for patterns), compiler-guided-repair (escalation-only repair — not first-pass)

Tactics: tactics-reference (tactic lookup — grep ^### TacticName), grind-tactic (SMT-style automation — when simp can't close), simp-reference (mechanism choice, simp normal forms, @[simp] hygiene, simproc authoring), tactic-patterns, calc-patterns

Proof Development: proof-templates, proof-refactoring (28K — grep by topic), proof-simplification (strategy-level: mathlib search, congr lemmas, helper extraction), sorry-filling

Optimization: proof-golfing (includes safety rules, bounded LSP lemma replacement, bulk rewrites, anti-patterns; escalates to axiom-eliminator), proof-golfing-patterns, performance-optimization (grep by symptom), profiling-workflows (diagnose slow builds/proofs)

Domain: domain-patterns (25K — grep ## Area), measure-theory (28K), axiom-elimination

Style: mathlib-style, verso-docs (Verso doc comment roles and fixups)

Custom Syntax: lean4-custom-syntax (read when building notations, macros, elaborators, or DSLs), metaprogramming-patterns (MetaM/TacticM API — composable blocks, elaborators), scaffold-dsl (copy-paste DSL template), json-patterns (json% syntax + ToJson)

Quality: linter-authoring (project-specific linter rules), ffi-interop (FFI, @&, init, symbol linkage)

Workflows: agent-workflows, subagent-workflows, command-examples, learn-pathways (intent taxonomy, game tracks, source handling)

Internals: review-hook-schema, compiler-internals (attributes, specialization, pipeline)

Commands 12

Lean4 Autoformalize

Autonomous end-to-end formalization: extracts claims from a source, drafts Lean skeletons, and proves them — all unattended. Combines /lean4:draft and /lean4:autoprove in a single command.

Usage

/lean4:autoformalize --source ./paper.pdf --claim-select=first --out=Paper.lean
/lean4:autoformalize --source ./paper.pdf --claim-select=regex:"Theorem.*" --out=Paper.lean --rigor=checked
/lean4:autoformalize --source ./notes.md --claim-select=named:"Main Lemma" --out=Lemma.lean

Invocation Contract

Interpret this command's inputs per the Command Invocation Contract.

Primary path (hook-validated): If a validated-invocation block for this command appears in context, treat it as the authoritative interpretation of parser-decidable inputs and do not re-parse the raw invocation text for those inputs. Start by reading all parser-decided fields from the block. Emit the final Resolved Inputs summary from the block values. See Validated Invocation Block.

Fallback path (other hosts): If no validated-invocation block is present, parse the raw invocation text against this command's input table before extracting claims or drafting anything.

Startup requirements:

  1. Emit a Resolved Inputs block with explicit values, defaults, coercions, ignored flags, and startup validation errors.
  2. Refuse to start on startup validation errors.
  3. Call lean4-skills-cycle-tracker init with resolved numeric values for --max-cycles, --max-stuck-cycles, --max-total-runtime, and --max-deep-per-cycle. A failed init (exit 2) is a startup validation error — do not proceed.
  4. The state file is the single source of truth for session counters. Read counters from tick/status output, not from conversational memory.
  5. Per-claim lifecycle: --max-cycles and --max-stuck-cycles are per-claim; --max-total-runtime is per-session. Before each claim, call start-claim. After each claim completes or stops (before the next), call reset-claim. The final claim does not need reset-claim — totals are accumulated live. See Claim Boundary Protocol.

Inputs

ArgRequiredDefaultDescription
--sourceyes—File path, URL, or PDF for claim extraction.
--claim-selectyes—first | named:"..." | regex:"...". Queue-extraction filter applied once at startup.
--outyes—Target file for formalized claims.
--statement-policynorewrite-generated-onlypreserve | rewrite-generated-only | adjacent-drafts.
--rigornosketchsketch | checked. Rigor for drafted skeletons.
--draft-modenoskeletonskeleton | attempt. Passed to draft phase.
--draft-elab-checknobest-effortbest-effort | strict. Passed to draft phase.
--max-cyclesno20Session stop budget: max total cycles per claim
--max-total-runtimeno120mBest-effort wall-clock session budget
--max-stuck-cyclesno3Session stop budget: max consecutive stuck cycles per claim
--deepnostucknever, stuck, or always
--deep-sorry-budgetno2Max sorries per deep invocation
--deep-time-budgetno20mAdvisory: scopes deep-mode subagent work. Not tracked or enforced by session tracker.
--max-deep-per-cycleno1Max deep invocations per cycle
--deep-snapshotnostashV1: stash only
--deep-rollbacknoon-regressionon-regression | on-no-improvement | always | never
--deep-scopenotargettarget | cross-file
--deep-max-filesno2Max files per deep invocation
--deep-max-linesno200Max added+deleted lines per deep invocation
--deep-regression-gatenostrictstrict | off
--commitnoautoauto | never
--golfnoneverprompt | auto | never
--review-sourcenointernalinternal | none (coerced from external/both — see autoprove)
--review-everynocheckpointN (sorries) | checkpoint | never

Flag validation

  • --source is required; error if missing.
  • --claim-select is required; error if missing (no unattended guessing).
  • --out is required when no existing target file is in scope; error if missing.
  • --statement-policy=preserve is respected but warns: stuck redraft path becomes manual intervention, not automatic rewrite.

Actions

The synthesis outer loop is the single source of truth for the algorithm. See cycle-engine.md for the full algorithm, provenance tracking, claim queue, and file assembly contract.

Summary:

  1. Extract claim queue from --source (filtered by --claim-select) at startup
  2. For each claim: draft skeleton → run inner 6-phase prove cycle → on stuck, consult review router
  3. On next_action=redraft: re-draft (check provenance + statement-policy); commit if allowed
  4. Advance to next claim when sorry-free or stop rule fires

Stop Conditions

Autoformalize checks stop budgets at cycle boundaries via lean4-skills-cycle-tracker tick --stuck=yes|no. Limits are checked at cycle boundaries only — a long-running tool call within a cycle will not be interrupted.

Autoformalize stops when the first of these is satisfied:

  1. Queue empty — all claims attempted (expected completion)
  2. Max stuck cycles — --max-stuck-cycles consecutive stuck cycles on current claim. Session-enforced via lean4-skills-cycle-tracker.
  3. Max cycles — --max-cycles total cycles reached on current claim. Session-enforced via lean4-skills-cycle-tracker.
  4. Max runtime — best-effort wall-clock budget reached (--max-total-runtime). Checked at cycle boundaries and deep preflight.
  5. Manual user stop — user interrupts

See Session Tracking for the cycle boundary protocol and enforcement levels.

Structured Summary on Stop

When autoformalize stops, emit:

## Autoformalize Summary

**Reason stopped:** [queue-empty | max-stuck | max-cycles | max-runtime | user-stop]

| Metric | Value | Source |
|--------|-------|--------|
| Claims attempted | N/M | `claims_attempted` from `status` (includes in-progress claim) |
| Sorries before | 0 | |
| Sorries after | S | |
| Cycles run | C | `cycles_total` from `status` (session total across all claims) |
| Stuck cycles | K | `stuck_cycles_total` from `status` (session total) |
| Deep invocations | D | `deep_total` from `status` (session total) |
| Time elapsed | T | `elapsed_display` from `status` |
| Drafts | F (R redrafted) | |

**Handoff recommendations:**
- [If incomplete: "Run /lean4:formalize for guided work on remaining claims"]
- [If stuck: "Review stuck blockers: file:line, file:line"]
- [If clean: "All sorries filled. Run /lean4:checkpoint to save."]
- [If claims remaining: "N claims remaining in queue. Re-run with same --source and --out to continue."]

Safety

  • Autonomous operation. Never blocks waiting for interactive input.
  • Guardrailed git commands are blocked. See cycle-engine.md for the full list.
  • Header fence. Proof engines (inner cycle) never modify declaration headers. Statement changes are handled by the synthesis outer loop's redraft path, not by deep mode.
  • All guardrails.sh rules apply.
  • Line width. Follow mathlib 100-char line width — do not wrap lines at 80 when they fit within 100.
  • Docstring policy — Rule C (new-file / new-decl generation). Session-generated files and declarations may carry module/declaration docstrings from creation; pre-existing declarations retain Rule A (no silent docstring rewrites). Newly created module docstrings must respect the applicable project template. If the generated file uses the mathlib header, they fill the mathlib-style.md § 1 module-docstring slot; Rule C neither selects nor redefines that header.

See Also

  • /lean4:draft — Skeleton-only drafting (standalone)
  • /lean4:formalize — Interactive synthesis (human-in-the-loop)
  • /lean4:autoprove — Autonomous proving (no drafting)
  • /lean4:disprove — Guided counterexample search with certified refutation (alternative path when a claim is suspected false)
  • Cycle Engine — Synthesis Outer Loop
  • Examples

Lean4 Autoprove

Autonomous multi-cycle theorem proving. Runs cycles automatically with explicit stop budgets and structured summaries.

Usage

/lean4:autoprove                        # Start autonomous session
/lean4:autoprove File.lean              # Focus on specific file
/lean4:autoprove --repair-only          # Fix build errors without filling sorries
/lean4:autoprove --max-cycles=10        # Limit total cycles

Invocation Contract

Interpret this command's inputs per the Command Invocation Contract.

Primary path (hook-validated): If a validated-invocation block for this command appears in context, treat it as the authoritative interpretation of parser-decidable inputs and do not re-parse the raw invocation text for those inputs. Start by reading all parser-decided fields from the block. Emit the final Resolved Inputs summary from the block values. See Validated Invocation Block.

Fallback path (other hosts): If no validated-invocation block is present, parse the raw invocation text against this command's input table before Phase 1.

Startup requirements:

  1. Emit a Resolved Inputs block with explicit values, defaults, coercions, ignored flags, and startup validation errors.
  2. Refuse to start on startup validation errors.
  3. Call lean4-skills-cycle-tracker init with resolved numeric values for --max-cycles, --max-stuck-cycles, --max-total-runtime, --max-deep-per-cycle, --max-consecutive-deep-cycles, and --conclude-after (--conclude-after=0 with --formalize=auto). A failed init (exit 2) is a startup validation error — do not proceed.
  4. The state file is the single source of truth for session counters. Read counters from tick/status output, not from conversational memory.
  5. With --persist: after the tracker is initialized and a valid first dispatch (with its file_baseline) exists, set LEAN4_RUN_PERSIST_STATE to a fresh invocation-private path (mktemp -d + a not-yet-existing file) and run lean4-skills-run-persist start before any proof edit; a startup-error is a startup validation error. Report the run_id in Resolved Inputs and follow Run Persistence at every review, cycle boundary, and stop; for each inline edit: check → edit → advance (changed entries only) → run-persist progress --payload (parent knowledge, no citation; fallbacks reflect reported knowledge only). With --prior-run, first run run-persist reuse; on drift or an uncovered file stop before any edit and before custody with an operational-error handoff naming what needs reconciliation (never accept drift automatically); otherwise run-persist custody, then start with --reuse-report (Prior-Run Reuse).

Inputs

ArgRequiredDefaultDescription
scopeNoallSpecific file or theorem to focus on
--repair-onlyNofalseFix build errors only, skip sorry-filling
--planningNoonon or off
--review-sourceNointernalinternal, external, both, or none (see coercion below)
--review-everyNocheckpointN (sorries), checkpoint, or never
--checkpointNotrueCreate checkpoint commits after each cycle
--deepNostucknever, stuck, or always (ask coerced to stuck — see Deep Mode)
--deep-sorry-budgetNo2Max sorries per deep invocation
--deep-time-budgetNo20mAdvisory: scopes deep-mode subagent work. Not tracked or enforced by session tracker.
--max-deep-per-cycleNo1Max deep invocations per cycle
--max-consecutive-deep-cyclesNo2Hard cap on consecutive cycles using deep mode
--deep-snapshotNostashV1: stash only
--deep-rollbackNoon-regressionon-regression, on-no-improvement, always, or never (see coercion below)
--deep-scopeNotargettarget or cross-file
--deep-max-filesNo2Max files per deep invocation
--deep-max-linesNo200Max added+deleted lines per deep invocation
--deep-regression-gateNostrictstrict or off (see coercion below)
--batch-sizeNo2Sorries to attempt per cycle (advisory)
--commitNoautoauto or never (ask coerced to auto — see note below)
--golfNoneverprompt, auto, or never
--persistNofalseWrite this run to the run store (dispatches, handoffs, notes, reviews, Replan summaries; one run per invocation). Off by default — existing invocations are unchanged. Platform support is a startup capability check. See cycle-engine: Run Persistence.
--run-storeNo—Storage root override; requires --persist (--run-store without --persist → startup validation error). Precedence: --run-store → $LEAN4_RUN_STORE → <project-root>/.lean4-skills.
--prior-runNo—Reuse a selected prior run's history (explicit id; never "latest"; resolved within the selected store); requires --persist (--prior-run without --persist → startup validation error). See cycle-engine: Prior-Run Reuse.
--max-cyclesNo20Session stop budget: max total cycles
--max-total-runtimeNo120mBest-effort wall-clock session budget
--max-stuck-cyclesNo3Session stop budget: max consecutive stuck cycles
--conclude-afterNo15%Reserve the end of the budget for a conclusion: N% (0–50, of every limited budget), Nc (total cycles only), a duration such as 5m (runtime only), or 0 (off). Startup validation error when the reserve is larger than its budget (3c with --max-cycles=3), for a duration with unlimited runtime, and for 0c and 0s (use 0). With --formalize=auto the conclusion phase is off (per-claim budgets).
--formalizeNonevernever | restage | auto. See Formalize Outer Loop. (deprecated: use /lean4:autoformalize)
--sourceNo—File path, URL, or PDF for claim extraction. Required when --formalize=auto. (deprecated: use /lean4:autoformalize)
--claim-selectNo—first | named:"..." | regex:"...". Queue-extraction filter applied once at startup. Required when --formalize=auto. Ignored without --source. (deprecated: use /lean4:autoformalize)
--formalize-rigorNosketchsketch | checked. Rigor for formalize skeleton. (deprecated: use /lean4:autoformalize --rigor)
--statement-policyNopreservepreserve | rewrite-generated-only | adjacent-drafts. Default becomes rewrite-generated-only when --formalize=restage|auto (see flag validation). (deprecated: use /lean4:autoformalize)
--formalize-outNo—Target file for formalized claims. Required if no existing target in scope. (deprecated: use /lean4:autoformalize --out)

Review Source Coercion

Autoprove accepts all --review-source values for flag compatibility with /lean4:prove. However, autoprove never blocks waiting for interactive input. If the value is external or both, autoprove coerces to internal at startup and emits:

⚠ --review-source=external requires interactive handoff. Using internal review for unattended operation.

Future autonomous external review: External review is currently manual-handoff only. Future versions may support autonomous external review via non-interactive CLI execution (e.g., codex exec) behind an explicit opt-in flag (--external-autonomous). Until then, unattended autoprove runs default to internal review.

Requirements for autonomous external review:

  1. Stable JSON input/output contract
  2. Timeout + retry + cost budgets
  3. Safe fallback to internal review on external failure
  4. Explicit opt-in flag, not default behavior

Formalize Flag Validation

  • --formalize=auto requires --source; error if missing.
  • --formalize=auto with --source requires --claim-select; error if missing (no unattended guessing).
  • --formalize=auto requires --formalize-out when no existing target file is in scope; error if missing.
  • --formalize=restage does NOT require --source — operates on existing scope with restage enabled on stuck. --source is ignored if provided (warn).
  • --formalize=never ignores --source (warn if provided).
  • --formalize=restage|auto with default --statement-policy coerces preserve → rewrite-generated-only at startup (warn). Explicit --statement-policy=preserve is respected but warns: stuck restage becomes manual intervention, not automatic rewrite.
  • --claim-select is a queue-extraction filter applied once at startup. Internal draft calls receive individual popped claims, not the full --source.
  • --claim-select without --source is ignored (no effect).

Startup Behavior

No questionnaire. Discover state and start immediately.

  1. Discover state (LSP-first is normative, see cycle-engine.md):
    • lean_diagnostic_messages(file) for errors/warnings
    • lean_goal(file, line) at each sorry
    • Up to 3 LSP search tools (~30s); record top candidates per sorry
  2. If --planning=on (default): run planning phase — list sorries with candidates, set order, then start
  3. If --planning=off: skip planning, start immediately. Stuck-triggered replan is still mandatory (see Stuck Definition).

Actions

Each cycle has 6 phases — see cycle-engine.md for shared mechanics.

Phase 1: Plan

See cycle-engine: LSP-First Protocol. Discover sorries via LSP, search with up to 3 tools (~30s), identify sorries, set order.

Phase 2: Work (Per Sorry)

See sorry-filling.md and cycle-engine: LSP-First Protocol.

  1. Refresh goal → search → generate 2-3 candidates → test via lean_multi_attempt
  2. Preflight falsification for decidable/finite goals (30-60s max)
  3. Tactic cascade if no candidate passed
  4. Validate via lean_diagnostic_messages; if "Try this" suggestion appears, resolve with lean_code_actions, then re-run lean_diagnostic_messages to confirm clean
  5. Stage & commit

Staging rule: If --commit=never, skip staging and committing entirely. Otherwise, stage only the files touched by this fill (git add <edited files>) — never git add -A or broad patterns. Commit: git commit -m "fill: [theorem] - [tactic]".

Touched-file reporting: At session end, report files_touched (files edited) and scratch_files_created (any /tmp files used for experiments).

Commit behavior (unique to autoprove): Default --commit=auto — commits without prompting. --commit=ask is coerced to auto at startup:

⚠ --commit=ask requires interactive confirmation. Using auto for unattended operation.

Autoprove never blocks waiting for interactive input.

Constraints: Max 3 candidates per sorry, ≤80 lines diff, NO statement changes (inner cycle; see Formalize Outer Loop for --formalize modes), NO cross-file refactoring (fast path).

Phase 3: Checkpoint

See cycle-engine: Checkpoint Logic. Stage only files from successful work; exclude rolled-back deep invocations.

Phase 4: Review

See cycle-engine: Review Phase. Runs at configured --review-every intervals.

Phase 5: Replan

See cycle-engine: Replan Phase.

Phase 6: Continue / Stop

Autonomous loop: Auto-runs cycles without per-cycle user prompts. Checkpoint + review + replan at each cycle boundary ("come up for air").

Formalize Outer Loop (Deprecated)

Deprecated: Prefer /lean4:autoformalize for new workflows. These flags remain functional for compatibility.

When --formalize is not never, autoprove wraps the inner 6-phase cycle with draft-driven statement acquisition (source-backed for auto, scope-backed for restage) and review-driven routing.

ModeBehavior
never (default)No outer loop. Identical to pre-change behavior.
restageNo claim queue. Run inner cycle on existing scope; on stuck, re-draft if next_action=redraft (subject to --statement-policy).
autoFull loop: extract claims from --source, draft each, prove, restage on stuck (subject to --statement-policy).

The inner 6-phase cycle is unchanged. The outer loop reads the stuck-mode next_action field from review as its routing gate. See cycle-engine.md for the full algorithm, provenance tracking, claim queue, and file assembly contract.

Stop Conditions

Autoprove checks stop budgets at cycle boundaries via lean4-skills-cycle-tracker tick --stuck=yes|no. Limits are checked at cycle boundaries only — a long-running tool call within a cycle will not be interrupted.

Autoprove stops when the first of these is satisfied:

  1. Completion — all sorries in scope are filled
  2. Max stuck cycles — --max-stuck-cycles consecutive stuck cycles (default: 3). Session-enforced via lean4-skills-cycle-tracker.
  3. Max cycles — --max-cycles total cycles reached (default: 20). Session-enforced via lean4-skills-cycle-tracker.
  4. Max runtime — best-effort wall-clock budget reached (--max-total-runtime, default: 120m). Checked at cycle boundaries and deep preflight.
  5. Concluded — the conclusion phase finished before any limit bound (see below)
  6. Manual user stop — user interrupts
  7. Queue empty — all claims attempted; expected completion for --formalize=auto sessions

See Session Tracking for the cycle boundary protocol and enforcement levels.

Conclusion Phase

When a tick reports conclude=yes (the --conclude-after reserve of a limited budget is reached, no limit binds), call lean4-skills-cycle-tracker conclude and spend the next cycle concluding: apply an already-tested candidate when exactly one sorry remains and the candidate still applies (finalization, verified per File Gate Scope — never a fresh deep search, and never under --repair-only, which synthesizes without filling sorries), otherwise synthesize a verdict — ready (only via finalization), fixable, or no-credible-path — with the best partial patch, the blocker inventory, missing lemmas, unexplored queries and the recommended next command. That cycle ends with the final Replan and one real tick (--stuck=no only if a sorry was filled). Then map: a successful finalization → completion, whatever the tick says; a limit reached on that tick → the tracker's stop_reason; otherwise concluded. A completed or user-stopped run never enters the phase, and --conclude-after=0 keeps today's behaviour. The runtime reserve is best-effort: before each expensive step read cycle-tracker status, and on runtime_exhausted=yes report what exists without starting another proof attempt. Full rules: cycle-engine: Conclusion Phase.

Structured Summary on Stop

When autoprove stops (for any reason), emit:

## Autoprove Summary

**Reason stopped:** [completion | max-stuck | max-cycles | max-runtime | concluded | user-stop | queue-empty]

**Conclusion:** [ready | fixable | no-credible-path | not reached: <what was produced> | none (phase not entered)]

| Metric | Value |
|--------|-------|
| Sorries before | N |
| Sorries after | M |
| Cycles run | C |
| Stuck cycles | S |
| Deep invocations | D |
| Time elapsed | T |
| Formalizations | F |
| Conclusion cost (if entered) | cycles / stuck cycles / deep / time since `conclude_at` |
| Run (with `--persist`) | `<run_id>` — `stored` / `not stored: <detail>` (after `LEAN4_RUN_PERSIST_STATE` was set to a fresh invocation-private path and `run-persist start` ran before any proof edit) |

**Handoff recommendations:**
- [If incomplete: "Run /lean4:prove for guided work on remaining N sorries"]
- [If stuck: "Review stuck blockers: file:line, file:line"]
- [If clean: "All sorries filled. Run /lean4:checkpoint to save."]
- [If claims remaining: "N claims remaining in queue. Re-run with same --source and --formalize-out to continue (existing claims detected via target file)."]

After the human-readable summary above, emit the complete run-contract/v1 handoff record — every required field, not just the ones in the Markdown table. With --persist this is the record passed to lean4-skills-run-persist finish. Report per its result: stored: true → stored, with the confirmed citation and any cache warning; stored: false, persistence: not-stored → print fallback_handoff here in full, "not saved", no citation; stored: false, persistence: unconfirmed → print it in full, "persistence is unconfirmed", no citation — never "not saved", never "stored". Citations of stored items use <run_id>#<seq> only (Run Persistence). Command-specific mapping: completion → status: solved; max-stuck → status: stopped, stop_reason: max-stuck (blocker-driven, so the blocker fields are non-null); max-cycles / max-runtime / user-stop / queue-empty / concluded → status: stopped with that stop_reason and null blocker fields (a queue-empty stop with claims remaining reruns freely, as does a concluded one — its recommendations are in the final Replan, never in new_evidence_required_for_rerun). A successful finalization in the conclusion phase is completion → status: solved, even on the last available cycle. Before relaunching, obey the rerun guard.

Deep Mode

Bounded subroutine for stubborn sorries. Default: stuck (auto-escalate when stuck).

Modes: never | stuck (default, auto on stuck) | always (auto on any failure). Note: ask is coerced to stuck (no interactive prompting in autoprove).

Statement changes are NOT permitted. Declaration headers are immutable (header fence). If deep concludes the statement is wrong, emit next_action = redraft, auto-revert any header changes, and mark stuck. When --formalize is active, statement work is handled by the outer loop's redraft path, not by deep mode.

Safety: Deep creates a path-scoped pre-deep snapshot, enforces scope/diff budgets, and auto-rolls back on regression. Rollback marks the sorry as stuck with reason.

Deep safety coercions (validated and applied at startup with warnings):

  • --deep-rollback=never → coerced to on-regression
  • --deep-regression-gate=off → coerced to strict

When dispatching sorry-filler-deep, include pre-collected MCP context per cycle-engine.md § Pre-flight Context.

See cycle-engine.md for full semantics, definitions, and prove/autoprove comparison.

Header Fence

Declaration headers (everything from theorem/def/lemma through := by) are snapshotted at deep entry. At each checkpoint, the engine compares headers against the snapshot. Any header change triggers immediate rollback and marks the sorry as stuck with "deep: header fence — declaration header modified".

Stuck Definition

A sorry is stuck when: same failure 2-3x, same build error 2x, no progress 10+ min, or empty LSP search 2x.

When stuck: auto-review → planner mode → revised plan → next cycle executes plan. On falsification flag: auto counterexample/salvage pass. Handoff must include LSP queries attempted, top candidates, and lean_multi_attempt outcomes.

See cycle-engine.md for full detection logic and blocker signature computation.

Falsification Artifacts

When a statement is disproved, create T_counterexample and T_salvaged lemmas. Avoid proving ¬ P if original sorry exists.

See cycle-engine.md for Lean code templates.

Repair Mode

Compiler-guided repair is escalation-only — not the default response to a first failure. Auto-invoke only when compiler errors are the active blocker: same blocker 2x, same build error 2x, or 3+ errors in scope. Apply direct fixes first. Budgets: max 2 per error signature, max 8 total per cycle. No improvement after 2 attempts → stuck + review + replan. Interactive repair options are coerced to autonomous (auto-select next strategy).

When dispatching proof-repair, include pre-collected MCP context per cycle-engine.md § Pre-flight Context.

See cycle-engine.md for full policy and compilation-errors.md for error-specific fixes.

Safety

Guardrailed git commands are blocked. See cycle-engine.md for the full list.

  • Line width. Follow mathlib 100-char line width — do not wrap lines at 80 when they fit within 100.

See Also

  • /lean4:autoformalize - Autonomous end-to-end formalization (preferred over --formalize flags)
  • /lean4:draft - Draft Lean declaration skeletons
  • /lean4:formalize - Interactive formalization (drafting + guided proving)
  • /lean4:prove - Guided cycle-by-cycle proving
  • /lean4:disprove - Guided counterexample search with certified refutation
  • /lean4:checkpoint - Manual save point
  • /lean4:review - Quality check (read-only)
  • /lean4:refactor - Strategy-level proof simplification
  • /lean4:golf - Optimize proofs
  • Cycle Engine - Shared prove/autoprove mechanics
  • Examples

Lean4 Checkpoint

Creates a checkpoint with per-file and project-wide build verification, axiom check, and commit.

Usage

/lean4:checkpoint
/lean4:checkpoint "optional custom message"
/lean4:checkpoint --mathlib-mk-all      # force the mk_all root-file gate
/lean4:checkpoint --no-mathlib-mk-all   # skip the mk_all root-file gate

Invocation Contract

Interpret this command's inputs per the Command Invocation Contract.

Primary path (hook-validated): If a validated-invocation block for this command appears in context, treat it as the authoritative interpretation of parser-decidable inputs and do not re-parse the raw invocation text for those inputs. Start by reading all parser-decided fields from the block. Emit the final Resolved Inputs summary from the block values. See Validated Invocation Block.

Fallback path (other hosts): If no validated-invocation block is present, parse the raw invocation text against this command's input table before acting.

Startup requirements:

  1. Emit a Resolved Inputs block with explicit values, defaults, ignored flags, and startup validation errors — including the effective mk_all-gate decision and its source (flag, the helper's intent.source, or helper-failure).
  2. Refuse to start on startup validation errors (e.g. both --mathlib-mk-all and --no-mathlib-mk-all).

Inputs

ArgRequiredDescription
messageNoCustom commit message suffix
--mathlib-mk-allNoForce the Generated Root Files gate on, overriding project-context detection. Mutually exclusive with --no-mathlib-mk-all.
--no-mathlib-mk-allNoForce the Generated Root Files gate off, overriding project-context detection. Mutually exclusive with --mathlib-mk-all.

Actions

  1. Verify Touched Files - For each existing added/modified .lean file in the candidate set for this checkpoint — the files touched during this session that the Stage and Commit step will stage, determined independently of the current git index (staging happens later) — compile individually:
    lake env lean <path/to/File.lean>   # from project root
    
    If any file fails, stop and report the error before proceeding.
  2. Generated Root Files gate (mathlib) - See Generated Root Files below. Runs before the project build; skips entirely unless the gate fires.
  3. Verify Build - Run lake build for the project-wide gate (catches cross-file issues not visible in per-file compilation)
  4. Best-effort Axiom Scan - Scan for non-standard axioms in top-level declarations:
    lean4-skills-check-axioms-inline .
    
    Note: checks top-level unindented declarations across all namespaces in each file (nested, sibling, and dotted namespaces are tracked correctly; sections are handled without leaking into the qualified name). Recognizes theorem|lemma|def|instance|abbrev|example|structure|class|inductive|axiom|constant, optionally prefixed by noncomputable, unsafe, partial, or nonrec. Indented declarations and unicode-identifier decls are not matched — files whose decls all fall in those classes are surfaced as UNVERIFIED (exit 1, not a silent pass). The script temporarily edits files in place while running — only use on version-controlled files, and avoid concurrent editors or watchers.
  5. Count Sorries - Report current sorry count:
    lean4-skills-sorry-analyzer . --format=summary
    
  6. Stage and Commit - Stage only files touched during this session, then commit:
    git add <files touched during this session>
    git diff --cached --name-only   # print exact staged set
    git commit -m "checkpoint(lean4): [summary]"
    
    Never use git add -A or broad glob patterns.
  7. Report Status - Show what was saved

Generated Root Files gate

Mathlib's generated root-import aggregators (Mathlib.lean, Mathlib/Tactic.lean, …) go stale when a .lean file is added, renamed, or deleted, and mathlib CI runs lake exe mk_all --check as a dedicated gate. This step catches that follow-up before the main build — but only when the current work is plausibly aimed at upstream mathlib contribution, so a personal mathlib fork used for experimentation is not blocked on every checkpoint.

1. Resolve whether the gate fires and acquire the project root (a flag resolving to true wins the intent decision; explicit false behaves like omission):

  • --no-mathlib-mk-all true → gate skipped; done. No helper is consulted and no root is needed.
  • Otherwise run lean4-skills-project-context --from "$PWD" to acquire and validate the project root, and validate the full record exactly as /lean4:draft does: schema = project-context/v1, intent.contributing_upstream a string in yes | no | unknown, intent.source a string in its domain — any missing/non-string/out-of-domain value is malformed helper output. Take $project_root from the record's non-null top-level root. Then:
    • --mathlib-mk-all true → gate fires. The flag overrides only the intent decision, not root discovery: if project-context fails, is malformed, or returns a null root, stop (explicit opt-in must not fail open) — do not skip and do not proceed to the build.
    • no flag → use intent.contributing_upstream: yes → gate fires; no, unknown, or a malformed/failed helper (including a null root) → gate skipped. Inferred intent may fail open (skip).

mk_all_declared is never consulted; availability is decided by actually running the command.

2. Detect root-affecting candidate changes. The candidate set is the session-touched files the Stage and Commit step will stage — not unrelated local work. Pass them NUL-delimited to the helper, anchored at the $project_root acquired above:

printf '%s\0' "${candidate_paths[@]}" \
  | lean4-skills-checkpoint-mathlib-roots --root "$project_root"

It emits a checkpoint-mathlib-roots/v1 JSON record listing added/deleted .lean files under <root>/Mathlib/ (renames surface as delete + add). Exit 0 = valid (including no changes); 2 = usage; 4 = git/operational failure.

Fail closed on any unusable result. Because the gate has already fired, validate the candidate-helper output before trusting it — do not treat an empty changes list as "clean" unless the result is well-formed. Any of the following is a stop (report that activation could not be determined; do not skip, do not proceed to the build): a nonzero exit (2 or 4), non-JSON output, schema ≠ checkpoint-mathlib-roots/v1, a root that does not match the $project_root passed in, or a missing/ill-typed changes field. Only a well-formed exit-0 record with an empty changes list means "no root-affecting changes → proceed to Verify Build".

3. Run the check. When changes is non-empty, run lake exe mk_all --check from $project_root and preserve its output verbatim:

  • Output explicitly names outdated files → stop before Verify Build; report those lines as-is and print the remediation lake exe mk_all (the same string diagnose §16 surfaces). Never auto-rewrite root files.
  • Any other nonzero (executable unavailable, Lake error) → preserve the output, state the gate could not complete, stop before Verify Build, and do not invent stale filenames.
  • Exit 0 → roots are current; proceed.

Global-check limitation (honest scope note). The candidate set controls only whether the gate activates; once activated, lake exe mk_all --check inspects the actual checkout, so unrelated local changes can affect its result. This does not violate "unrelated work must not trigger the gate" — activation is candidate-scoped — but candidate-level isolation would require a clean-worktree/stash mechanism, which is out of scope for v1.

Output

## Checkpoint Created

**Commit:** [hash] - [message]
**Touched files compiled:** ✓ [N] files
**Project build:** ✓ passing
**Sorries:** [N] remaining
**Axioms:** [status]

**Next steps:**
- Continue with `/lean4:prove`
- Push manually when ready: `git push`

Safety

  • Does NOT push to remote (manual only)
  • Does NOT create PRs (manual only)
  • Does NOT amend commits (each checkpoint = new commit)
  • Will NOT create checkpoint if build fails

Rollback

git reset --soft HEAD~1   # Undo last, keep staged
git reset HEAD~1          # Undo last, keep unstaged
git reset HEAD~N          # Undo last N commits

Warning: Only use reset before pushing.

See Also

  • /lean4:prove - Guided cycle-by-cycle proving
  • /lean4:review - Read-only code review
  • /lean4:refactor - Strategy-level proof simplification
  • Examples

Lean4 Diagnostics

Diagnostics, troubleshooting, and migration assistance for the Lean4 plugin.

Usage

/lean4:diagnose                    # Full diagnostic (plugin + workspace)
/lean4:diagnose env                # Environment only
/lean4:diagnose migrate            # Detect legacy installs (read-only)
/lean4:diagnose migrate --global   # Include user-level ~/.claude scan
/lean4:diagnose cleanup            # Show stale files + removal commands
/lean4:diagnose cleanup --apply    # Actually remove stale files
/lean4:diagnose <pasted error>     # Error triage: match against known patterns

Inputs

ArgRequiredDescription
modeNoenv, migrate, cleanup, or full (default)
--globalNoInclude user-level paths (~/); migrate only
--applyNoExecute removals; cleanup only
error textNoPositional text whose first token is not a recognized mode is treated as pasted diagnostic text for error triage

Dispatch is decided by the first positional token only:

  • a recognized mode (env, migrate, cleanup) or no positional token → existing mode behavior (default full diagnostic when absent);
  • otherwise → treat the positional text as pasted diagnostic input for error triage.

Mode-specific flags (--global, --apply) remain flags in every case — they are never treated as error text.

Error triage precedence: pasted text is matched against the specific patterns in compilation-errors.md (Quick Reference Table first), including the module-system patterns below, before falling back to the generic Build fails → lake update && lake clean && lake build row. A specific match wins over the generic remediation.

Actions

1. Environment Check

ToolCheckRequired
leanlean --versionYes
lakelake --versionYes
python3python3 --versionFor scripts
gitgit --versionFor commits
rgrg --versionOptional (faster search)

Persistent-environment hosts use LEAN4_PLUGIN_ROOT, LEAN4_SCRIPTS, LEAN4_REFS, and LEAN4_PYTHON_BIN. Trusted native Codex installs instead receive absolute SessionStart paths; those values are not shell exports.

Run the shared preflight without depending on PATH, which may be absent.

Native Codex plugin: use the literal absolute SessionStart preflight value:

/absolute/plugin/root/bin/lean4-skills-preflight --codex

If trusted context is missing, report this canonical recovery block:

1. Review and trust the lean4 plugin hooks in /hooks.
2. Start a new Codex task (re-runs the SessionStart hook).
3. Run the absolute <plugin-root>/bin/lean4-skills-preflight --codex command; if it is missing, reinstall the plugin.

Persistent environment (including Claude Code):

if command -v lean4-skills-preflight >/dev/null 2>&1; then
    lean4-skills-preflight
elif [[ -n "${LEAN4_PLUGIN_ROOT:-}" && -x "$LEAN4_PLUGIN_ROOT/bin/lean4-skills-preflight" ]]; then
    "$LEAN4_PLUGIN_ROOT/bin/lean4-skills-preflight"
else
    echo "Lean4 bootstrap environment is not fully set up in this Claude Code session." >&2
    echo "  Recovery:" >&2
    echo "    1. Run /lean4:diagnose env for a full diagnosis." >&2
    echo "    2. Restart the Claude Code session (re-runs the SessionStart bootstrap hook)." >&2
    echo "    3. If it persists, check the plugin hook/bootstrap state (hooks.json, bootstrap.sh)." >&2
fi

The persistent preflight checks LEAN4_*, PATH, and wrappers. Codex checks the installed tree and absolute wrappers. Each has a canonical recovery block.

1b. MCP Tools

CheckDetectionStatus
Lean LSP MCPlean_goal tool available in this sessionOptional (sub-second feedback)
✓ … available or ⚠ … unavailable — see INSTALLATION.md

2. Plugin Check

Verify structure and permissions:

plugins/lean4/
├── .claude-plugin/plugin.json
├── .codex-plugin/plugin.json
├── commands/     (*.md command files)
├── hooks/        (Claude + Codex hook configs; executable hooks)
├── skills/lean4/ (SKILL.md + references/)
├── agents/       (4 files)
├── bin/          (lean4-skills-* wrappers; absolute under Codex, on PATH under Claude)
└── lib/scripts/  (executable .py / .sh internals)

3. Project Check

  • lakefile.lean and lean-toolchain present
  • lake build passes
  • Sorry count reported

4. Migration Detection (read-only)

Detects legacy v3 artifacts without making changes.

Legacy plugin installs:

~/.claude/plugins/lean4-theorem-proving/
~/.claude/plugins/lean4-subagents/
~/.claude/plugins/lean4-memories/

Stale environment variables:

  • LEAN4_PLUGIN_ROOT pointing to old path (e.g., lean4-theorem-proving)
  • LEAN4_SCRIPTS not under current plugin
  • LEAN4_REFS not under current plugin

Name mapping (v3 → v4):

V3V4
lean4-theorem-provinglean4
lean4-memoriesRemoved
lean4-subagentsIntegrated
/lean4-theorem-proving:*/lean4:*

With --global: Also scans user-level ~/.claude/ for duplicates or stale plugin versions. Only when explicitly requested.

5. Cleanup

Detects and optionally removes obsolete artifacts.

Workspace paths checked:

.claude/tools/lean4/
.claude/docs/lean4/
.claude/lean4-*/           # Any lean4-* directories

User-level paths (with --global):

~/.claude/plugins/lean4-theorem-proving/
~/.claude/plugins/lean4-subagents/
~/.claude/plugins/lean4-memories/

Behavior:

  • Default: Report findings, show rm -rf commands, do NOT execute
  • With --apply: Interactive per-item confirmation

Interactive prompt (--apply):

Found 3 items to clean:
  [1] .claude/tools/lean4/
  [2] .claude/docs/lean4/
  [3] .claude/lean4-memories/

Remove .claude/tools/lean4/? [y/n/a/q] y
  ✓ Removed

Remove .claude/docs/lean4/? [y/n/a/q] n
  → Skipped

Remove .claude/lean4-memories/? [y/n/a/q] q
  → Quit (1 removed, 1 skipped, 1 remaining)

Keys: y=remove this, n=keep this, a=remove all remaining, q=quit now

Output

Full diagnostic:

## Lean4 Diagnostics Report

### Environment
✓ lean 4.x.x
✓ lake 4.x.x
...

### MCP Tools
✓ Lean LSP MCP tools available in this session (lean_goal)

### Plugin
✓ LEAN4_PLUGIN_ROOT set
✓ Scripts executable
...

### Project
✓ Build passes
→ N sorries in M files

### Status: Ready

Migration report:

## Migration Check

### Legacy Plugins
⚠ Found: ~/.claude/plugins/lean4-theorem-proving/
  → Uninstall or remove this directory

### Stale Environment
✓ LEAN4_PLUGIN_ROOT points to current plugin

### Summary
Found 1 stale item. Run `/lean4:diagnose cleanup` to see removal commands.

Cleanup report:

## Cleanup Report

### Stale Files Found
.claude/tools/lean4/
.claude/docs/lean4/

### Removal Commands
rm -rf .claude/tools/lean4/
rm -rf .claude/docs/lean4/

No changes made. Run `/lean4:diagnose cleanup --apply` to remove.

Troubleshooting

IssueFix
Native Codex bare wrapper not found on PATHExpected: invoke the literal absolute bin_dir/lean4-skills-* path supplied by trusted SessionStart. Codex does not document persistent plugin PATH mutation.
LEAN4_SCRIPTS not set1. Run /lean4:diagnose env for a full diagnosis. 2. Restart the Claude Code session (re-runs the SessionStart bootstrap hook). 3. If it persists, check the plugin hook/bootstrap state (hooks.json, bootstrap.sh).
lean4-skills-* wrapper not found on PATH1. Run /lean4:diagnose env for a full diagnosis. 2. Restart the Claude Code session (re-runs the SessionStart bootstrap hook). 3. If it persists, check the plugin hook/bootstrap state (hooks.json, bootstrap.sh).
lake not foundInstall via elan
Scripts not executableWrappers should be shipped executable — check command -v lean4-skills-sorry-analyzer. For unwrapped internals: chmod +x $LEAN4_SCRIPTS/*.sh $LEAN4_SCRIPTS/*.py
Build failslake update && lake clean && lake build
Fresh worktree rebuild is slow / LSP times out on first usePrime cache (lake cache get or lake exe cache get), then lake build; do not symlink .lake/build from another worktree
Stale build after lake cleanHydrate cache (lake cache get or lake exe cache get), then lake build
Legacy plugin detectedUninstall old plugin, remove directory
Stale env varsRestart session after removing old plugin
Commands not found after migrationCheck /lean4:* not /lean4-theorem-proving:*
rg not foundInstall via package manager — see ripgrep
Lean LSP MCP tools unavailableCheck claude mcp list (Claude Code); if missing, claude mcp add --transport stdio --scope user lean-lsp -- uvx lean-lsp-mcp or see INSTALLATION.md

Under Codex, PreToolUse is advisory and is not a security boundary.

Module-System Troubleshooting

Error-triggered guidance for the Lean module system (post-2025-11-19 mathlib). These patterns take precedence over the generic Build fails row above; each links to a worked entry in compilation-errors.md.

Error patternFix
cannot import non-`module` X from `module` X lacks a module header, or an aggregator is plain-style. Plain lake exe mk_all preserves the existing style; use lake exe mk_all --module to create or convert a module-style aggregator. Import-list staleness is a separate companion problem — § 16
Unknown identifier for a name that exists upstream; Expected a definition with an exposed body; backward.privateInPublic warningModule visibility: private-by-default declarations / non-exposed bodies. Use the public API, import all (same Lake package), or upstream public/@[expose] — § 17
Invalid `meta` definition ..., not marked `meta` vs may not access declaration ... marked as `meta` Two opposite meta-phase failures: the first may need meta import; for the second, meta import is not the fix — the consumer becomes meta or uses a non-meta implementation — § 18
Old-style plain import header in a module-system repoRewrite to the mathlib-style.md header (module, grouped public import/import, public section), then lake exe mk_all — § 19

The lake exe mk_all remediation string here is the same one /lean4:checkpoint's mk_all gate (#111) will surface at checkpoint time — users hitting it mid-build and at checkpoint get one consistent instruction.

Safety

  • All modes are read-only by default
  • migrate never makes changes (detection only)
  • cleanup shows commands but does not execute without --apply
  • cleanup --apply prompts per-item (y/n/a/q) - users can keep specific items
  • --global only scans ~/ when explicitly requested
  • Does not modify Lean source files

See Also

  • /lean4:prove - Guided cycle-by-cycle proving
  • /lean4:checkpoint - Save progress
  • Examples

Lean4 Disprove

Search for a counterexample to a target proposition and, when possible, produce a Lean proof of its negation. Reports REFUTED only when Lean certifies the refutation; otherwise WITNESS_UNCERTIFIED (a candidate was found but Lean refused to certify it) or INCONCLUSIVE (no candidate found within budgets).

/lean4:disprove is always interactive — disprove is an exploratory search, and the workflow generates three dynamic menus each cycle (Step 0 knowledge search, Step 1 method, Step 2 config) seeded by accumulated evidence and the Target Profile.

Usage

/lean4:disprove Foo.lean:42                       # File + line (sorry/declaration site)
/lean4:disprove MyNs.SubNs.myThm                  # Qualified theorem name
/lean4:disprove Foo.lean:42 --max-cycles=5
/lean4:disprove Foo.lean:42 --commit=never

Prime Directive

Report REFUTED only when a Lean term of the negation typechecks under lake lean <target-file> (the dependency-aware file gate: it builds the file's imports, then elaborates this exact file — also for a target outside any lean_lib; lake env lean is a pre-screen, never the license — it reads built .oleans and cannot see a stale import) with no sorry or admit and its axiom set is within the allowed whitelist (propext, Classical.choice, Quot.sound; plus Lean.ofReduceBool only under an explicit native_decide opt-in this cycle). Fast witnesses and informal heuristics are hypotheses until Lean certifies them. See disprove-engine.md § Prime Directive.

REFUTED is licensed by a checked closed term of type ¬ TARGET, not by the artifact's surface form: T_counterexample may be a direct ¬ TARGET theorem or a witness theorem whose named per-shape wrapper (also axiom-checked) derives ¬ TARGET.

Invocation Contract

Interpret this command's inputs per the Command Invocation Contract.

Primary path (hook-validated): If a validated-invocation block for this command appears in context, treat it as the authoritative interpretation of parser-decidable inputs and do not re-parse the raw invocation text for those inputs. Start by reading all parser-decided fields from the block. Emit the final Resolved Inputs summary from the block values. See Validated Invocation Block.

Fallback path (other hosts): If no validated-invocation block is present, parse the raw invocation text against this command's input table before Phase 1.

Runtime requirement: /lean4:disprove requires Python 3.11+ — its method registry loader (lib/disprove_methods.py) uses the stdlib tomllib parser. The rest of the lean4 plugin targets Python 3.10+. On an older interpreter the command fails fast with a clear "requires Python 3.11+" error rather than an opaque ImportError.

Startup requirements:

  1. Emit a Resolved Inputs block with explicit values, defaults, coercions, ignored flags, and startup validation errors.
  2. Refuse to start on startup validation errors.
  3. Call lean4-skills-cycle-tracker init with resolved numeric values for --max-cycles, --max-stuck-cycles, --max-runtime, and --max-knowledge-search-per-cycle=<--knowledge-search-budget>. Disprove has no deep mode in v1; omit the deep args and let the tracker default them (they remain inert because disprove never calls can-deep / deep). A failed init (exit 2) is a startup validation error — do not proceed.
  4. The cycle-tracker state file is the single source of truth for session counters. Read counters from tick/status output, not from conversational memory.

Inputs

ArgRequiredDefaultDescription
targetYes—File.lean:LINE or Namespace.theoremName. Inline Props not supported in v1. A qualified name containing a prime (') or an escaped «…» identifier is not accepted in v1 — use a File.lean:LINE target for that declaration.
--max-cyclesNo3Max widening passes. Each cycle picks one method via the Step 1 menu and configures its parameters via the Step 2 menu.
--max-stuck-cyclesNo2Bail after this many consecutive cycles where the next cycle's Step 1 menu has no non-failed (family, config) pair to place in its top 3 (no remaining widening lever).
--max-runtimeNo5mBest-effort wall-clock session budget across all cycles.
--negation-policyNocounterexample-onlyReserved for future salvage modes; locked in v1.
--commitNoaskPer-cycle Checkpoint behavior. ask prompts before each commit; auto commits without prompting; never skips committing (leave staging to /lean4:checkpoint).
--knowledge-search-budgetNo3Max Step 0 (knowledge search) visits per cycle. Cycle 1 always runs Step 0 once; later cycles only re-enter Step 0 if their Step 1 menu surfaces knowledge search and the user picks it. After the Nth visit completes, knowledge search is disabled in that cycle's Step 1 menu.

Per-method parameters (e.g. enumerate's range, native_decide opt-in, sample count for plausible) are surfaced as dynamic Step 2 candidates in each cycle's Plan phase, not top-level flags. See disprove-engine.md § Step 2 — Config Menu.

Actions

Six phases — see disprove-engine.md for full mechanics.

Phase 1: Plan

During Plan, the cycle builds three dynamic menus from accumulated evidence, the Target Profile, and the prior cycle's Review:

  • Step 0 — Knowledge Search (engine)
  • Step 1 — Method (engine)
  • Step 2 — Config (engine)

Keep only the selected entries and their rationale in the cycle record. Cycle 1 also resolves the TARGET, normalizes shape, builds the Target Profile, and runs Step 0 once; cycle ≥2 re-enters Step 0 only if Step 1 surfaces knowledge search and the user picks it. A qualified-name target must resolve to a writable source file (the declaration's file); if it resolves only to a read-only dependency, the session refuses before Phase 2 (use a File.lean:LINE target instead).

Full menu mechanics, invariants, and the findings schema live in disprove-engine.md § Phase 1 — Plan.

Phase 2: Work

See disprove-engine.md § Phase 2 — Work. Run the chosen method and pre-screen candidates via lean_multi_attempt; Work yields a pre-screen-passing candidate (or none). The cycle outcome (certified / near-miss / exhausted-no-witness / no-candidate) is finalized by the Phase 3 gate, not in Work.

Phase 3: Checkpoint

See disprove-engine.md § Phase 3 — Checkpoint. On a pre-screen-passing candidate, open a transaction (txn=$(lean4-skills-disprove-artifact-txn begin)) and append T_counterexample via its append --txn=$txn --role=artifact subcommand (witness shapes also append the gate-only *_negates_target with --role=gate; every shape then appends the gate-only #print axioms <¬TARGET decl> (unqualified, so it resolves to the just-appended declaration even inside a namespace left open to end-of-file) probe with --role=gate), run lake lean <target-file> once from the project root (the dependency-aware file gate: imports built, then this exact file elaborated; not lake env lean, which cannot see a stale import) and read the axiom set of the declaration carrying ¬ TARGET (T_counterexample for direct shapes, T_counterexample_negates_target for witness shapes) from that same run's #print axioms output — lean_verify is advisory only, since its LSP import snapshot can lag the rebuilt imports. Report REFUTED only if it typechecks and that declaration's axioms ⊆ {propext, Classical.choice, Quot.sound} (plus Lean.ofReduceBool only under an explicit native_decide opt-in this cycle): on REFUTED, drop-role --txn=$txn --role=gate (every shape: removes the probe and any wrapper), re-run lake lean <target-file> on the gate-free file, and commit only T_counterexample. Otherwise rollback --txn=$txn (reverts every declaration appended this cycle), distinguishing the non-REFUTED outcomes: a typecheck failure is a near-miss cycle outcome (capture the error signature for the next cycle), while a non-whitelisted axiom or inconclusive axiom inspection is WITNESS_UNCERTIFIED. <target-file> is the resolved source file — for a qualified-name target, the declaration's writable source file from Phase 1 (disprove refuses if it resolves only to a read-only dependency).

Commit prompt (when --commit=ask):

Commit T_counterexample to <file>? [yes / yes-all / no / never]
  • yes — commit this cycle's artifact; prompt again next cycle.
  • yes-all — switch to auto for the rest of the session.
  • no — unstage; don't commit this cycle.
  • never — switch to never for the rest of the session.

For provenance, the commit message body includes the relevant audit field from the cycle's Phase 5 evidence record:

  • If the cycle's method was custom method: derived-from-custom="<user text>".
  • If the family was external: external_script_path="<path under $LEAN4_SESSION_DIR/scripts/>" (the script remains for re-run / audit).
  • If the entry was [verify-known-cex]: derived-from-verify-known-cex="<source_url or repo-relative path>".

Phase 4: Review

See disprove-engine.md § Phase 4 — Review. Classifies the cycle's outcome and captures the residual error signature on near-misses for the next cycle's menus.

Phase 5: Accumulate

See disprove-engine.md § Phase 5 — Accumulate. Appends the cycle's (family, config, outcome, near-miss_signature) to session evidence. No hardcoded recommendation table — the next cycle's Step 0 / Step 1 / Step 2 menus absorb the recommendation logic. A cycle is stuck when it produced no certified outcome AND the next cycle's Step 1 menu has no non-failed (family, config) pair to place in its top 3.

Phase 6: Continue / Stop

See disprove-engine.md § Phase 6 — Continue / Stop. Always prompts the user:

Cycle N complete (outcome: <outcome>).
Next cycle's Step 1 preview: <top-ranked entry's family + config>.
- [continue] — run cycle N+1 with the preview pre-selected at Step 1
- [stop]     — accept the current outcome and exit

To override the preview, pick a different entry (any registry family, knowledge search, or custom method) when the next cycle's Step 1 menu opens.

Stop Conditions

The cycle-tracker enforces budgets at each tick boundary. The session stops on the first of:

  1. REFUTED outcome — a cycle produced a certified counterexample
  2. Max stuck cycles — --max-stuck-cycles consecutive stuck cycles
  3. Max cycles — --max-cycles total cycles run
  4. Max runtime — wall-clock budget reached (best-effort, checked at cycle boundaries)
  5. User stop — user chose stop at a Continue/Stop prompt

Disprove Summary

When the command stops (any branch), emit:

## Disprove Summary

**Outcome:** [REFUTED | WITNESS_UNCERTIFIED | INCONCLUSIVE]

| Metric | Value |
|--------|-------|
| Target | <resolved descriptor> |
| Witness | <Lean term or "—"> |
| Artifact theorem | T_counterexample (or "—") |
| Artifact file | <path or "—"> |
| Build gate | passed | failed | skipped |
| Axiom gate | <axioms listed, e.g. "propext, Classical.choice, Quot.sound" \| failed \| skipped> |
| Cycles run | <N> |
| Stuck cycles | <N> |
| Time elapsed | <T> |

**Per-cycle attempts:**

| # | Method (family) | Config | Outcome | URL |
|---|-----------------|--------|---------|-----|
| 1 | <family> | <key=value list> | <outcome> | <URL or —> |
| 2 | <family> | <...> | <outcome> | <URL or —> |
| ... | | | | |

The `Method (family)` column shows the stable id from the registry; the
`Config` column mirrors the cycle's Step 2 choices — for example
`native_decide=off` for `decide-cascade`; `range=[a,b), atom=<tactic>`
for `enumerate`; `samples=N, seed=<int>` for `plausible`. The `URL`
column is populated **only** for cycles whose certifying witness was
elevated via `[verify-known-cex]` (the URL is the verified `source_url`
of the originating Step 0 finding); all other cycles show `—`. See
[disprove-engine.md § Step 2 — Config Menu](../skills/lean4/references/disprove-engine.md#step-2--config-menu).

[REFUTED]
  Counterexample certified.
  - If already committed (`--commit=auto`, or `ask` accepted): committed as
    `disprove: T_counterexample — cycle N` (see `git log -1`).
  - If not committed (`--commit=never`, or `ask` declined): Recommended:
    /lean4:checkpoint to commit.

[WITNESS_UNCERTIFIED]
  Candidate witness w0 = <value>; Lean error <signature>.
  Recommended: /lean4:prove <target> --deep=stuck, or rerun and pick
               `tactics` in Step 1, or enable native_decide in Step 2.

[INCONCLUSIVE]
  Coverage: <e.g. enumerate covered [0, 128); plausible sampled 200>
  Stop reason: max-cycles | max-stuck | max-runtime | user-stop
  Recommended: rerun with --max-cycles=<higher> and pick `knowledge
               search` in Step 1 (widens with fresh evidence), or hand
               off to /lean4:prove for a positive proof attempt.

Safety

  • Append-only, transactional. Never rewrite an existing theorem T : P := by sorry declaration to : ¬ P. Cycle artifacts are written through lean4-skills-disprove-artifact-txn (over the collision-safe lean4-skills-disprove-emit-artifact): each append is wrapped in txn-id markers and refuses to modify or clobber an existing declaration; the cycle's writes are reverted as a unit via rollback / drop-role on failure or gate-block drop.
  • No native_decide without opt-in (any method). native_decide defaults off and is not in the tactics method's default list. Anywhere it can appear — decide-cascade's native_decide=on, a custom tactics list, or a custom-config — it is the same explicit, audit-worthy opt-in: the cycling LLM surfaces it as such in Step 2 and records it in the cycle's evidence. Enabling admits the Lean.ofReduceBool axiom, which the compile/axiom gate then permits only for that cycle.
  • No REFUTED without compile gate + axiom gate. lean_multi_attempt and lake env lean are pre-screens; REFUTED requires lake lean <target-file> (from the project root, on the resolved source path; builds the file's imports first, so the check is dependency-aware) to succeed (no sorry/admit) and the ¬ TARGET declaration's axioms (T_counterexample, or T_counterexample_negates_target for witness shapes) ⊆ {propext, Classical.choice, Quot.sound} (plus Lean.ofReduceBool only under an explicit native_decide opt-in). A non-whitelisted axiom, or inconclusive axiom inspection, → revert any declarations appended this cycle and report WITNESS_UNCERTIFIED.
  • No Step 0 findings without source_url. Findings produced without a citable URL or repo-relative path are dropped at write time. Web counterexample candidates require WebFetch verification before elevation to [verify-known-cex]. If WebFetch is unavailable in the host, web findings are dropped, not elevated.
  • Line width. Follow mathlib 100-char line width — do not wrap lines at 80 when they fit within 100.

See Also

  • /lean4:prove — Guided cycle-by-cycle proving
  • /lean4:autoprove — Autonomous multi-cycle proving
  • /lean4:checkpoint — Manual save point
  • Disprove Engine — Phase mechanics, Step 0 / 1 / 2 menus (Knowledge Search / Method / Config), Per-Shape Recipes
  • Implementation Status — what is deterministic script vs model-mediated vs deferred
  • Method Registry — Stable method ids, parameter schemas, cost classes
  • Examples
  • Benchmark — 16-target evaluation suite (certified refutations) from the disprove paper

Citation

The /lean4:disprove skill is described in:

@inproceedings{ondras2026lean,
  title     = {Lean Disprove: Certified Counterexample Search for {AI}-Assisted Formal Mathematics},
  author    = {Jan Ondras and Cameron Freer},
  booktitle = {3rd AI for Math Workshop: Toward Self-Evolving Scientific Agents},
  note      = {Workshop at ICML 2026},
  year      = {2026},
  url       = {https://openreview.net/forum?id=5ck1jRE65S}
}

Lean4 Draft

Draft Lean 4 declaration skeletons from informal mathematical claims. Produces sorry-stubbed statements ready for /lean4:prove or /lean4:autoprove.

Usage

/lean4:draft "Every continuous function on a compact set is bounded"
/lean4:draft --mode=attempt "Zorn's lemma implies AC"
/lean4:draft --source ./paper.pdf          # Ingest, pick claims, draft skeletons
/lean4:draft --source ./paper.pdf "Theorem 3.2"  # Source as context, topic as claim
/lean4:draft --output=file --out=MyTheorem.lean "..."

Invocation Contract

Interpret this command's inputs per the Command Invocation Contract.

Primary path (hook-validated): If a validated-invocation block for this command appears in context, treat it as the authoritative interpretation of parser-decidable inputs and do not re-parse the raw invocation text for those inputs. Start by reading all parser-decided fields from the block. Emit the final Resolved Inputs summary from the block values. See Validated Invocation Block.

Fallback path (other hosts): If no validated-invocation block is present, parse the raw invocation text against this command's input table before claim acquisition.

Startup requirements:

  1. Emit a Resolved Inputs block with explicit values, defaults, coercions, ignored flags, and startup validation errors.
  2. Refuse to start on startup validation errors.
  3. Validate output paths and overwrite policy before writing anything.

Inputs

ArgRequiredDefaultDescription
topicno—Informal claim to draft. Optional when --source provides it (source-led flow). At least one of topic or --source must be given; omitting both is a startup validation error.
--modenoskeletonskeleton | attempt. skeleton produces sorry-stubbed declarations only. attempt adds a proof-attempt loop (lean_multi_attempt) before finalizing.
--elab-checknobest-effortbest-effort | strict. Elaboration check strictness for drafted skeletons.
--levelnointermediatebeginner | intermediate | expert
--outputnochatchat | scratch | file
--outno—Output path. Required when --output=file; startup validation error if missing.
--overwritenofalseAllow overwriting existing files with --output=file. Without flag, existing target → startup validation error.
--mathlib-templatenofalseEmit the mathlib module-system file header on --output=file writes regardless of detected project context. Requires --output=file; mutually exclusive with --no-mathlib-template.
--no-mathlib-templatenofalseNever emit the mathlib module-system file header on --output=file writes, regardless of detected project context. Requires --output=file; mutually exclusive with --mathlib-template.
--sourceno—File path, URL, or PDF to seed drafting. See learn-pathways.md.
--intentnomathauto | usage | math. See learn-pathways.md.
--presentationnoautoinformal | supporting | formal | auto. Controls user-facing display, not Lean backing. See learn-pathways.md.
--claim-selectno—first | named:"..." | regex:"...". Noninteractive claim selection from --source. See below.

Output validation

  • --output=file without --out → startup validation error
  • --output=scratch → .scratch/lean4/draft-<timestamp>.lean (workspace-local). Auto-create .scratch/lean4/ if missing; warn if .scratch/ is not in .gitignore.
  • --output=file with existing target and no --overwrite → startup validation error
  • --mathlib-template with --no-mathlib-template → startup validation error (mutually exclusive)
  • --mathlib-template or --no-mathlib-template without --output=file → startup validation error (either flag only affects whole-file writes)

Flag validation

  • --intent, --presentation, or --elab-check with invalid value → startup validation error.
  • --intent=auto inference: apply the shared inference rules, then coerce internals → usage and authoring → usage (draft does not define behavior for those intents).
  • --source + unreadable format → warn + ask for text excerpt.
  • --claim-select without --source → startup validation error (nothing to select from).

Noninteractive Claim Selection

PolicyBehavior
firstSelect the first extractable claim from --source
named:"..."Match claims by title/label substring (e.g. named:"Theorem 3.2")
regex:"..."Match claims by regex on extracted claim text

Standalone draft processes one claim per invocation (batch-size is 1). When called by the synthesis outer loop (--caller=autoformalize or --caller=formalize), draft receives a single pre-selected claim as its topic. The outer loop owns queue extraction and iteration — see cycle-engine.md.

File Write Contract

Standalone draft writes whole files via --output=file + --out. When called with --caller=autoformalize or --caller=formalize (internal-only flag), draft writes declaration-only blocks to $TMPDIR/lean4-draft/<session-id>/claim-<N>.lean with -- needs-import: comments. The outer loop owns file assembly and commits. See cycle-engine.md.

Mathlib Template Gate

Applies to --output=file whole-file writes only. Chat, scratch, and --caller=* declaration-block modes are unchanged. Resolve whether to emit the mathlib module-system file header (mathlib-style.md):

  1. Explicit flag wins. --mathlib-template → emit it; --no-mathlib-template → do not. Only a flag resolving to true participates in precedence; explicit false (e.g. --mathlib-template=false) is equivalent to omission.
  2. Otherwise consult the shared project-context helper. Run lean4-skills-project-context --from <dir> where <dir> is the nearest existing parent directory of the --out target (the target may not exist yet; passing a nonexistent target directly would exit 4). Require schema equal to project-context/v1 in the JSON output, intent.contributing_upstream a string in yes | no | unknown, and intent.source a string in its documented domain; any missing, non-string, or out-of-domain value is malformed helper output.
  3. yes → emit the mathlib header. no → existing generic behavior, unchanged. unknown → existing generic behavior, plus a one-line advisory in the output summary: pass --mathlib-template if this file targets mathlib.
  4. Helper failure degrades to unknown. Missing wrapper, nonzero exit, malformed JSON, wrong schema, or a malformed intent record per step 2 → treat as unknown with source helper-failure (advisory included). The gate never blocks a write.
  5. Report the decision. The Resolved Inputs block states the effective decision and its source: flag when a flag decided it, the helper's reported intent.source (e.g. env-override, remote-heuristic, default) otherwise, or helper-failure when the helper could not be consulted.

When the gate fires, the emitted file shape is: copyright block, then module, then the public import block, then the plain import block, then the /-! module docstring, then a public section opening the exported scope before any declarations. Declarations in a module are private by default, and public import alone re-exports imports without making this file's declarations public — a file missing the public section (or per-declaration public) elaborates yet exports nothing. Use @[expose] public section only when downstream definitional unfolding is intentionally part of the API; plain public section exports signatures while keeping implementations opaque. Preserve the selected import set — assign public import to public-API dependencies (statements and signatures are the central case; exported instances, notation, syntax, and metaprogramming can also require it, and Lean's own public/private checking is authoritative over this heuristic) and plain import to implementation/proof-only dependencies, alphabetized within each block with a blank line between the two nonempty blocks (omit a block rather than emit an empty group); the gate changes header shape, never import selection. For the copyright block, use the current year and git config user.name as best-effort defaults — user-supplied attribution always wins, lookup failure falls back to the Author Name placeholder and never blocks the write, and the chosen value is reported in the output summary.

Draft does not run lake exe mk_all; it emits the correct file shape and reminds the user to run it after adding files. Checkpoint-time mk_all enforcement is #111's scope.

Actions

0. Intent Intake

Resolve --intent and --presentation. Defaults: --intent=math, --presentation=auto (→ informal for math intent). Announce resolved values. Explicit flags override inference.

1. Claim Acquisition

Two entry points:

  • Direct: topic given → parse the informal claim directly.
  • Source-led: --source given, no topic → ingest source (.lean → Read; PDF → Read; .md/.txt → Read; URL → web fetch; other → warn + ask for excerpt). Extract candidate claims. If --claim-select is present, select noninteractively per policy; otherwise present to user, user picks which to draft.
  • Both: topic and --source given → use topic as the claim and source as supporting context.

2. Draft Theorem Skeleton

Parse natural-language claim → draft theorem skeleton with appropriate types, hypotheses, and conclusion. Use mathlib naming conventions and types where possible (lean_local_search, lean_leanfinder/lean_leansearch, lean_loogle to find canonical types).

3. Elaboration Check

Run lean_diagnostic_messages on the drafted skeleton. Under --elab-check=strict, all diagnostics must be clean (excluding the expected sorry). Under --elab-check=best-effort, attempt to fix diagnostics but continue if unfixable.

4. Proof Attempt (--mode=attempt only)

When --mode=attempt: lean_goal + lean_multi_attempt loop. Search mathlib for existing proofs or applicable lemmas before writing tactics from scratch. If proof succeeds, include it. If proof fails, leave sorry and note the attempt.

This mode recovers the proof-attempt behavior of the old /lean4:formalize command. For full synthesis (including falsification, rigor completion, and assumption ledgers), use /lean4:formalize.

5. Depth Check

Offer the depth-check menu:

  • show source / show proof state
  • alternative formalization (e.g., different types or encoding)
  • save to scratch / write to file

Output

Output format follows --presentation: informal → prose with math notation (no Lean blocks unless user requests "show Lean backing"); supporting → prose with selective Lean snippets; formal → Lean code blocks as primary content. In scratch or file mode, additionally write a .lean file regardless of presentation.

Safety

  • Read-only in chat mode. Does not write files unless --output requests it.
  • No silent mutations. Prefer LSP tools (lean_goal) over file writes for compilation checks. If LSP unavailable and temp file needed for internal compilation, write only under /tmp/lean4-draft/, auto-cleanup after use, warn user before writing.
  • No commits. /draft never commits. --output=file writes but does not stage or commit.
  • Docstring policy — Rule C (new-file / new-decl generation). Draft may emit a module docstring on a file it newly creates and a declaration docstring on a declaration it newly creates. It must not rewrite docstrings on declarations that already exist in a target file — those stay under Rule A. When the Mathlib Template Gate selects the mathlib header, Rule C fills that template's module-docstring slot in mathlib-style.md § 1 shape; Rule C neither selects nor redefines the template.
  • Path restriction. User-requested outputs (--output=file, --output=scratch) restricted to workspace root (scratch uses .scratch/lean4/). Reject path traversal (../) or absolute paths outside workspace. Internal temp files may use /tmp/lean4-draft/.
  • Overwrite protection. --output=file with existing target requires --overwrite; otherwise startup validation error.
  • Caller integration: When --caller=autoformalize or --caller=formalize, file assembly and draft: commits are handled by the outer loop, not by draft.
  • All guardrails.sh rules apply.
  • Line width. Follow mathlib 100-char line width — do not wrap lines at 80 when they fit within 100.

See Also

  • Examples
  • LSP Tools API — search tools used in proof attempts
  • Learning Pathways — intent taxonomy, source handling
  • /lean4:formalize — interactive synthesis (draft + prove)
  • /lean4:autoformalize — autonomous synthesis (draft + autoprove)
  • /lean4:disprove — guided counterexample search with certified refutation (use when you suspect a drafted claim is false)

Lean4 Formalize

Interactive formalization: draft Lean skeletons from informal claims, then prove them with guided cycles. Combines /lean4:draft and /lean4:prove in a single human-in-the-loop workflow.

Compatibility: Accepts all flags from old formalize (v4.3.x). Semantics are broader — new formalize runs a full prove cycle after drafting. Users wanting the old lighter-weight "draft + shallow proof attempt" behavior should use /lean4:draft --mode=attempt. Users wanting skeletons only should use /lean4:draft.

Usage

/lean4:formalize "Every continuous function on a compact set is bounded"
/lean4:formalize --rigor=axiomatic "Zorn's lemma implies AC"
/lean4:formalize --source ./paper.pdf          # Ingest, pick claims, formalize
/lean4:formalize --source ./paper.pdf "Theorem 3.2"  # Source as context, topic as claim
/lean4:formalize --output=file --out=MyTheorem.lean "..."

Invocation Contract

Interpret this command's inputs per the Command Invocation Contract.

Primary path (hook-validated): If a validated-invocation block for this command appears in context, treat it as the authoritative interpretation of parser-decidable inputs and do not re-parse the raw invocation text for those inputs. Start by reading all parser-decided fields from the block. Emit the final Resolved Inputs summary from the block values. See Validated Invocation Block.

Fallback path (other hosts): If no validated-invocation block is present, parse the raw invocation text against this command's input table before drafting or proving.

Startup requirements:

  1. Emit a Resolved Inputs block with explicit values, defaults, coercions, ignored flags, and startup validation errors.
  2. Refuse to start on startup validation errors.
  3. Validate output paths and overwrite policy before writing anything.

Inputs

ArgRequiredDefaultDescription
topicno—Informal claim to formalize. Optional when --source provides it (source-led flow). At least one of topic or --source must be given; omitting both is a startup validation error.
--rigornocheckedchecked | sketch | axiomatic
--verifynobest-effortbest-effort | strict. Verification strictness for key claims. See learn-pathways.md.
--levelnointermediatebeginner | intermediate | expert
--outputnochatchat | scratch | file
--outno—Output path. Required when --output=file; startup validation error if missing.
--overwritenofalseAllow overwriting existing files with --output=file. Without flag, existing target → startup validation error.
--mathlib-templatenofalseEmit the mathlib module-system file header on --output=file writes regardless of detected project context. Requires --output=file; mutually exclusive with --no-mathlib-template.
--no-mathlib-templatenofalseNever emit the mathlib module-system file header on --output=file writes, regardless of detected project context. Requires --output=file; mutually exclusive with --mathlib-template.
--sourceno—File path, URL, or PDF to seed formalization. See learn-pathways.md.
--intentnomathauto | usage | math. See learn-pathways.md.
--presentationnoautoinformal | supporting | formal | auto. Controls user-facing display, not Lean backing. See learn-pathways.md.
--claim-selectno—first | named:"..." | regex:"...". Noninteractive claim selection from --source.
--draft-modenoattemptskeleton | attempt. Mode for the draft phase (default is attempt in formalize context).
--draft-elab-checknobest-effortbest-effort | strict. Elaboration check for the draft phase.
--deepnonevernever | ask | stuck | always. Deep mode for prove phase.
--deep-sorry-budgetno1Max sorries per deep invocation
--deep-time-budgetno10mAdvisory: scopes deep-mode subagent work. Not tracked or enforced.
--commitnoaskask | auto | never
--golfnopromptprompt | auto | never

Output validation

  • --output=file without --out → startup validation error
  • --output=scratch → .scratch/lean4/formalize-<timestamp>.lean (workspace-local). Auto-create .scratch/lean4/ if missing; warn if .scratch/ is not in .gitignore.
  • --output=file with existing target and no --overwrite → startup validation error
  • --mathlib-template with --no-mathlib-template → startup validation error (mutually exclusive)
  • --mathlib-template or --no-mathlib-template without --output=file → startup validation error (either flag only affects whole-file writes)

Flag validation

  • --intent, --presentation, or --verify with invalid value → startup validation error.
  • --intent=auto inference: apply the shared inference rules, then coerce internals → usage and authoring → usage (formalize does not define behavior for those intents).
  • --source + unreadable format → warn + ask for text excerpt.
  • --claim-select without --source → startup validation error (nothing to select from).

Noninteractive Claim Selection

PolicyBehavior
firstSelect the first extractable claim from --source
named:"..."Match claims by title/label substring (e.g. named:"Theorem 3.2")
regex:"..."Match claims by regex on extracted claim text

Standalone formalize processes one claim per invocation (batch-size is 1).

Mathlib Template Gate

Applies to --output=file whole-file writes only; chat and scratch modes are unchanged. Formalize follows the same gate contract as draft — see Mathlib Template Gate for the full resolution rules. Summary:

  1. Explicit flag wins: --mathlib-template → emit the mathlib module-system file header (mathlib-style.md); --no-mathlib-template → do not. Only a flag resolving to true participates in precedence; explicit false is equivalent to omission.
  2. Otherwise run lean4-skills-project-context --from <dir> from the nearest existing parent directory of the --out target, require schema equal to project-context/v1, and read intent.contributing_upstream: yes → emit the header; no → existing generic behavior; unknown → existing generic behavior plus a one-line advisory (pass --mathlib-template if this file targets mathlib).
  3. Helper failure (missing wrapper, nonzero exit, malformed JSON, wrong schema, or a malformed intent record) degrades to unknown with source helper-failure; the gate never blocks a write.
  4. The emitted file places declarations in a public section after the module docstring — declarations in a module are private by default, and public import alone does not export them.
  5. Report the effective decision and its source (flag, the helper's intent.source, or helper-failure) in the Resolved Inputs block.

Formalize does not run lake exe mk_all; it emits the correct file shape and reminds the user to run it after adding files. Checkpoint-time mk_all enforcement is #111's scope.

Actions

Phase 1: Draft

Invoke draft logic (same algorithm as /lean4:draft):

  1. Intent Intake — resolve --intent and --presentation.
  2. Claim Acquisition — parse topic or ingest --source.
  3. Draft Theorem Skeleton — translate claim to sorry-stubbed Lean declaration.
  4. Elaboration Check — lean_diagnostic_messages on skeleton.
  5. Proof Attempt (when --draft-mode=attempt, default) — lean_goal + lean_multi_attempt loop.

Phase 2: Prove

Invoke prove logic (same algorithm as /lean4:prove):

  1. Run guided prove cycle on the drafted declaration.
  2. Falsification & rigor checks per --rigor.
  3. User confirms or adjusts between cycles.

Rigor completion criteria:

RigorsorryDiagnosticsNon-standard axiomSilent global axiom
checkedFAILFAILFAILFAIL
axiomaticFAILFAILallowed if in ledgerFAIL
sketchallowedallowedallowedFAIL
  • sketch: never fails finalization, but always prints -- ⚠ NOT VERIFIED — sketch only banner.
  • axiomatic: allows explicit assumptions but hard-fails on any silently introduced global axiom not in the ledger.
  • All modes hard-fail on silent global axioms — no exceptions.

If proof blocked (no counterexample found), offer in order: local assumptions as parameters (preferred) → explicit axiomatic draft with assumption ledger + warning.

Phase 3: Statement Mismatch Handling

If the prove phase concludes the statement is wrong (deep mode emits next_action = redraft), present to user:

  1. Redraft — return to Phase 1 with revised claim
  2. Salvage sibling — create T_salvaged with weaker statement
  3. Preserve + stop — keep current statement, mark sorry, stop
  4. Continue — keep trying with current statement

Permission boundary: Formalize owns the right to change declaration headers. The prove phase itself cannot — it recommends redraft, and formalize executes the change with user approval.

Phase 4: Depth Check

Offer the depth-check menu:

  • show source / show proof state
  • alternative formalization (e.g., different types or encoding)
  • generalize (weaken hypotheses)
  • strengthen (add conclusions)
  • save to scratch / write to file

Output

Output format follows --presentation: informal → prose with math notation (no Lean blocks unless user requests "show Lean backing"); supporting → prose with selective Lean snippets; formal → Lean code blocks as primary content. In scratch or file mode, additionally write a .lean file regardless of presentation.

Assumption Ledger (axiomatic rigor)

-- Assumption Ledger
-- ┌──────────────────────────┬────────────────────┬───────────┬─────────────────────┐
-- │ Assumption               │ Justification      │ Scope     │ Introduced by       │
-- ├──────────────────────────┼────────────────────┼───────────┼─────────────────────┤
-- │ h_cont : Continuous f    │ stated in claim    │ parameter │ user-stated         │
-- │ h_bdd : IsBounded S     │ needed for compact │ parameter │ assistant-inferred  │
-- └──────────────────────────┴────────────────────┴───────────┴─────────────────────┘

Standard Axiom Whitelist

propext, Classical.choice, Quot.sound — not flagged. All others reported as non-standard.

Always run lean4-skills-check-axioms-inline <target> --report-only before presenting final results.

Safety

  • Read-only in chat mode. Does not write files unless --output requests it.
  • No silent mutations. Prefer LSP tools (lean_goal) over file writes for compilation checks. If LSP unavailable and temp file needed for internal compilation, write only under /tmp/lean4-formalize/, auto-cleanup after use, warn user before writing.
  • No commits in standalone mode. /formalize never commits in standalone mode (--commit is accepted for prove-phase compatibility but inert — no staging, no committing). --output=file writes but does not stage or commit.
  • Docstring policy — Rule C (new-file / new-decl generation). Formalize may emit a module docstring on a file it newly creates and a declaration docstring on a declaration it newly creates; it must not rewrite docstrings on pre-existing declarations (those stay under Rule A). When the Mathlib Template Gate selects the mathlib header, Rule C fills that template's module-docstring slot in mathlib-style.md § 1 shape; Rule C neither selects nor redefines the template.
  • Path restriction. User-requested outputs (--output=file, --output=scratch) restricted to workspace root (scratch uses .scratch/lean4/). Reject path traversal (../) or absolute paths outside workspace. Internal temp files may use /tmp/lean4-formalize/.
  • Overwrite protection. --output=file with existing target requires --overwrite; otherwise startup validation error.
  • Never add global axioms silently. Assumptions go as explicit theorem parameters or in namespace Assumptions. Always verified with lean4-skills-check-axioms-inline <target> --report-only.
  • All guardrails.sh rules apply.
  • Line width. Follow mathlib 100-char line width — do not wrap lines at 80 when they fit within 100.

See Also

  • Examples
  • LSP Tools API — search tools used in proof attempts
  • Learning Pathways — intent taxonomy, source handling
  • /lean4:draft — skeleton-only drafting (no prove phase)
  • /lean4:autoformalize — autonomous synthesis (unattended)

Lean4 Golf

Improve Lean proofs that already compile. Score candidates by: correctness → directness → clarity/inference burden → performance/determinism → length. Length is still a core goal, but a tiebreaker among acceptable proofs.

Prerequisite: Code must compile. Verify code compiles first (lean_diagnostic_messages(file) or lake env lean <path/to/File.lean> from project root; lake build for project-wide).

Usage

/lean4:golf                     # Golf entire project
/lean4:golf File.lean           # Golf specific file
/lean4:golf File.lean:42        # Golf proof at specific line
/lean4:golf --dry-run           # Show opportunities without applying
/lean4:golf --search=full          # Include lemma replacement pass
/lean4:golf --max-delegates=3    # Override default 2 concurrent subagents

Inputs

ArgRequiredDescription
targetNoFile or file:line to golf
--dry-runNoPreview only, no changes
--searchNooff, quick (default), or full — LSP lemma replacement pass
--max-delegatesNo2 — max concurrent golfer subagents (preflight must pass first)

Actions

  1. Verify Build - Ensure code compiles before optimizing
  2. Find Patterns - Detect golfable patterns (in policy order: directness → structural → conditional):
    lean4-skills-find-golfable [file] --filter-false-positives
    
    For direct-proof discovery when --search is enabled or syntactic pass stalls:
    lean4-skills-find-exact-candidates [file]
    
  3. Exact-Collapse Pass (bounded) — For apply/exact chain anchors from lean4-skills-find-golfable:
    • Mechanical (≤30 anchors/file): Construct collapsed exact from tactic structure → lean_multi_attempt + lean_diagnostic_messages baseline check (no new diagnostics, no sorry increase). Accept if the replacement is more direct or clearer. Reject if it introduces heavier automation (simpa, rwa, broad simp) to replace an explicit proof, if term length exceeds ~80 chars, if dot-chain depth > 2, or if it removes meaningful intermediate names. A 1-line saving that raises inference burden is not a win.
    • Exploratory (when --search≠off; consumes --search budget): On remaining single-goal anchors, build candidate exact terms from chain lemmas + local hypotheses + dot-notation rewrites → lean_multi_attempt + diagnostics check. Probe caps are phase-local: quick ≤5 probes/file; full ≤15 probes/file; ≤2 probes/anchor. Time budget is shared with lemma replacement (step 4): quick 30s total, full 60s total across both phases.
    • Skip: calc, cases/induction, multi-goal branches, blocks >7 lines, semicolon-heavy (>3), blocks with have/refine. constructor chains are handled by the existing instant-win rule, not this pass.
  4. Lemma Replacement (if --search=quick or full):
    • Run LSP searches per candidate; test with lean_multi_attempt
    • quick: 1 search, ≤2 candidates; full: 2 searches, ≤3 candidates; ≤3 search calls; uses remaining shared time budget
    • Accept the best passing replacement by the scoring order below
    • If a replacement would require a statement change → reject the candidate, keep the existing proof, and report the proposed change for explicit approval (golf never changes statements; an unsuitable candidate is not evidence the statement is wrong); if it needs a multi-file or strategy-level refactor → hand off to /lean4:refactor by returning the proposal to the parent (no cross-file edits here); hand off to axiom-eliminator only for axiom/assumption hygiene
  5. Verify Safety - Check usage before inlining:
    lean4-skills-analyze-let-usage [file] --line [line]
    
  6. Apply - Make changes with lean_diagnostic_messages after each; lake build for final verification
  7. Report - Show savings and saturation status

Golfing Patterns

Instant Wins (Always Apply)

BeforeAfterNotes
ext x; rflrfl
simp; rflsimp
constructor; exact h1; exact h2exact ⟨h1, h2⟩
apply f; exact hexact f h
by exact ttAt declaration RHS / term-wrapper positions only — not inside tactic blocks

Safe with Verification

PatternCondition
Inline letUsed ≤2 times
Inline haveUsed once, ≤1 line

Skip (False Positive Risk)

  • Let bindings used 3+ times
  • Complex have blocks
  • Named hypotheses in error messages

Golfing Policy

Semicolons: Never introduce naked ; as a golfing transform. <;> may be introduced only when applying a single identical tactic to literally identical goals (its intended purpose — e.g., constructor <;> simp); do not use it to compress non-identical branches. When counting line savings, each ;-separated tactic counts as its own line — semicolons do not reduce line count. If existing code uses ; or <;>, do not count those lines as savings and do not target rewrites that preserve or expand semicolon usage.

Scoring order. A candidate is a win iff correct and not rejected (see below). Among wins, prefer in this order: (1) more direct proof shape, (2) lower inference/search burden, (3) better performance/determinism, (4) shorter code. Length is still a core goal of golf — it is a tiebreaker among acceptable proofs, not a license to introduce heavier tactics. Inference burden and performance are judged heuristically by the tactic complexity ladder, not by measurement: rfl/exact < rw/apply < simp only < simpa/rwa < broad simp/decide/omega/grind.

Hard reject if: introduces naked ; · introduces <;> on non-identical goals (per semicolon policy) · moves UP the complexity ladder for only a 1-line win · removes meaningful names · collapsed term > ~80 chars or dot-chain > 2 · replaces direct proof with terminal simp only without user opt-in · replaces exact with simpa/rwa unless exact fails.

Terminal simp only caveat: Narrowing non-terminal simp → simp only is always valid (the FlexibleLinter flags non-only simp before rigid tactics). But terminal simp vs simp only is a style split — some projects prefer terminal simp for resilience to simp-set changes (the converse concern). Do not narrow terminal simp or introduce terminal simp only without user confirmation. In non-interactive/delegate mode, skip unless project style already uses it nearby.

Minimum value filter: 1-line savings only worth surfacing if (a) zero-risk syntax cleanup (e.g., by exact → t) or (b) also improve clarity or performance.

simpa/rwa direction rule:

  • Never replace exact t with simpa using t unless exact t fails.
  • Only replace simpa using with exact when the elaborated target is already literally the same type — do not guess.
  • simpa using is only a win when it deletes surrounding boilerplate (an extra rw, change, or simp block).
  • In coercion-heavy or subtype-heavy proofs, test exact first; only fall back to simpa using if transport is actually needed.
  • Treat calc steps, subtype witnesses, and cast/transport goals as unsafe-by-default for wrapper removal (simpa→exact, rwa→rw+exact).
  • Note: simp using is NOT a drop-in for simpa using in term positions — they have different semantics.

Output

## Golf Results

**Meaningful simplifications:** 3 (directness improvements)
**Performance cleanups:** 1 (simp narrowing)
**Syntax cleanups:** 1 (by exact → term)
**Skipped:** 2 (1 safety, 1 marginal compression)
**Build status:** ✓ passing
**Total savings:** 8 lines (~12%)

Optional next step: run `/lean4:checkpoint` to save progress.

Saturation

Stop when success rate < 20% or last 3 attempts failed.

Safety

  • Requires passing build to start
  • Reverts immediately on build failure
  • Does not create commits (use /lean4:checkpoint)
  • --search replacements follow same revert-on-failure policy

Bulk Rewrite Safety

sed/bulk rewrites activate automatically when ≥4 whitelisted syntax-only patterns are found at declaration RHS / term-wrapper positions in a file; never inside tactic blocks or calc blocks. The preview step (step 1 below) is the user confirmation gate. Default when <4 candidates: individual edits with per-edit verification.

Whitelist: := by exact t → := t, by rfl → rfl

Skip rules: Skip candidate when the replacement TERM introduces a nested tactic-mode boundary (a by at non-top-level position in the term). If context classification is uncertain, skip the rewrite — never force.

Bulk workflow (effective per-run limit: min(10 replacements/file, 3 hunks × 60 lines); overflow recomputed on next invocation — no persistent queue):

  1. Preview — match count + 3-5 sample hunks; user confirms before applying
  2. Batch apply — per-file, up to min(10, hunk/line cap) replacements
  3. Validate — capture baseline diagnostics on touched files before batch; after batch run lean_diagnostic_messages(file) and compare: new diagnostics vs baseline + sorry-count delta
  4. Auto-revert — if sorry count increases or new diagnostics appear relative to baseline, revert batch immediately
  5. On permission denial — abort bulk mode, continue with individual edits

Never bulk-rewrite: semantic patterns, proof structure changes, let/have inlining, anything inside tactic blocks or calc blocks

Delegation Execution Policy

Golf follows the shared Delegation Execution Policy of run-contract/v1 — preflight, permission gate, bounded concurrency (--max-delegates, default 2), exclusive ownership, fallback contract, and pre-collected context. These golf-specific batching rules layer on top when delegating to proof-golfer subagents:

  1. Batch by value — Batch 1: high-priority instant wins, then prompt user for checkpoint; Batch 2: medium-priority; ask before continuing
  2. After each batch — diagnostics summary, changed files, Continue? [yes/no]
  3. One plan message per batch — no repeated "launching more agents" narration

See Also

  • /lean4:review - See opportunities (read-only)
  • /lean4:refactor - Strategy-level simplification (before golf)
  • /lean4:checkpoint - Save after golfing
  • proof-golfing.md
  • Examples

Lean4 Learn

Interactive teaching and mathlib exploration. Adapts to beginner, intermediate, and expert audiences.

Usage

/lean4:learn                                 # Start conversational discovery
/lean4:learn Finset.sum                      # Auto-detect mode from topic
/lean4:learn --mode=repo                     # Explore current project
/lean4:learn --mode=mathlib topology         # Navigate mathlib for a topic
/lean4:learn --style=socratic --interactive  # True Socratic method
/lean4:learn --style=game --track=nng-like   # Game-style natural numbers track
/lean4:learn --source ./paper.pdf            # Learn from a paper/PDF
/lean4:learn --presentation=informal "Bolzano-Weierstrass"  # Prose, Lean-backed
/lean4:learn --output=scratch                # Write results to scratch file
/lean4:learn --style=socratic --adaptive=off  # Socratic, no style/level drift

Invocation Contract

Interpret this command's inputs per the Command Invocation Contract.

Primary path (hook-validated): If a validated-invocation block for this command appears in context, treat it as the authoritative interpretation of parser-decidable inputs and do not re-parse the raw invocation text for those inputs. Start by reading all parser-decided fields from the block. Then, if this command has repo-dependent startup rules (the --mode=mathlib scope coercion depends on local-declaration resolution), apply them using runtime context (LSP, grep). Emit the final Resolved Inputs summary from the combined result. See Validated Invocation Block.

Fallback path (other hosts): If no validated-invocation block is present, parse the raw invocation text against this command's input table before discovery.

Startup requirements:

  1. Emit a Resolved Inputs block with explicit values, defaults, coercions, ignored flags, and startup validation errors.
  2. Refuse to start on startup validation errors.
  3. Validate output paths and overwrite policy before writing anything.

Inputs

ArgRequiredDefaultDescription
topicno—Free-text topic, theorem name, file path, or natural-language claim. If omitted, start conversational discovery; set --mode after first user reply.
--modenoautoauto | repo | mathlib
--levelnointermediatebeginner | intermediate | expert
--scopenoautoauto | file | changed | project | topic
--stylenotourtour | socratic | exercise | game
--outputnochatchat | scratch | file
--outno—Output path. Required when --output=file; startup validation error if missing.
--overwritenofalseAllow overwriting existing files with --output=file. Without flag, existing target → startup validation error.
--interactivenofalseTrue Socratic method (withhold answers, ask questions). Valid only with --style=socratic; ignored with warning otherwise.
--intentnoautoauto | usage | internals | authoring | math. See learn-pathways.md.
--presentationnoautoinformal | supporting | formal | auto. Controls user-facing display, not Lean backing. See learn-pathways.md.
--verifynobest-effortbest-effort | strict. Verification strictness for key claims. See learn-pathways.md.
--trackno—Exercise ladder: nng-like | set-theory-like | analysis-like | proofs-reintro. Valid only with --style=game. See learn-pathways.md.
--sourceno—File path, URL, or PDF to seed learning. See learn-pathways.md.
--adaptivenoonon | off. Controls whether the debate can change style/level. See learn-pathways.md.

Scope defaults by mode (when --scope=auto)

ModeDefault scope
repofile
mathlibtopic

Scope coercions

  • --mode=mathlib + --scope=file|changed|project → warn + coerce to topic, unless topic resolves to a local declaration

Output validation

  • --output=file without --out → startup validation error
  • --output=scratch → .scratch/lean4/learn-<timestamp>.lean (workspace-local). Auto-create .scratch/lean4/ if missing; warn if .scratch/ is not in .gitignore.
  • --output=file with existing target and no --overwrite → startup validation error

Flag validation

  • --intent, --presentation, or --verify with invalid value → startup validation error.
  • --track without --style=game → warn + ignore. --style=game without --track → prompt track picker.
  • --source + --scope=file|changed|project → warn "source overrides scope for initial discovery". Unsupported source type → warn + ask for text excerpt.
  • --adaptive with invalid value → startup validation error. --adaptive=off freezes the Learning Profile: the debate cannot change style or level. Within-style remediation (hint escalation, trying a counterexample instead of repeating an explanation) is unaffected — those don't modify the profile.

Actions

0. Intent Intake

Two-layer contract: All modes are Lean-backed by default. Lean verification is attempted for all key claims — theorem statements, correctness judgments, game pass/fail, and "therefore X" assertions. --presentation controls what is shown, not whether Lean runs. Each key-claim step carries a verification label: [verified], [partially-verified], or [unverified]. Under --verify=strict, never present claims as settled unless verified; on failure after retry, mark blocked and offer: continue conceptually or relax to best-effort. See learn-pathways.md.

Classify learning intent and establish a session Learning Profile: {intent, presentation, verify, style, track, level, adaptive}. --source is per-invocation only (not persisted) unless user explicitly says "continue same source." Explicit flags are used directly; inference is only for auto values. Announce resolved intent and presentation, marking each as inferred or explicit. When --presentation=auto: if confidence is high, auto-resolve and announce; if ambiguous, ask: "Informal (prose, Lean-backed), supporting (prose + Lean snippets), or formal (Lean shown)?" Profile persists within the current conversation; explicit flags on later turns override and update it. Precedence (applied before validation rules): explicit flags > stored profile > inference. If explicit --intent conflicts with source-inferred intent, honor explicit and warn about mismatch. If explicit --mode conflicts with resolved intent (explicit or inferred), honor explicit mode and warn. See learn-pathways.md for inference rules and the full behavior matrix.

1. Mode Resolution

When --mode=auto, resolve by tie-breaking order:

  1. If topic resolves to an existing .lean file path → repo
  2. Resolve topic against project-local declarations (via Grep/lean4-skills-find-usages). Local wins — if both local and mathlib match, prefer local → repo
  3. Check mathlib namespace/theorem names (via lean_local_search, lean_leanfinder/lean_leansearch, lean_loogle) → mathlib
  4. If topic is a natural-language mathematical statement → suggest /lean4:formalize
  5. If ambiguous → ask the user

When no topic is provided, enter conversational discovery and set --mode after the user's first reply.

Intent bias: After tie-breaking, cross-check against intent. --intent=math biases toward /lean4:formalize — suggest it, do not enter formalize mode. --intent=internals biases toward repo. If bias conflicts with tie-breaking and no explicit --mode, ask the user.

2. Discovery (per mode)

repo: Glob/Grep (file survey) → Read (targeted content) → lean4-skills-find-usages (dependency pass). Build a map: key files, declarations, dependency flow, where proofs live.

mathlib: lean_local_search → one semantic search (lean_leanfinder for goal/proof-state shaped queries, lean_leansearch for natural-language concept queries) → lean_loogle (type-pattern gaps). Present canonical lemmas, type signatures, minimal usage examples.

Source-aware: When --source is provided, ingest first: .lean → Read; PDF → Read (for large PDFs, read abstract/intro/theorems first, ask which section); .md/.txt → Read directly; URL → web fetch (if unavailable, ask user for excerpt); other types → warn + ask for text excerpt. Extract key definitions, theorem statements, notation. Use as seed for the resolved mode's discovery. On ingestion failure: ask user for relevant excerpt and proceed.

Fallback rule: If a tool is unavailable or rate-limited, continue with the next tool in order, label affected output [unverified] or [partially-verified], and note the fallback. If Lean verification fails after retry: attempt to revise; if revision also fails, state that verification is pending/failed and offer: continue conceptually or switch to formal mode.

3. Explanation

Present findings at the user's --level in the user's --style:

  • tour: Narrated walkthrough, explains as it goes.
  • socratic: Guided discovery with prompts. If --interactive, withhold answers and ask user questions first — delay direct solutions until user has engaged.
  • exercise: Present a challenge, let user attempt, then explain. Always end with a Lean-verified reference solution.
  • game: Structured progression through --track levels. Verification is always Lean-backed (lean_goal + lean_multi_attempt + clean lean_diagnostic_messages). In informal: user argues informally; agent restates its interpretation before checking, reports result without showing Lean unless asked. In supporting: user argues informally; agent shows the Lean translation after verification. In formal: user writes Lean proofs directly. If no --track, present track picker. See learn-pathways.md.

4. Depth Check

Offer the depth-check menu:

  • show source / show proof state / show alternative approach
  • show Lean backing (on-demand transparency into the verification layer)
  • go deeper / switch mode / broaden scope
  • draft a skeleton → suggest /lean4:draft (skeleton only)
  • formalize a specific result → suggest /lean4:formalize (draft + prove)
  • save to scratch / write to file (mid-session output actions — --output is part of the loop, not just startup config)

5. Pedagogical Self-Debate

Without this step, learn responds in whatever style was set at the start — if a learner is struggling, it keeps explaining the same way; if they're bored, it doesn't notice. This step makes learn adaptive: it reads what the user's response reveals about their understanding and adjusts pace, method, and depth before each reply.

After receiving the user's response (answer attempt, question, menu choice, or freeform message) and before formulating a reply, reason from three advisor perspectives to choose the best response strategy:

  • Pace Advisor: "Is the learner ready to advance, or do they need consolidation? What does their response reveal about their current understanding level?"
  • Method Advisor: "Is the current style still right, or should we switch? Would a different framing (intuitive vs. formal vs. example-driven) serve them better here?"
  • Depth Advisor: "Should I go deeper on this subtlety, surface a related concept, or redirect? Am I risking overloading them?"

Pick the best strategy based on the learner's current profile ({intent, level, style, track}) and what their response revealed. Tiebreak: prioritize the learner's momentum (keep them engaged) over completeness.

The debate is internal reasoning. Whether the strategy note is surfaced depends on --presentation:

  • informal / supporting: Show a one-sentence *Pedagogy: ...* note before the reply.
  • formal: Suppress the note by default (code-first output). Surface only if the user requests it via "show Lean backing" or asks why the approach changed.

Pedagogy: [one sentence — e.g., "Hinting rather than revealing since you're close" or "Switching to a worked example since you've been stuck on the same concept twice."]

When to run:

  • Mandatory in --style=game and --style=socratic modes.
  • Optional (skip for trivial menu navigation) in --style=tour and --style=exercise modes.
  • When --level=expert and --style=tour, may be omitted for straightforward navigation responses.

Key constraints:

  • Do NOT trigger new Lean verification here — reason about teaching strategy only, using already-discovered information.
  • In --style=game: follow the hint escalation ladder from the 1st failure (directional hint → specific hint → full answer with explanation). The Pace Advisor must flag repeated failure (2+) and may offer to regress to an easier level.
  • If the user's last 2 responses reveal the same misunderstanding, the debate MUST flag this and the chosen strategy MUST switch approach.
  • The debate may suggest style or level updates mid-session, but only for values that were inferred or defaulted. If the user explicitly set a flag (e.g., --style=socratic), the debate must not override it — instead, suggest the change and let the user confirm.
  • When --adaptive=off, the debate must not modify style or level in the Learning Profile. Within-style remediation (hint escalation, framing switches, counterexamples) is unaffected — the debate adapts how it teaches within the locked style, but cannot change which style or level is active.

See Pedagogical Self-Debate for the full reference.

6. Iterate

After step 5, respond using the chosen strategy. Return to step 4 (Depth Check) for the next turn. In exercise mode, the next exercise replaces the depth-check menu as the primary loop driver. On mode switch or topic change, return to step 2 (Discovery). Continue until the user is satisfied or switches mode.

Output

Output format follows --presentation: informal → prose with math notation (no Lean blocks unless user requests "show Lean backing"); supporting → prose with selective Lean snippets; formal → Lean code blocks as primary content. In scratch or file mode, additionally write a .lean file regardless of presentation.

Safety

  • Read-only by default. repo and mathlib modes never write files unless --output requests it.
  • No silent mutations. Prefer LSP tools (lean_goal) over file writes for compilation checks. If LSP unavailable and temp file needed for internal compilation, write only under /tmp/lean4-learn/, auto-cleanup after use, warn user before writing.
  • No commits. /learn never commits. --output=file writes but does not stage or commit.
  • Path restriction. User-requested outputs (--output=file, --output=scratch) restricted to workspace root (scratch uses .scratch/lean4/). Reject path traversal (../) or absolute paths outside workspace. Internal temp files may use /tmp/lean4-learn/.
  • Overwrite protection. --output=file with existing target requires --overwrite; otherwise startup validation error.
  • Scope guardrails. --scope=project in repo mode with >50 .lean files → warn with count, ask to narrow. In non-interactive contexts (e.g., LLM-invoked), default to "no" (do not proceed with large scope).
  • All guardrails.sh rules apply.

See Also

Lean4 Prove

Guided, cycle-by-cycle theorem proving. Asks before each cycle, supports deep escalation, and checkpoints your progress.

Usage

/lean4:prove                         # Start guided session
/lean4:prove File.lean               # Focus on specific file
/lean4:prove --repair-only           # Fix build errors without filling sorries
/lean4:prove --deep=stuck            # Enable deep escalation when stuck

Invocation Contract

Interpret this command's inputs per the Command Invocation Contract.

Primary path (hook-validated): If a validated-invocation block for this command appears in context, treat it as the authoritative interpretation of parser-decidable inputs and do not re-parse the raw invocation text for those inputs. Start by reading all parser-decided fields from the block. Emit the final Resolved Inputs summary from the block values. See Validated Invocation Block.

Fallback path (other hosts): If no validated-invocation block is present, parse the raw invocation text against this command's input table before Phase 1.

Startup requirements:

  1. Emit a Resolved Inputs block with explicit values, defaults, coercions, ignored flags, and startup validation errors.
  2. Refuse to start on startup validation errors.
  3. Persist any user-approved adjustments as session state so later cycles follow the updated configuration rather than the initial prose alone.
  4. With --persist: after the checks above and a valid first dispatch, set LEAN4_RUN_PERSIST_STATE to a fresh invocation-private path (mktemp -d + a not-yet-existing file) and run lean4-skills-run-persist start before any proof edit; a startup-error is a startup validation error. Report the run_id in Resolved Inputs and follow Run Persistence at every review, cycle boundary, and stop; for each inline edit: check → edit → advance (changed entries only) → run-persist progress --payload (parent knowledge, no citation; fallbacks reflect reported knowledge only). With --prior-run, first run run-persist reuse, show the drift report (drift and uncovered files), obtain approval of that report (its token), run-persist custody, and pass --reuse-report (and, when the report was not a match, --approve <token>) to start, which re-derives custody (Prior-Run Reuse).

Inputs

ArgRequiredDefaultDescription
scopeNoallSpecific file or theorem to focus on
--repair-onlyNofalseFix build errors only, skip sorry-filling
--planningNoaskask (prompt at startup), on, or off
--review-sourceNointernalinternal, external, both, or none
--review-everyNocheckpointN (sorries), checkpoint, or never
--checkpointNotrueCreate checkpoint commits after each cycle
--deepNonevernever, ask, stuck, or always
--deep-sorry-budgetNo1Max sorries per deep invocation
--deep-time-budgetNo10mAdvisory: scopes deep-mode subagent work. Not tracked or enforced.
--max-deep-per-cycleNo1Max deep invocations per cycle
--deep-snapshotNostashV1: stash only
--deep-rollbackNoon-regressionon-regression, on-no-improvement, always, or never
--deep-scopeNotargettarget or cross-file
--deep-max-filesNo1Max files per deep invocation
--deep-max-linesNo120Max added+deleted lines per deep invocation
--deep-regression-gateNostrictstrict (auto-abort on regression) or off
--batch-sizeNo1Sorries to attempt per cycle
--commitNoaskask (prompt before each commit), auto, or never
--golfNopromptprompt, auto, or never
--persistNofalseWrite this run to the run store (dispatches, handoffs, notes, reviews, Replan summaries; one run per invocation). Off by default — existing invocations are unchanged. Platform support is a startup capability check. See cycle-engine: Run Persistence.
--run-storeNo—Storage root override; requires --persist (--run-store without --persist → startup validation error). Precedence: --run-store → $LEAN4_RUN_STORE → <project-root>/.lean4-skills.
--prior-runNo—Reuse a selected prior run's history (explicit id; never "latest"; resolved within the selected store); requires --persist (--prior-run without --persist → startup validation error). See cycle-engine: Prior-Run Reuse.

Startup Behavior

If key preferences are not passed via flags, ask once at startup:

Planning preference:

Start with a planning phase? (Recommended for new sessions)

  1. Yes — discover state, set scope, show plan (recommended)
  2. No — skip planning, start immediately

Review source:

How should reviews be conducted?

  1. Internal — planner mode reviews and can apply fixes (recommended)
  2. External — interactive handoff for advice only
  3. Both — internal first, then external advice
  4. None — no automatic reviews

If --planning=off, skip initial planning but stuck-triggered replan is still mandatory (see Stuck Definition).

Actions

Each cycle has 6 phases — see cycle-engine.md for shared mechanics.

Phase 1: Plan

See cycle-engine: LSP-First Protocol. Discover sorries via LSP, search with up to 3 tools (~30s), show plan and get confirmation.

Phase 2: Work (Per Sorry)

See sorry-filling.md and cycle-engine: LSP-First Protocol.

  1. Refresh goal → search → generate 2-3 candidates → test via lean_multi_attempt
  2. Preflight falsification for decidable/finite goals (30-60s max)
  3. Tactic cascade if no candidate passed
  4. Validate via lean_diagnostic_messages; if "Try this" suggestion appears, resolve with lean_code_actions, then re-run lean_diagnostic_messages to confirm clean
  5. Stage & commit (see below)

Staging rule: If --commit=never, skip staging and committing entirely. Otherwise, stage only the files touched by this fill (git add <edited files>) — never git add -A or broad patterns.

Touched-file reporting: At session end, report files_touched (files edited) and scratch_files_created (any /tmp files used for experiments).

Commit behavior (unique to prove): Show diff and ask before each commit when --commit=ask (default):

Commit this? [yes / yes-all / no / never]
  • yes — commit, prompt again next time
  • yes-all — switch to auto for rest of session
  • no — unstage (git reset HEAD <files>), skip this commit
  • never — unstage, skip all remaining commits for session

Constraints: Max 3 candidates per sorry, ≤80 lines diff, NO statement changes, NO cross-file refactoring (fast path). Declaration headers are immutable — if deep mode suggests a header change, it must stop and recommend /lean4:formalize.

Phase 3: Checkpoint

See cycle-engine: Checkpoint Logic. Stage only files from accepted fills; exclude declined fills and rolled-back deep invocations.

Phase 4: Review

See cycle-engine: Review Phase. Runs at configured --review-every intervals.

Phase 5: Replan

See cycle-engine: Replan Phase.

Phase 6: Continue / Stop

Prompt the user after each full cycle:

Cycle complete. Filled N/M sorries this cycle.
- [continue] — run next cycle
- [stop] — save progress and exit
- [adjust] — change flags for next cycle

Never auto-start the next cycle. Always ask.

At a stop or stuck boundary, emit the complete run-contract/v1 handoff record — every required field, so a human or another agent can continue in one pass. Command-specific mapping: a filled sorry → contributes to status: solved; a stuck sorry → status: stuck with the blocker fields; a user/budget stop → status: stopped with the matching stop_reason and null blocker fields. Before relaunching, obey the rerun guard.

Deep Mode

Bounded subroutine for stubborn sorries. Enabled via --deep. Default: never.

Modes: never | ask (prompt first) | stuck (auto on stuck) | always (auto on any failure).

Statement changes are NOT permitted. Declaration headers are immutable (header fence). If deep concludes the statement is wrong, it emits next_action = redraft but does not rewrite. Suggest /lean4:formalize for statement work. Deep allows multi-file refactoring and helper extraction within the header fence.

Safety: Deep creates a path-scoped pre-deep snapshot (--deep-snapshot), enforces scope/diff budgets (--deep-scope, --deep-max-files, --deep-max-lines), and auto-rolls back on regression (--deep-regression-gate). Rollback marks the sorry as stuck with reason.

Validation: Deep-safety flags are validated at startup; invalid values produce descriptive errors.

When dispatching sorry-filler-deep, include pre-collected MCP context per cycle-engine.md § Pre-flight Context.

See cycle-engine.md for full semantics, definitions, and prove/autoprove comparison.

Header Fence

Declaration headers (everything from theorem/def/lemma through := by) are snapshotted at deep entry. At each checkpoint, the engine compares headers against the snapshot. Any header change triggers immediate rollback and marks the sorry as stuck with "deep: header fence — declaration header modified". The prove phase itself never modifies headers; statement changes require /lean4:formalize.

Stuck Definition

A sorry is stuck when: same failure 2-3x, same build error 2x, no progress 10+ min, or empty LSP search 2x.

When stuck: review → fresh plan → present for approval ([yes / no / skip]). On decline: offer counterexample/salvage pass. Handoff must include LSP queries attempted, top candidates, and lean_multi_attempt outcomes.

See cycle-engine.md for full detection logic and blocker signature computation.

Falsification Artifacts

When a statement is disproved, create T_counterexample and T_salvaged lemmas. Avoid proving ¬ P unless user chose negation policy.

See cycle-engine.md for Lean code templates.

Completion

Report filled/remaining sorries, then prompt:

## Session Complete

Filled: 5/8 sorries
Counterexamples: 1 (T_counterexample)
Salvaged: 1 (T_salvaged)
Commits: 7 new
Run: 20260909T120000Z-7484bfa8 (stored; final handoff 20260909T120000Z-7484bfa8#8)   # with --persist

Create checkpoint? (per-file + project build, axiom check, commit)
- [yes] — run /lean4:checkpoint
- [no] — keep commits as-is

Golf prompt (if --golf=prompt or default):

Run /lean4:golf on touched files?
- [yes] — golf each file
- [no] — skip golfing

If --golf=auto, run golf automatically. If --golf=never, skip entirely.

Repair Mode

Compiler-guided repair is escalation-only — not the default response to a first failure. Auto-invoke only when compiler errors are the active blocker: same blocker 2x, same build error 2x, or 3+ errors in scope. Apply direct fixes first for straightforward errors. Budgets: max 2 per error signature, max 6 total per cycle. No improvement after 2 attempts → stuck + review + replan.

When dispatching proof-repair, include pre-collected MCP context per cycle-engine.md § Pre-flight Context.

See cycle-engine.md for full policy and compilation-errors.md for error-specific fixes.

Safety

Guardrailed git commands are blocked. See cycle-engine.md for the full list.

  • Line width. Follow mathlib 100-char line width — do not wrap lines at 80 when they fit within 100.
  • Docstring policy — Rule A (existing declarations). Prove edits existing declarations, so existing docstrings remain protected: never rewrite an existing docstring; only inline comments in proof bodies may be adjusted. This is the SKILL.md default for any workflow mutating existing decls — the escape hatch is an explicit user request. Statement/signature changes route to /lean4:formalize.

See Also

  • /lean4:draft - Draft Lean declaration skeletons
  • /lean4:autoformalize - Autonomous end-to-end formalization
  • /lean4:autoprove - Autonomous multi-cycle proving
  • /lean4:disprove - Guided counterexample search with certified refutation
  • /lean4:checkpoint - Manual save point
  • /lean4:review - Quality check (read-only)
  • /lean4:refactor - Strategy-level proof simplification
  • /lean4:golf - Optimize proofs
  • Cycle Engine - Shared prove/autoprove mechanics
  • Examples

Lean4 Refactor

Strategy-level proof simplification: find better proof approaches, leverage mathlib, and extract reusable helpers. Complements /lean4:golf (tactic-level optimization) and /lean4:review (read-only audit).

Mutating command: Edits files with user approval. Does not change theorem statements, introduce axioms, or create commits.

Escalation target for /lean4:golf. Golf performs local, statement-preserving proof cleanup, potentially across many proofs; when a golf replacement needs a multi-file or strategy-level change — extracting a helper, moving declarations between files, switching the proof approach — golf hands off here. Axiom/assumption hygiene goes to the axiom-eliminator agent instead; a needed statement change is reported to you rather than applied by either.

Usage

/lean4:refactor File.lean                  # Refactor all proofs in file
/lean4:refactor File.lean:149              # Refactor proof at line 149
/lean4:refactor --scope=changed            # Refactor files modified since last commit
/lean4:refactor --scope=changed --dry-run  # Report opportunities without editing

Inputs

ArgRequiredDescription
targetNoFile or File.lean:line
--scopeNofile (default with target), changed (default without target)
--dry-runNoReport only, do not edit
--searchNoquick (default) or full (exhaustive mathlib search)
--extract-helpersNoon (default) or off (skip helper extraction)

Scope Behavior

InputScope
File.leanAll proofs in file
File.lean:149Single proof containing line 149
No target--scope=changed (files modified since last commit)
--scope=changedFiles modified since last commit

Line target: Identifies the enclosing theorem/lemma/def containing the given line and refactors that proof only.

Large-run confirmation: When --scope=changed touches >5 files or >20 opportunities, confirm before proceeding.

Preconditions

  • Target proofs must compile (no sorries, no build errors in scope)
  • Run /lean4:prove or /lean4:autoprove first if there are open sorries

Refusal: If preconditions are not met:

⚠️  Cannot refactor: File.lean has 2 sorries and 1 build error.
Run /lean4:prove first, then retry /lean4:refactor.

Actions

  1. Audit — Read target proofs, identify repeated patterns, long proofs (>30 lines), hand-rolled arguments, case splits replaceable by congr/EqOn/EventuallyEq, thin definition APIs
  2. Search — For each opportunity, search mathlib via LSP-first protocol. --search=quick: up to 2 LSP queries per opportunity. --search=full: up to 5 queries with module exploration.
  3. Plan — Present findings with estimated impact:
    ## Refactor Plan — File.lean
    ### Strategy Improvements
    1. [proof] (line N): [current] → Use [mathlib lemma] (saves ~N lines)
    ### Helper Extraction
    1. [pattern] — Nx (lines ...) → Extract `helper_name`
    ### Estimated Impact
    - Lines before: N → after: ~N | Helpers: N | New mathlib lemmas: N
    
  4. Approval — Ask before each batch (--dry-run stops here). A batch groups opportunities within a single proof or closely related proofs. Prompt: Apply batch N (M changes)? [yes / skip / stop] — yes applies, skip moves to next batch, stop ends the session.
  5. Apply — Edit files, verify with lean_diagnostic_messages after each batch; revert batch on any new diagnostic or sorry increase
  6. Verify — lake lean <file> file gate (run from project root; it builds the file's imports first, so a cross-file batch cannot false-fail against a stale .olean — see File Gate Scope); lake build project gate if multi-file. If final gate fails, revert all batches applied in this session.
  7. Report — Summarize changes applied, helpers extracted, line count delta

See proof-simplification for the strategy guide (congr/EqOn patterns, generalization checklist, file-level audit).

Helper scope defaults: Single use inside one proof → local (have / local helper). Reused within one file → private theorem. Public/non-private → only with explicit user approval or clear existing API reason.

Safety

  • Does not change theorem/lemma statements
  • Does not introduce axioms
  • Does not create commits
  • Asks before each batch of edits
  • Reverts batch on per-batch verification failure; reverts all session batches on final gate failure
  • Compiled proofs only (refuses files with sorries or build errors)
  • Follow mathlib 100-char line width — do not wrap lines at 80 when they fit within 100

See Also

Lean4 Review

Read-only review of Lean proofs for quality, style, and optimization opportunities.

Non-destructive: Files are restored after analysis.

Usage

/lean4:review                              # Review changed files (default)
/lean4:review File.lean                    # Review specific file
/lean4:review File.lean --line=89          # Review single sorry
/lean4:review File.lean --line=89 --scope=deps  # Review sorry + its dependencies
/lean4:review --scope=project              # Review entire project (prompts)
/lean4:review --mathlib-review             # Force the mathlib-review bar (Layer 2)

Invocation Contract

Interpret this command's inputs per the Command Invocation Contract.

Primary path (hook-validated): If a validated-invocation block for this command appears in context, treat it as the authoritative interpretation of parser-decidable inputs and do not re-parse the raw invocation text for those inputs. Start by reading all parser-decided fields from the block. Emit the final Resolved Inputs summary from the block values. See Validated Invocation Block.

Fallback path (other hosts): If no validated-invocation block is present, parse the raw invocation text against this command's input table before acting.

Startup requirements:

  1. Emit a Resolved Inputs block with explicit values, defaults, and any ignored flags — including the effective Layer-2 activation decision and its source (flag, repository_kind, contributing_upstream, the helper's validated intent.source, or helper-failure; see Mathlib Review Layer).
  2. Refuse to start on startup validation errors — including passing both --mathlib-review and --no-mathlib-review (--mathlib-review with --no-mathlib-review → startup validation error).

Inputs

ArgRequiredDescription
targetNoFile or directory to review
--scopeNosorry, deps, file, changed, or project
--lineNoLine number for single-sorry scope
--codexNoExternal review via Codex (interactive handoff)
--llmNoUse llm CLI with model
--hookNoRun custom analysis script
--jsonNoOutput structured JSON for external tools
--modeNobatch (default) or stuck (triage)
--mathlib-reviewNoForce the Layer-2 mathlib-review bar at full strictness, overriding project-context detection. Mutually exclusive with --no-mathlib-review.
--no-mathlib-reviewNoForce Layer-2 findings to advisory, overriding project-context detection. Mutually exclusive with --mathlib-review.

Scope Behavior

Scope levels:

ScopeDescription
sorrySingle sorry at --line (requires target file + --line)
depsSorry + same-file helpers and directly referenced lemmas (requires target file + --line)
fileAll sorries in target file
changedFiles modified since last commit (git diff)
projectEntire project (requires confirmation)

Defaults:

  • No args → --scope=changed
  • Target file provided → --scope=file
  • Target + --line → --scope=sorry
  • Triggered by prove/autoprove → matches current focus (sorry or file)

Note: Scope filtering is implemented by the reviewing agent, not the underlying scripts. The agent reads script output and filters results to match the requested scope.

Project-wide confirmation:

⚠️  This will review the entire project.
Proceed? (yes / no)

Output header always shows scope:

## Lean4 Review Report
**Scope:** Core.lean:89 (single sorry)

Review Modes

Batch mode (default):

  • Purpose: "What changed in this batch" + basic hygiene — full review report with all sections
  • Use: Regular cadence reviews, manual quality checks

Stuck mode:

  • Trigger: prove/autoprove invokes stuck mode per its detection triggers when no progress is detected. Can also be invoked manually.
  • Purpose: "What's blocking progress on current focus" — top 3 blockers with actionable next steps
  • Lightweight: Skips full golf analysis and complexity metrics; focuses on blockers only

Stuck mode output format:

## Stuck Review — Core.lean:89

**Primary blocker class:** missing library lemma

**Top 3 blockers:**
1. Missing lemma about tendsto_atTop → search Mathlib.Topology.Order
2. Typeclass instance missing for MeasurableSpace β → supply the intended structure (`have : MeasurableSpace β := borel β` only when `[TopologicalSpace β]` is available and Borel is intended; otherwise import the declaring module or report the missing prerequisite); `inferInstance` would re-run the failed search
3. Proof too long (38 lines) → extract helper lemma first

**Evidence:**
- searches — `lean_leansearch "tendsto atTop of monotone"`, `lean_loogle "Tendsto _ atTop"`
- returned lemmas — `tendsto_atTop_mono`, `Tendsto.comp`
- attempts — `exact tendsto_atTop_mono h` (type mismatch), `apply Tendsto.comp` (unification goal)

**Flag:** Statement may be false (optional — see below)

**Recommended next action:** Search for tendsto variants in Topology/Order
**Why first:** the top blocker is a missing lemma, so search dominates more tactic attempts
**next_action:** continue

The Primary blocker class value uses the Blocked-Goal Triage vocabulary from sorry-filling.md (definitional equality / missing intro-constructor-cases / missing rewrite / arithmetic / missing library lemma / typeclass-coercion-elaboration / needs helper lemma) and classifies the top blocker — the listed blockers may span classes. The Evidence block records the searches attempted, top candidate lemmas returned, and lean_multi_attempt outcomes required by the cycle-engine stuck-handoff contract. This block supplies the evidence and blocker vocabulary that the parent wraps into a run-contract/v1 handoff record — it is not itself a complete record (it carries no schema/record/status/blocker_signature/custody fields), and its human blocker phrases map to the record's kebab-case blocker_class enum. These fields are part of the human-readable stuck report only — they are not represented in the lean4-review-output/v2 interchange contract, which carries per-finding suggestions, not stuck-triage narrative.

next_action classification (stuck mode): continue (retryable), deep (needs escalation), repair (compiler blocker), redraft (statement-shape blocker), golf (sorry-free), stop (no path). Informational unless autoprove outer loop is active.

Falsification flag: Include when analysis suggests statement may be false:

  • Decidable goal that failed decide or native_decide
  • Repeated proof failures with no viable approach
  • prove/autoprove passed falsification signal from earlier preflight

Example: **Flag:** Statement may be false (decidable goal failed decide)

Blocker priority (stuck mode):

  1. Build errors/diagnostics in focus
  2. Sorries on critical path (target line or its dependencies)
  3. Custom axioms introduced in focus
  4. Long/fragile proofs (performance risk)
  5. Falsification signals (decidable goal that failed decide, repeated proof failures)

For strategy-level proof simplification (mathlib leverage, helper extraction, congr-lemma patterns), run /lean4:refactor or /lean4:refactor --dry-run.

Actions — Layer 1: core proof hygiene (always-on)

The agent selects files based on scope, then runs these analyses (per file or directory):

  1. Build Status - lake build (project-wide); for scoped review (--scope=file), use lean_diagnostic_messages(file) + lake env lean <path/to/File.lean> (run from project root) first
  2. Sorry Audit - lean4-skills-sorry-analyzer <target> --format=json --report-only
  3. Axiom Check - lean4-skills-check-axioms-inline <target> --report-only
  4. Style Review - Check mathlib conventions (naming, structure, tactics, 100-char line width). Flag lines wrapped under 100 chars that fit on one line (common: mkAppM calls, short struct literals, single-expression tactic lines).
  5. Golfing Opportunities - lean4-skills-find-golfable <target> --filter-false-positives
  6. Complexity Metrics - Proof sizes, longest proofs, tactic patterns

Stuck mode: Steps 5–6 are skipped; focus is on blockers (steps 1–4) for quick triage.

Layer 1 findings are always blockers-or-hygiene for the current project. The second-pass mathlib-review layer below runs on top of them.

Mathlib Review Layer (Layer 2)

A second pass surfaces what mathlib's own PR-review guide asks for, in four first-class sections mapped onto the shipped mathlib-review taxonomy (#114) and the category values in lean4-review-schema.json (#115). This layer consumes those references; it does not restate their vocabulary.

  1. Documentation Review — module + declaration docstrings on public API, proof sketches on intricate arguments, cross-references. Categories: docstring, module-doc.
  2. Library Integration Review — duplicate/more-general existing results, file placement, heavier-than-needed imports, lowest sensible module. Categories: file-placement, import-hygiene.
  3. API / Generalization Review — weakest reasonable assumptions, structure-vs-conjunction, blocked generalizations. Categories: api, generalization (settled rule rule_id: vacuous-api, severity: advisory).
  4. Attributes & Instances Review — @[simp] justification, new-instance diamond risk, @[ext], @[reducible]. Categories: attribute, simp, instance.

Layer-2 activation

Layer 2 runs at full strictness (findings alongside Layer-1) only when the work is plausibly aimed at upstream mathlib; otherwise its findings are advisory. Resolve the mode in this order — conflict validation precedes precedence:

  1. Conflict first. Only flags resolving to true participate; an explicit --mathlib-review=false (or --no-mathlib-review=false) equals omission. If both --mathlib-review and --no-mathlib-review resolve to true, refuse to start (one startup validation error) — do not silently pick one.
  2. Explicit true flag wins — skip the helper. If --mathlib-review resolves to true, use full strictness; if --no-mathlib-review resolves to true, use advisory. Do not consult project-context in either case.
  3. Otherwise acquire project context. Run lean4-skills-project-context --from "<target>" (the target file/dir if one was given, else $PWD) and validate the record exactly as /lean4:checkpoint does: schema = project-context/v1; facts.repository_kind a string in mathlib | other-lean | not-lean | unknown; intent.contributing_upstream a string in yes | no | unknown; intent.source a string in env-override | invalid-env-override | remote-heuristic | default. A nonzero exit, unparseable output, or any missing / non-string / out-of-domain field is malformed helper output.
  4. Then precedence on the validated record:
Condition (in order)Layer-2 behaviorSource
--no-mathlib-review trueadvisoryflag
--mathlib-review truefull strictnessflag
facts.repository_kind == mathlibfull strictnessrepository_kind
intent.contributing_upstream == yesfull strictnesscontributing_upstream
any other resolved context (other-lean/not-lean/unknown, no/unknown intent)advisoryintent.source
helper nonzero / unparseable / malformed recordadvisoryhelper-failure

facts.repository_kind (what the repo is) and intent.contributing_upstream (intent) are distinct signals; either independently activates full strictness, and an explicit flag overrides both. The fail direction is toward advisory — the opposite of the checkpoint gate's fail-closed — because a review consumer must never impose mathlib blockers when the context is uncertain. Report the resolved mode and its source in the Resolved Inputs block.

Output labeling (normative)

Advisory Layer-2 findings must be structurally separable from Layer-1 blockers. In human-readable output, render them under a distinct heading (e.g. ### Advisory (mathlib-style)) or label them explicitly as advisory. In lean4-review-output/v2, encode them with severity: advisory (the schema carries severity, not a section heading). Intermixing advisory and blocking findings in one undifferentiated list is insufficient.

Mode × layer:

  • batch × mathlib-targeted: all four Layer-2 sections emit as first-class findings alongside Layer-1.
  • batch × non-mathlib: Layer-2 emits under a separate "Advisory (mathlib-style)" section.
  • stuck × mathlib-targeted: bias toward blockers; allow one Layer-2 blocker when it is the main reason the patch won't survive mathlib review.
  • stuck × non-mathlib: Layer-1 blockers only; Layer-2 stays advisory and may be omitted.

Output

## Lean4 Review Report
**Scope:** Core.lean:89 (single sorry)

### Build Status
✓ Project compiles

### Sorry Audit (N remaining)
| File | Line | Theorem | Suggestion |
|------|------|---------|------------|
| ... | ... | ... | ... |

### Axiom Status
✓ Standard axioms only

### Style Notes
- [file:line] - [suggestion]

### Golfing Opportunities
- [pattern] → [optimization]

### Recommendations
1. [action item]

External Hooks

Custom hooks receive structured JSON on stdin with file information, sorries, axioms, and build status. They return a complete lean4-review-output/v2 object containing a suggestions array.

Validate before merging. Every hook or Codex output/v2 object is validated before its findings are incorporated — pipe it through lean4-skills-validate-review-output (reads the object on stdin):

  • exit 0 — valid; merge the findings.
  • exit 3 — validation failure (error_code schema-invalid or semantic-invalid on stdout). Exclude these findings and report the failure; never normalize or repair the output.
  • exit 2 — empty input or malformed JSON (treat as a hook that produced no usable result); exit 4 — the shipped schema is unreadable (operational).

The validator enforces the shipped schema plus the cross-field invariants JSON Schema cannot express: total_suggestions == len(suggestions), the by_severity histogram agrees with the suggestions, and a non-null error implies empty suggestions.

See review-hook-schema.md for full input/output schemas, examples, and performance tips for rate-limited APIs.

External Review Handoff

When --codex is specified, display context for external review:

─────────────────────────────────────────────────────────
CODEX REVIEW — {scope description}
─────────────────────────────────────────────────────────

[Context based on scope:]
- sorry: ±50 lines around the target sorry
- deps: Target sorry + referenced helpers/lemmas
- file: Full file content
- changed: All modified files (git diff)
- project: Full project (requires confirmation)

If no sorries in scope:
- file: Include top-level definitions + relevant sections
- changed: Include diff + changed file list

To review in Codex CLI:
1. Run `codex` in project directory
2. Type `/review` → select "Review uncommitted changes"
3. Or paste the above context and ask for review

Return one complete `lean4-review-output/v2` object conforming to the shipped
[`lean4-review-schema.json`](../skills/lean4/references/lean4-review-schema.json):
every suggestion carries all eight fields (using `null` where unavailable), and
the root also includes `version`, `summary`, and `error`. See
[review-hook-schema.md](../skills/lean4/references/review-hook-schema.md) for a
worked example.
─────────────────────────────────────────────────────────

Post-Review Actions

After review completes (internal or external), prompt:

## Review Complete

Would you like me to create an action plan from the review findings?
- [yes] — Enter plan mode with 3-6 step implementation plan
- [no] — End review, return to conversation

If "yes":

  1. Enter plan mode
  2. Create plan with one task per high-priority suggestion
  3. Get user approval before execution
  4. Route to the appropriate command (review itself remains read-only):
    • Missing proofs / build blockers → /lean4:prove
    • Strategy simplification opportunities → /lean4:refactor
    • Tactic-level brevity cleanup → /lean4:golf

Note: When --mode=stuck is triggered by prove/autoprove, skip this prompt—the proving command handles the follow-up with its own "Apply this plan? [yes/no]" prompt.

Built-in --json report schema (lean4-review-report/v1)

This legacy report format is distinct from the hook/Codex lean4-review-output/v2 interchange contract above (lean4-review-schema.json): it is the built-in command's own human-oriented --json dump, unchanged by #115. When using --json, output follows this structure:

{
  "version": "1.0",
  "build_status": "passing" | "failing",
  "sorries": [
    {"file": "Core.lean", "line": 89, "theorem": "convergence_main", "goal": "..."}
  ],
  "axioms": {
    "standard": ["propext", "Classical.choice", "Quot.sound"],
    "custom": []
  },
  "style_notes": [
    {"file": "Core.lean", "line": 42, "message": "Consider using field syntax"}
  ],
  "golfing_opportunities": [
    {"file": "Core.lean", "line": 78, "pattern": "have chain", "suggestion": "Inline or extract"}
  ],
  "summary": {
    "total_sorries": 3,
    "total_custom_axioms": 0,
    "style_issues": 2,
    "golf_opportunities": 5
  }
}

Stuck mode only: The summary object includes "next_action": "continue" (or other value) when --mode=stuck. Absent in batch mode.

Codex Integration

Note: Codex CLI's /review command is interactive-only. There's no codex review <sha> CLI command for automation. Two approaches are available:

Option A: Interactive Handoff (Recommended)

  1. Run codex in the project directory
  2. Type /review and select:
    • "Review uncommitted changes" — for working tree
    • "Review a commit" — select SHA from list
    • "Review against a base branch" — for PR-style diff
  3. Copy suggestions back to this session

Tip: Use /diff after /review to see exact file changes.

Option B: Non-interactive CLI automation (codex exec)

For CI or scripted reviews, use codex exec with a review prompt:

codex exec "Review this Lean 4 proof for correctness, focusing on:
1. Incomplete sorries and proof gaps
2. Type mismatches or missing instances
3. Non-standard axiom usage

$(cat Core.lean)
" --output-schema "$LEAN4_REFS/lean4-review-schema.json" -o review-output.json

The --output-schema argument points at the shipped, normative contract lean4-review-schema.json ($LEAN4_REFS is the installed references directory). It is the single source of truth for the category/severity enums — this command does not restate the full schema. External Codex reviews emit fix: null and set rule_id only for a specific rule (e.g. vacuous-api under api). A minimal conforming suggestion:

{
  "file": "Core.lean", "line": 89, "column": null,
  "severity": "advisory", "category": "api", "rule_id": "vacuous-api",
  "message": "Public API collapses to True; delete or replace.", "fix": null
}

See review-hook-schema.md for the field tables and the Codex SDK Cookbook for CI integration patterns.

Future autonomous external review: External review is currently manual-handoff only. Future versions may support autonomous external review via non-interactive CLI execution (e.g., codex exec) behind an explicit opt-in flag (--external-autonomous). Until then, unattended autoprove runs default to internal review.

Requirements for autonomous external review:

  1. Stable JSON input/output contract
  2. Timeout + retry + cost budgets
  3. Safe fallback to internal review on external failure
  4. Explicit opt-in flag, not default behavior

Safety

  • Read-only (does not modify files permanently)
  • Axiom check temporarily appends #print axioms, then restores
  • Does not create commits
  • Does not apply fixes
  • Docstring policy — Rule B (review). Review may flag weak or missing docstrings, development-history language (e.g. "sorry-free", "earlier drafts"), and scaffolding comments (TODO/HACK/FIXME), and may propose replacement wording in the report. It stays read-only: a docstring finding is a suggestion, never an in-place edit. See mathlib-style.md § Avoid Development History References for what to flag.

See Also

  • /lean4:prove - Guided cycle-by-cycle proving
  • /lean4:autoprove - Autonomous multi-cycle proving
  • /lean4:disprove - Guided counterexample search with certified refutation
  • /lean4:golf - Apply golfing optimizations
  • mathlib-style.md
  • mathlib-review-taxonomy.md — the vocabulary the Mathlib Review Layer emits. Its buckets become first-class findings when Layer 2 is at full strictness, and advisory findings otherwise.
  • Examples

Agents 4

Inputs

Consume the run-contract/v1 dispatch record (record == "dispatch"): read target/scope, the context envelope, and owned_files + file_baseline (fail closed — see below). Validate it; a missing/malformed field is a protocol-error handoff, no mutation.

parameters shape for this worker: {axioms: [...], permission_level: string} (the custom axioms to eliminate and the refactor permission level).

Actions

  1. Audit current state:

    • Start with lean_diagnostic_messages(file) on the target file(s) before broader verification
    • Use lean4-skills-check-axioms-inline FILE.lean (or . for project-wide audit) to measure current axiom state
    • Use lean4-skills-find-usages axiom_name for dependency inventory

    MCP canary: If lean_diagnostic_messages is missing from context (tool not listed), emit "⚠ Lean MCP tools unavailable in this subagent context" and fall back immediately to lean4-skills-check-axioms-inline and lake build for validation. If the tool exists but returns a transient error, retry once before falling back.

    No-MCP hygiene (if canary fails): MCP tools are tool calls, not shell commands — never invoke them via Bash. Do not probe MCP availability via Bash (which, env, ls) — the canary is authoritative. Stop retrying MCP for this run. Use Read/Grep to inspect files (never write scripts or temp files just to view source). Temp .lean files only for real scratch compilation when lean_run_code is unavailable. Start from pre-collected context in the parent prompt.

  2. Propose migration plan (~500-800 tokens):

    ## Axiom Elimination Plan
    **Total custom axioms:** N
    **Target:** 0
    
    ### Inventory
    1. **axiom_1** - Type: [mathlib_search|compositional|structural]
       Used by: M theorems, Priority: high/medium/low
    
    ### Elimination Order
    Phase 1: Low-hanging fruit (mathlib_search)
    Phase 2: Medium difficulty (compositional)
    Phase 3: Hard cases (structural/convert to sorry)
    
  3. Execute batch by batch - For each axiom:

    • Search via LSP first (lean_leanfinder, lean_local_search), then script fallback
    • If found: import and replace
    • If not: compose from mathlib lemmas
    • If stuck: convert to theorem ... := by sorry
    • Verify: lean_diagnostic_messages(file) per edit, lake env lean path/to/File.lean for file gate (run from the project root), axiom count decreased. Two distinct commands: lake lean <path/to/File.lean> (the dependency-aware file gate — builds the imports, then elaborates this exact file; use it once this refactor edited an imported module, since lake env lean reads stale .oleans — File Gate Scope) and plain lake build (project-wide; reserve for the final/project gate)
    • Fail closed on file baselines: whenever a run-contract/v1 dispatch carries owned_files, its file_baseline is required before any mutation (absent/malformed record or unavailable checker → dispatch-protocol error, no mutation; standalone work outside a structured dispatch is governed by the direct caller). lean4-skills-file-baseline check --baseline - before every mutating tool operation (all intended targets first) — only exit 0 authorizes the mutation; on any nonzero exit, apply nothing, report the structured stale-baseline result, and stop — never re-record and retry. Advance only intentionally changed entries after success (shell-quote each path operand, -- before positionals) — advance's output replaces the current baseline for subsequent checks; if advance fails, stop (cycle-engine.md § File baselines and drift)
  4. Report progress after each elimination and final summary

Output

At the return boundary, emit a complete run-contract/v1 handoff record — echo target/scope/mode; report files_owned/files_changed + the final adopted file_baseline; set blocker_kind/blocker_class only when blocker-driven; and next_action. The human-readable per-axiom report below is in addition to that record.

Per-axiom report (~200-400 tokens):

## Axiom Eliminated: axiom_name
**Strategy:** mathlib_import/compositional/converted_to_sorry
**Changes:** [imports, helpers]
**Verification:** Compile ✓, Count N→N-1 ✓

Final summary (~300-500 tokens):

## Axiom Elimination Complete
**Starting:** N, **Ending:** M
**By strategy:** X mathlib, Y compositional, Z sorry
**Files changed:** K

Total: ~2000-3000 tokens per batch

Constraints

  • Lemma search required before proving (LSP-first, script fallback)
  • Compile and verify after EACH elimination
  • May NOT add new axioms while eliminating
  • May NOT skip lemma search
  • May NOT break dependent theorems
  • Must track axiom count (trending down)
  • Prefer live-file MCP for target-context verification; use lean_run_code for isolated scratch experiments, and temporary .lean files only if lean_run_code is unavailable or insufficient
  • Follow mathlib 100-char line width — do not wrap lines at 80 when they fit within 100

Example (Happy Path)

## Axiom Elimination Plan
**Total:** 2, **Target:** 0

1. **helper_lemma** - mathlib_search, used by 3 theorems

---

Searching: lean4-skills-search-mathlib "helper" name
Found: Mathlib.Foo.helper_lemma

## Axiom Eliminated: helper_lemma
**Strategy:** mathlib_import
**Changes:** Added import, replaced axiom with theorem
**Verification:** ✓ Count 2→1

Tools

LSP-first (use before scripts; fall back only when LSP is unavailable, rate-limited, or inconclusive after bounded attempts):

lean_goal(file, line)
lean_diagnostic_messages(file)
lean_leanfinder("query")
lean_local_search("keyword")
lean_loogle("type pattern")
lean_run_code("code")
# Script fallback:
lean4-skills-check-axioms-inline
lean4-skills-find-usages
lean4-skills-search-mathlib
lean4-skills-smart-search
lake build

See Also

Inputs

Consume the run-contract/v1 dispatch record (record == "dispatch"): read target, the context envelope, and owned_files + file_baseline (fail closed — see below). Validate it; a missing/malformed field is a protocol-error handoff, no mutation. A passing build is required (verify before starting).

parameters shape for this worker: {search_mode: "off" | "quick" | "full", golfable_patterns: [...], candidate_targets: [...]} (default search_mode quick).

Actions

MCP canary runs before step 3 (after pure-script steps 1-2). See step 2 for details and fallback behavior.

  1. Find patterns (in policy order: directness → structural → conditional) with false-positive filtering:

    lean4-skills-find-golfable FILE.lean --filter-false-positives
    

    For direct-proof discovery when search_mode ≠ off or syntactic pass stalls:

    lean4-skills-find-exact-candidates FILE.lean
    
  2. Verify safety before inlining any binding:

    lean4-skills-analyze-let-usage FILE.lean --line LINE
    
    • 1-2 uses: Safe to inline
    • 3-4 uses: Check carefully (40% worth optimizing)
    • 5+ uses: NEVER inline

    MCP canary: Before step 3, test lean_diagnostic_messages(file). If unavailable (tool-not-found, missing from context, or inaccessible), emit "⚠ Lean MCP tools unavailable — golfing limited to syntactic patterns", skip steps 3-4 (require lean_multi_attempt), and reduce step 5 to max 1 hunk with lake env lean <file> (from project root) per-hunk verification; reserve lake build for final verification only.

    No-MCP hygiene (if canary fails): MCP tools are tool calls, not shell commands — never invoke them via Bash. Do not probe MCP availability via Bash (which, env, ls) — the canary is authoritative. Stop retrying MCP for this run. Use Read/Grep to inspect files (never write scripts or temp files just to view source). Start from pre-collected context in the parent prompt.

  3. Exact-collapse pass (for apply-exact-chain anchors from step 1):

    • Mechanical (≤30 anchors/file): construct collapsed exact → lean_multi_attempt + lean_diagnostic_messages baseline check; accept by scoring order (per golf.md: directness → inference burden → perf → length)
    • Exploratory (when search_mode ≠ off; shared budget): candidate exact from chain lemmas + local hyps + dot-notation rewrites → lean_multi_attempt; ≤2 probes/anchor, quick ≤5/file 30s, full ≤15/file 60s. Skip: calc, multi-goal, blocks >7 lines, semicolon-heavy, have/refine
  4. Lemma replacement search (if search_mode ≠ off):

    • lean_local_search first, then lean_leanfinder or lean_loogle
    • quick: 1 search, ≤2 candidates; full: 2 searches, ≤3 candidates
    • Test with lean_multi_attempt; accept the best passing replacement by scoring order (per golf.md: directness → inference burden → perf → length)
    • Budget: ≤3 search calls, max 3 candidates; uses remaining shared time budget (quick 30s, full 60s total across steps 3–4)
    • If a replacement would require changing a declaration's statement → reject the candidate and keep the existing proof; report the proposed change for explicit user approval (this is not evidence that the statement is wrong — golf starts from a compiling proof). When stopping to hand that decision back to the parent, use next_action = stop, not redraft. If it needs a multi-file or strategy-level refactor → return the proposal to the parent for /lean4:refactor (through its normal approval flow); do not expand your own file ownership or start cross-file edits. Hand off to axiom-eliminator only for axiom/assumption hygiene
  5. Apply optimizations (max 3 hunks × 60 lines each):

    • Fail closed on file baselines: whenever a run-contract/v1 dispatch carries owned_files, its file_baseline is required before any mutation (absent/malformed record or unavailable checker → dispatch-protocol error, no mutation; standalone work outside a structured dispatch is governed by the direct caller). lean4-skills-file-baseline check --baseline - before every mutating tool operation (all intended targets first) — only exit 0 authorizes the mutation; on any nonzero exit, apply nothing, report the structured stale-baseline result, and stop — never re-record and retry. Advance only intentionally changed entries after success (shell-quote each path operand, -- before positionals) — advance's output replaces the current baseline for subsequent checks; if advance fails, stop (cycle-engine.md § File baselines and drift)
    • Priority: directness wins first (by exact→t, apply+exact→exact, ext+rfl→rfl), then perf (linter simp cleanup, simp only narrowing), then verified inlines
    • lean_diagnostic_messages(file) after each change; lake build only for final verification
    • Revert immediately on failure
  6. Report results with savings and saturation status

Output

At the return boundary, emit a complete run-contract/v1 handoff record — echo target/scope/mode; report files_owned/files_changed + the final adopted file_baseline; set blocker_kind/blocker_class only when blocker-driven; and next_action (golf at saturation). The human-readable summary below is in addition to that record.

Proof Golfing Results:

File: [filename]
Meaningful simplifications: N (directness improvements)
Performance cleanups: M
Syntax cleanups: K
Skipped: J (marginal compressions)
Failed/Reverted: L

Lines: X → Y (Z% reduction)

[If success rate < 20%]: SATURATION REACHED

Constraints

  • Max 3 edit hunks per run, each ≤60 lines
  • No semantic changes
  • No new dependencies, except one import when replacing a custom helper or axiom with a Mathlib lemma and the replacement scores better by the lexicographic order (directness → inference burden → perf → length)
  • Must verify safety before inlining
  • Stop when success rate < 20%
  • May NOT skip safety verification
  • If a replacement would require a statement change → reject the candidate, keep the existing proof, report the proposed change for explicit approval (next_action = stop, never redraft — an unsuitable candidate is not evidence the statement is wrong); if it needs a multi-file or strategy-level refactor → return the proposal to the parent for /lean4:refactor (no cross-file edits, no ownership expansion); hand off to axiom-eliminator only for axiom/assumption hygiene, never as a generic "bigger surgery" target

Bulk rewrite constraints (obeys 3-hunk cap):

  • sed activates automatically when ≥4 whitelisted syntax wrappers found at declaration RHS / term-wrapper positions (:= by exact t → := t, by rfl → rfl); never inside tactic blocks or calc blocks; preview + user confirmation required before applying
  • Preview required: match count + 3-5 sample hunks before applying
  • Effective per-run limit: min(10 replacements/file, 3 hunks × 60 lines); overflow recomputed on next invocation — no persistent queue; validate vs pre-batch baseline diagnostics + sorry count
  • Auto-revert batch if sorry count increases or new diagnostics appear vs baseline
  • On permission denial → stop immediately, report back to parent agent
  • Skip candidate when replacement TERM introduces a nested tactic-mode boundary (by at non-top-level); if context classification is uncertain, skip
  • Verify symbol resolves in current imports and argument order matches before replacing; no broad replace-all

Golfing Policy

Semicolons: Never introduce naked ; as a golfing transform. <;> only for literally identical single-tactic goals (e.g., constructor <;> simp). Each ;-separated tactic counts as its own line — semicolons do not reduce line count.

Scoring order (per golf.md): directness → inference burden → perf/determinism → length. Length is a core goal but a tiebreaker. Inference/perf judged heuristically by tactic complexity ladder (rfl/exact < rw/apply < simp only < simpa/rwa < broad simp/decide/omega/grind), not by measurement.

Hard reject: introduces naked ; · introduces <;> on non-identical goals · moves UP ladder for only 1-line win · removes meaningful names · >80 chars or >2 dot-chain · replaces exact with simpa/rwa unless exact fails.

Terminal simp only: Non-terminal simp → simp only always valid. Terminal simp → simp only is a style split — skip in delegate mode unless project already uses it nearby.

Minimum value filter: 1-line savings only if (a) zero-risk syntax cleanup or (b) also improve clarity or performance.

simpa/rwa direction: Never replace exact t with simpa using t unless exact t fails. simpa using is only a win when it deletes surrounding boilerplate. In coercion-heavy proofs, test exact first. See golf.md for full rules.

Delegation Awareness

When invoked as a background subagent:

  • If Edit/Bash permission denied → stop immediately, do NOT retry or request again
  • Report to parent: "Permission denied — completed N/M patterns"
  • Default max 2 concurrent golfer agents (parent may override via --max-delegates); parent handles batching and checkpointing

Example (Happy Path)

Pattern found at line 45:
  let x := expr
  exact property x

Running: lean4-skills-analyze-let-usage --line 45
Result: x used 1 time → Safe

Before (2 lines):
  let x := expr
  exact property x

After (1 line):
  exact property expr

Building... ✓
Savings: 1 line

Tools

LSP (use before scripts; fall back only when LSP is unavailable, rate-limited, or inconclusive after bounded attempts):

lean_goal(file, line)                   # Proof goal context
lean_local_search("keyword")           # Lemma search (try first)
lean_leanfinder("query")              # Semantic search
lean_loogle("type pattern")           # Type-based search
lean_multi_attempt(file, line, snippets=[...])  # Test replacements
lean_diagnostic_messages(file)         # Per-edit validation

Scripts:

lean4-skills-find-golfable       # Pattern detection
lean4-skills-analyze-let-usage  # Safety verification (CRITICAL)
lake build                              # Final verification

See Also

Inputs

Consume the run-contract/v1 dispatch record (record == "dispatch"): read target, the context envelope, and parameters.error (the structured error to repair). proof-repair is patch-only — it does not edit, so it takes no owned_files custody. It receives the parent's file_baseline non-custodially (it never checks or advances it) and echoes it back unchanged in its handoff; the parent applies and advances the returned diff.

parameters.error shape:

{
  "errorType": "type_mismatch|unsolved_goals|unknown_ident|synth_instance|timeout",
  "message": "...",
  "file": "Foo.lean",
  "line": 42,
  "goal": "⊢ Continuous f",
  "localContext": ["h1 : Measurable f"]
}

Actions

  1. Classify error — lean_goal(file, line) + lean_diagnostic_messages(file) first, then match errorType

    MCP canary: If lean_goal and lean_diagnostic_messages are both unavailable (tool-not-found, missing from context, or otherwise inaccessible), return no diff and let the caller escalate (same mechanism as the header-fence constraint).

    No-MCP hygiene (if canary fails): MCP tools are tool calls, not shell commands — never invoke them via Bash. Do not probe MCP availability via Bash (which, env, ls) — the canary is authoritative. Stop retrying MCP for this run. Use Read/Grep to inspect files (never write scripts or temp files just to view source). Start from pre-collected context in the parent prompt.

  2. Apply error-specific strategy (see table below)

  3. Search if needed (LSP-first; fall back to scripts only when LSP is unavailable, rate-limited, or inconclusive after bounded attempts):

    • lean_leanfinder("query") or lean_local_search("keyword") first
    • Script fallback: lean4-skills-search-mathlib only after LSP exhausted
  4. Generate minimal diff (1-5 lines)

  5. Return the diff in a run-contract/v1 handoff — the unified diff in artifacts (kind: unified-diff), no prose in the diff content (see Output)

Two-Stage Approach

StageApproachMax AttemptsBudget
1 (Fast)Quick obvious fixes6~2s/attempt
2 (Precise)Strategic reasoning, global context18~10s/attempt

Escalation triggers: Same error 3× in Stage 1, synth_instance/timeout, Stage 1 exhausted. Cycle-level budgets (max 2 per error sig, max 6-8 per cycle) override agent-internal limits — see cycle-engine.md.

Repair Strategies

ErrorStrategy
type_mismatchconvert _ using N, type annotation, refine, rw
unsolved_goalssimp?, exact?, intro, use, constructor
unknown_identSearch mathlib, add import, fix namespace
synth_instancelocal instance via plain have/let, open scoped, reorder arguments
timeoutsimp only [...], clear, explicit instances

Output

Return a complete run-contract/v1 handoff record with the unified diff carried in artifacts (proof-repair does not edit): files_changed: [], the parent's file_baseline echoed unchanged, and

"artifacts": [{"kind": "unified-diff", "content": "--- Foo.lean\n+++ Foo.lean\n@@ -42,1 +42,1 @@\n-  exact h1\n+  convert continuous_of_measurable h1 using 2\n"}]

The diff itself is line-number-anchored, nothing else in content. status/blocker_kind/next_action follow the outcome (a repaired goal → next_action: continue; an un-repairable one → status: stuck, blocker_kind: proof). The parent checks, applies, and advances the patch (§ File baselines and drift).

Constraints

  • The diff content is unified-diff ONLY (no explanations); it rides in the handoff's artifacts
  • Change ONLY 1-5 lines per call
  • Stay within stage budget
  • May NOT rewrite entire functions
  • May NOT try random tactics
  • May NOT skip mathlib search
  • May NOT modify declaration headers (header fence). If the fix requires a signature change, return no diff and let the caller escalate.
  • Use lean_diagnostic_messages(file) for per-edit validation before any Bash-based file gate; prefer lean_run_code over temporary .lean files for isolated scratch probes
  • Follow mathlib 100-char line width — do not wrap lines at 80 when they fit within 100

Example (Happy Path)

Input: type_mismatch at line 42, expected Continuous f, got Measurable f

Output:

--- Core.lean
+++ Core.lean
@@ -42,1 +42,1 @@
-  exact h1
+  exact Continuous.of_discrete h1

Tools

LSP-first order (use before scripts):

lean_goal(file, line)                # LSP live goal
lean_diagnostic_messages(file)       # Current errors/warnings
lean_code_actions(file, line)        # Resolve "Try this" suggestions to edits
lean_leanfinder("query")            # Semantic search (try first)
lean_local_search("keyword")        # Local + mathlib
lean_loogle("type pattern")         # Type-based search
lean_multi_attempt(file, line, snippets=[...])  # Test candidates
lean_run_code("code")               # Isolated scratch experiments

Script fallback (only when LSP is unavailable, rate-limited, or inconclusive after bounded attempts):

lean4-skills-search-mathlib    # Search by pattern
lean4-skills-smart-search      # Multi-source

See Also

Inputs

Consume the run-contract/v1 dispatch record (record == "dispatch"): read target/scope, the context envelope (pre-collected LSP state — use it as the starting state when MCP is unavailable), and owned_files + file_baseline (fail closed on these — see below). Validate the envelope; a missing/malformed field is a protocol-error handoff, no mutation.

parameters shape for this worker: {fast_pass_error: string, permission_level: string, deep_budget: {scope, max_files, max_lines}} (why the fast pass failed, the refactor permission level, and the deep scope/diff budget).

Actions

  1. Understand why fast pass failed:

    • Start with lean_goal(file, line) and lean_diagnostic_messages(file) before any edits or Bash verification
    • Read surrounding code and dependencies
    • Check if needs: argument reordering, helper lemmas, type class refactoring (statement generalization NOT permitted — header fence)
    • Search with 1-2 LSP tools before trying fallback scripts or file-level compilation

    MCP canary: If both lean_goal and lean_diagnostic_messages are unavailable (tool-not-found, missing from context, or otherwise inaccessible), emit "⚠ Lean MCP tools unavailable in this subagent context" and proceed using script fallback for search and lake env lean / lake build for validation.

    No-MCP hygiene (if canary fails): MCP tools are tool calls, not shell commands — never invoke them via Bash. Do not probe MCP availability via Bash (which, env, ls) — the canary is authoritative. Stop retrying MCP for this run. Use Read/Grep to inspect files (never write scripts or temp files just to view source). Temp .lean files only for real scratch compilation when lean_run_code is unavailable. Start from pre-collected context in the parent prompt.

  2. Outline plan FIRST (~200-500 tokens):

    ## Sorry Filling Plan
    **Target:** [file:line]
    **Why it's hard:** [reasons]
    **Strategy:** [phases]
    **Safety checks:** [compile after each phase]
    
  3. Execute incrementally with Lean-backed checks after each phase:

    • Phase 1: Prepare infrastructure (helpers, imports)
    • Phase 2: Fill the sorry
    • Phase 3: Clean up
    • After each edit batch: lean_diagnostic_messages(file) first; use lake env lean path/to/File.lean only as a file gate when LSP is unavailable or a file-level import/environment check is needed (run from the project root). Once this run has edited an imported module (deep mode permits that within the header fence), gate with lake lean <path/to/File.lean> for the importing target instead — the file gate checks against built .oleans and does not rebuild changed imports (File Gate Scope)
  4. Report progress after each phase and final summary

Output

At the return boundary, emit a complete run-contract/v1 handoff record — echo target/scope/mode; report files_owned/files_changed + the final adopted file_baseline; set blocker_kind/blocker_class only when blocker-driven (a deep-safety abort is blocker_kind: safety-guard, blocker_class: null); and next_action. The human-readable phase reports below are in addition to that record.

Phase reports (~300-500 tokens each):

## Phase N Complete
**Actions:** [changes made]
**Compile status:** ✓/✗
**Next phase:** [what's next]

Final summary (~200-300 tokens):

## Sorry Filled Successfully
**Strategy:** compositional/structural/novel
**Files changed:** N
**Helpers added:** M
**Axioms:** 0

Constraints

  • May refactor across files (with compile verification)
  • May NOT generalize statements (header fence). Report next_action = redraft if statement appears wrong.
  • May NOT change statements without permission
  • May NOT introduce axioms without permission
  • May NOT make large architectural changes without approval
  • May NOT delete existing working proofs
  • Must validate after every phase: lean_goal before first edit and after material changes; lean_diagnostic_messages per edit batch
  • Prefer live-file MCP for target-context work; for isolated scratch experiments use lean_run_code (temporary .lean files only as last resort)
  • Engine creates path-scoped snapshot before deep and rolls back on regression or scope exceeded
  • Follow mathlib 100-char line width — do not wrap lines at 80 when they fit within 100
  • Engine enforces --deep-scope, --deep-max-files, --deep-max-lines — do not bypass
  • Agent must not run git snapshot/rollback commands directly; on rollback, sorry is marked stuck and agent must stop
  • One concurrent editor per file. Never dispatch multiple agents targeting the same file in parallel — the last agent to Edit overwrites earlier agents' completed proofs with no error. For N sorrys in one file, either use one agent or dispatch sequentially with commits between each.
  • File-baseline drift check (issue #102) — fail closed. Whenever a run-contract/v1 dispatch carries owned_files, its file_baseline is required before any mutation; if it is absent, malformed, or the checker is unavailable, report a dispatch-protocol error and apply no mutation (standalone work outside a structured dispatch is governed by the direct caller). Run lean4-skills-file-baseline check --baseline - (record over stdin) immediately before every mutating tool operation, checking every intended target first for multi-file operations — only exit 0 authorizes the next mutation. On any nonzero exit (drift or operational error): apply no mutation, report the structured stale-baseline result (affected paths + classification + recommend rerun, serialize, or isolation: "worktree"), and stop — never re-record and retry. After each successful mutation, advance only the entries you intentionally changed (advance --baseline - -- "<changed path>" ... — shell-quote each path operand, -- before positionals) — its output JSON replaces your current baseline for every subsequent check; if advance fails, stop before any further mutation. Full custody rule: cycle-engine.md § File baselines and drift.

Example (Happy Path)

## Sorry Filling Plan
**Target:** Core.lean:156
**Why it's hard:** Need Filter.Eventually lemma but it doesn't exist yet
**Strategy:**
1. Extract helper lemma `filter_eventually_of_set`
2. Add import for Filter.Eventually
3. Prove using helper

## Phase 1 Complete
**Actions:** Added helper lemma, added import
**Compile:** ✓
---
## Sorry Filled Successfully
**Strategy:** helper extraction
**Helpers added:** 1

Tools

LSP-first (use before scripts; fall back only when LSP is unavailable, rate-limited, or inconclusive after bounded attempts):

lean_goal(file, line)                # Understand goal
lean_diagnostic_messages(file)       # Per-edit validation
lean_leanfinder("query")            # Semantic search (try first)
lean_local_search("keyword")        # Local + mathlib
lean_loogle("type pattern")         # Type-based search
lean_multi_attempt(file, line, snippets=[...])  # Test candidates
lean_run_code("code")               # Isolated scratch experiments

Scripts:

lean4-skills-sorry-analyzer       # Context analysis
lean4-skills-check-axioms-inline  # Verify no axioms
lean4-skills-find-usages          # Dependency analysis
lean4-skills-smart-search         # Search fallback (after bounded LSP pass)
lake env lean path/to/File.lean         # File gate (project root, after LSP checks; built imports only)
lake lean path/to/File.lean             # Dependency-aware file gate: builds imports, then elaborates this file
lake build                              # Project / checkpoint / final gate only

See Also

Sponsors

Details

Marketplace
cameronfreer/lean4-skills
Source
plugins/lean4
Category
Community

More from cameronfreer/lean4-skills

All 2