Logo de Lean Verify

Lean Verify

Comunidade
hirosassa
lean-verify

Use the Lean 4 theorem prover to find software bugs with counterexamples (integer overflow, bit manipulation, boundary conditions, spec/implementation mismatches) and to prove that an optimization or refactoring is equivalent to the original, so performance work can land safely. Also covers installing Lean and creating a minimal project. Use this skill proactively, even when Lean is not mentioned by name, when the user mentions Lean / lake / elan / formal verification / theorem proving / bv_decide / counterexample search / "is this optimization equivalent?" / "check that it holds for all inputs" / "find bugs tests can't catch" / "safely swap out a bit-twiddling or arithmetic trick", or wants to confirm the correctness of a peephole optimization, strength reduction, bounds-check elimination, or algorithm rewrite. Language-agnostic (Rust, C, Go, TypeScript, ...).

Visão geral

Publicado porhirosassa
Repositóriolean-verify
Nome da habilidadelean-verify
Estrelas
66
Forks
2
Arquivos incluídos
8
LicençaMIT
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    As habilidades de IA são escritas em Markdown simples, não em código específico de um provedor. Por isso, funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • Arquivos incluídos: 8

    Scripts, templates e referências que o modelo pode ler enquanto trabalha. Os arquivos são somente para leitura e nunca são executados.

  • Código aberto

    Publicada por hirosassa no GitHub. Leia os arquivos da habilidade antes de instalá-la.

Instalação

Instale a habilidade de IA Lean Verify no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL abaixo, que aponta para a pasta da habilidade, e confirme.
    https://github.com/hirosassa/lean-verify/tree/main/skills/lean-verify
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Adicionar habilidade → Via URL do GitHub. Depois, cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/hirosassa/lean-verify.git /tmp/lean-verify
mkdir -p .claude/skills
cp -r /tmp/lean-verify/skills/lean-verify .claude/skills/lean-verify
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Lean Verify em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Lean Verify automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Lean Verify não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

lean-verify: Find bugs and speed up code safely with Lean 4

Tests only guarantee the inputs you tried. Lean can mechanically answer whether a property holds for all inputs, or hand back a counterexample. This skill uses Lean not as a heavyweight verification framework but as a tool for small functions and single rewrite rules. Do not try to prove a whole program: the proof cost explodes and you learn nothing extra.

When to use it

SituationFitMode
Correctness of integer ops, bit ops, shifts, rotations, wrapping arithmeticExcellentA: bv_decide
"Is the optimized version equal to the naive one?" (strength reduction, bit tricks, expression rewrites)ExcellentB: equivalence
Bounds-check elimination, index range validityGoodB + omega
Loop/recursion invariants, algorithm rewritesGood (needs induction)B + induction
Exhaustive search over a small finite domainGooddecide / #eval
I/O, concurrency, networking, code with huge statePoorRecommend ordinary tests / fuzzing

If the target is a poor fit, don't force it into Lean. Say so and propose another approach.

Workflow

  1. Check the environment → run scripts/check_lean.sh. If it prints found (not on PATH) and a hint: export PATH=... line, Lean is in ~/.elan/bin but not on PATH: run that export in the same Bash call as lean / lake. If Lean is missing, follow references/setup.md (ask the user before installing). If plausible looks necessary (searching for properties over structured data such as lists), read the plausible: line of the output: available means use it, not installed means follow references/setup.md §4 (ask the user first). Don't propose it when bv_decide or #eval can do the job (fixed-width integers, small finite domains).
  2. Narrow the target: verify one function or one rewrite rule. Split anything larger.
  3. Model it: translate the target into Lean definitions. Watch for semantic differences (see "Modeling pitfalls" below). Start the file from this minimal template; forgetting the import is the most common first error (error: "to use bv_decide, please include import Std.Tactic.BVDecide"):
    lean
    import Std.Tactic.BVDecide
    
    theorem t (x : BitVec 32) : (x <<< 1) = x * 2 := by bv_decide
  4. State the property: for bug hunting, the property the code should satisfy; for optimization, fast x = slow x.
  5. Look for a counterexample first: before proving, try bv_decide / plausible / #eval. A counterexample saves the proof effort and is directly usable as a bug report.
  6. Prove it: try the tactics in the order given in references/tactics.md (bv_decide → omega → decide +kernel → simp → induction). Once it is proved, run a mutation check: change one constant or operator (e.g. <<< 3 → <<< 2) and confirm Lean now reports a counterexample. If the mutant is still proved, the proof is probably vacuous (details in references/perf-equivalence.md).
  7. Translate the result back: turn a counterexample into concrete inputs in the original language and write a test that reproduces it in the original code (don't take Lean's output on faith; a modeling gap can cause a false positive). Don't call it a bug until it reproduces in the real code (see "potentially spurious counterexample" under Known limitations). A successful proof means "equivalent in the model"; state explicitly that the correspondence between the model and the real code is a human guarantee.

Modes

A. Bug hunting (go get a counterexample)

Write the spec a different way (more naive, or computed in a wider type) and compare it with the implementation. When bv_decide fails it returns a counterexample assignment:

lean
def avgBad (a b : BitVec 32) : BitVec 32 := (a + b) >>> 1          -- a+b overflows 32 bits
def avgSpec (a b : BitVec 32) : BitVec 32 :=
  ((a.zeroExtend 33 + b.zeroExtend 33) >>> 1).truncate 32          -- compute in 33 bits
theorem t (a b : BitVec 32) : avgBad a b = avgSpec a b := by unfold avgBad avgSpec; bv_decide
-- error: The prover found a counterexample: a = 4294967295#32, b = 4294967295#32

If bv_decide can neither prove the property nor produce a counterexample, suspect how the spec is written or a missing precondition (e.g. h : x ≠ 0). Full examples are in assets/examples/ and have been run. Detailed steps are in references/bug-hunting.md.

B. Proving an optimization equivalent

Optimizations risk being "faster but subtly different". Treat the naive implementation as the spec and the optimized one as the implementation, prove they are equal, and the rewrite can be adopted with confidence:

lean
theorem mul10 (x : BitVec 32) : (x <<< 3) + (x <<< 1) = x * 10 := by bv_decide
theorem mod8  (x : BitVec 32) : x % 8 = x &&& 7 := by bv_decide

For optimizations with preconditions (e.g. "only holds when x is a power of two"), state the precondition as a hypothesis (h : ...). Whether callers actually guarantee it must be checked separately. Rewrites of recursion or loops use induction. Details in references/perf-equivalence.md.

Modeling pitfalls (the main source of false positives/negatives)

  • Lean's BitVec is two's-complement wrapping arithmetic. Rust's + panics in debug builds; wrapping_add is what matches Lean. Map to the semantics of the target language and build mode.
  • Shift amounts behave differently. Shifting a BitVec by its width or more gives 0 in Lean, but Rust's <</>> panic at width or more (masked in release), and C is undefined behavior. Reduce the shift amount with % 32 or put it in a precondition so it matches the original language.
  • Signed division/remainder rounding (toward zero vs. floor) differs by language. Check which of BitVec.sdiv / srem / smod corresponds.
  • Floating point is outside bv_decide's scope. Extract only the integer part.
  • Nat / Int have unbounded precision. Use BitVec n to study fixed-width behavior.

Known limitations (hit in practice)

  • Plausible (property-based testing) is not part of core. If check_lean.sh reports plausible: not installed and you need it, ask the user for permission before adding it (it edits lakefile.toml and downloads from the network; see references/setup.md §4). Never add it unasked. If the user declines, or for a single file, an exhaustive #eval search can stand in.

  • ring_nf / nlinarith / linarith and friends are Mathlib-only. To stay within core, use simp only [Nat.add_mul, ...] + omega. Mathlib's first build is heavy, so don't add it until it is needed.

  • Using decide for an exhaustive search as small as Fin 256 can hit the recursion limit. Use decide +kernel or set_option maxRecDepth N in decide.

  • The first lean run downloads the toolchain and can take minutes, and concurrent elan invocations wait on a lock. Watch for timeouts and use background execution.

  • bv_decide uses a SAT solver (cadical); 64-bit expressions with many multiplications or divisions can be slow. If so, shrink the width to 8/16 bits and check first whether a counterexample exists (the structure of a bug often doesn't depend on width).

  • "potentially spurious counterexample" from bv_decide means the counterexample may not be real. It appears when the goal contains something the solver treats as opaque: an opaque / abstracted variable, an expression you abstracted away (e.g. a hash or call replaced by a free variable), or floating-point values. Treat it as a lead only: reproduce it in the real code (or model the abstracted part / add the precondition) before reporting a bug. Steps in references/bug-hunting.md.

Report format

Return results to the user in this form:

  1. What was verified, and the assumptions made while modeling
  2. Result: counterexample found (input values and how to reproduce in the original code) / proved (under which preconditions) / undecided (what blocked it)
  3. Next action (fix proposal, tests to add, whether to adopt the optimization)

Do not rephrase "proved" as "the original code is correct". The guarantee only extends to the model.

Arquivos incluídos

O modelo lê esses arquivos sob demanda enquanto a habilidade está carregada. Eles são disponibilizados para leitura e nunca são executados.

Perguntas frequentes

O que a habilidade de IA Lean Verify faz?

Use the Lean 4 theorem prover to find software bugs with counterexamples (integer overflow, bit manipulation, boundary conditions, spec/implementation mismatches) and to prove that an optimization or refactoring is equivalent to the original, so performance work can land safely. Also covers installing Lean and creating a minimal project. Use this skill proactively, even when Lean is not mentioned by name, when the user mentions Lean / lake / elan / formal verification / theorem proving / bv_decide / counterexample search / "is this optimization equivalent?" / "check that it holds for all in...

Por que usar Lean Verify no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. A habilidade Lean Verify é escrita em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. No TypingMind, você usa suas próprias chaves de API e paga diretamente aos provedores, em vez de pagar uma assinatura por licença de usuário. Suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Lean Verify no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/hirosassa/lean-verify/tree/main/skills/lean-verify. O TypingMind lê o arquivo SKILL.md, reúne os arquivos da habilidade e a instala para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Lean Verify?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Lean Verify?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Lean Verify com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Lean Verify é gratuita?

Sim. A habilidade é publicada no GitHub por hirosassa sob a licença MIT. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, templates ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas que ele pode acionar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA dá ao modelo o conhecimento e as orientações de que ele precisa: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver lista completa

Crie seu próprio espaço de trabalho com IA agora

Inscreva-se na nossa newsletter para receber avisos sobre novos recursos e futuros sorteios 👇