Логотип Lean Verify

Lean Verify

Спільнота
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, ...).

Огляд

Видавецьhirosassa
Репозиторійlean-verify
Назва навичкиlean-verify
Зірки
66
Форки
2
Файли в пакеті
8
ЛіцензіяMIT
Посилання
  • Інструкції у форматі Markdown

    Файл SKILL.md, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний Markdown, а не код для певного постачальника, тому вони працюють із GPT, Claude, Gemini, Grok або локальною моделлю.

  • Файлів у комплекті: 8

    Скрипти, шаблони й довідкові матеріали, які модель може читати під час роботи. Файли доступні лише для читання й ніколи не виконуються.

  • Відкритий вихідний код

    Видавець на GitHub: hirosassa. Перед установленням перегляньте вихідні файли навички.

Встановлення

Установіть навичку ШІ Lean Verify у TypingMind, щоб використовувати її з будь-якою LLM, або додайте її до іншого агента, що читає SKILL.md.

1

Встановити в TypingMind

TypingMind встановлює навичку безпосередньо з її папки на GitHub — читає SKILL.md, збирає файли ресурсів у пакет і зберігає результат локально.

  1. Відкрийте застосунок і перейдіть до розділу «Плагіни» → «Навички».
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/hirosassa/lean-verify/tree/main/skills/lean-verify
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Додати навичку → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
2

Встановити в іншому агенті

Будь-який агент, що підтримує формат Agent Skills, може використовувати цю навичку — скопіюйте папку до каталогу навичок цього агента.

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
Після копіювання перезапустіть Claude Code, щоб завантажити нову навичку.

Використовуйте навичку в TypingMind

Увімкніть навичку Lean Verify в будь-якому чаті TypingMind, і далі модель усе зробить сама. Назва й опис навички містяться в системному промпті, а щойно надходить відповідний запит, модель самостійно завантажує повні інструкції — вам не потрібно викликати навичку вручну, і до фактичного використання вона не витрачає токенів.

Модель самостійно завантажує навичку Lean Verify, щойно надходить відповідний запит.

Працює з будь-якою моделлю ШІ

Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для певного постачальника, тому навичка Lean Verify не прив’язана до моделі, для якої її створено. Установіть її один раз у TypingMind і використовуйте з GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama або локальною моделлю, яку ви запускаєте самостійно, — усе з вашими власними ключами API.

  • Завантажується лише за потреби

    Системний промпт містить лише назву й опис. Інструкції завантажуються за першого відповідного запиту, тож поки навичка не потрібна, токени на її інструкції не витрачаються.

  • Змінюйте моделі під час чату

    Оскільки навичка — це інструкції, а не код, зміна моделі не порушує її роботу: наступна модель читає той самий файл SKILL.md.

Інструкції навички

Це вміст файлу SKILL.md, який завантажує модель. Прочитайте його перед установленням — навичка містить інструкції, яких дотримуватиметься ваша модель.

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.

Файли в пакеті

Модель читає ці файли за потреби, поки навичку завантажено. Вони доступні для читання й ніколи не виконуються.

Поширені запитання

Що робить навичка ШІ 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 in...

Навіщо використовувати Lean Verify у TypingMind?

Тому що ви встановлюєте її один раз і використовуєте з будь-якою моделлю. Lean Verify — це звичайний Markdown, а не код для конкретного постачальника, тому та сама навичка працює з GPT-5, Claude, Gemini, Grok або локальною моделлю. Ви можете змінити модель навіть посеред чату, і навичка продовжить працювати. TypingMind використовує ваші власні ключі API, тож ви платите безпосередньо постачальникам замість передплати за кожне місце користувача, а ваші навички й чати залишаються у вашому сховищі.

Як встановити Lean Verify у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/hirosassa/lean-verify/tree/main/skills/lean-verify. TypingMind прочитає файл SKILL.md, додасть супровідні файли та встановить навичку, яку можна вмикати окремо для кожного чату.

Які моделі ШІ можуть використовувати Lean Verify?

Будь-яка модель, яку ви підключите в TypingMind. Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для конкретного постачальника, тому GPT, Claude, Gemini, Grok і локальні моделі можуть завантажувати цю навичку, коли запит їй відповідає.

Зі скількома моделями ШІ можна використовувати Lean Verify?

Зі скількома забажаєте. У TypingMind ви можете використовувати Lean Verify із будь-якою моделлю, яка підтримує навички, зокрема з GPT, Claude, Gemini, Grok, DeepSeek, Mistral чи Llama. Для цього ви використовуєте власні ключі API.

Чи безкоштовна навичка ШІ Lean Verify?

Так. На GitHub цю навичку публікує hirosassa за ліцензією MIT. Ви платите лише своєму постачальнику ШІ за використані токени.

Що таке навички ШІ?

Навичка ШІ — це набір інструкцій для повторного використання, який навчає модель ШІ виконувати одне конкретне завдання. Він відповідає відкритому формату Agent Skills: файл SKILL.md із назвою та описом, а також скрипти, шаблони чи довідкові файли, які можуть знадобитися моделі. Модель читає інструкції лише тоді, коли ваш запит відповідає навичці, тому встановлена навичка нічого не коштує, доки її не використано.

Чим навички ШІ відрізняються від плагінів або серверів MCP?

Плагін або сервер MCP надає моделі нові інструменти, які вона може викликати, — код, який десь виконується й повертає результат. Натомість навичка ШІ дає моделі знання й пояснює порядок дій: як підійти до завдання, яких кроків дотримуватися та яким має бути якісний результат. Навички — це звичайний Markdown, тож їм не потрібні ні сервер, ні ключ API, ні середовище виконання, і вони працюють із будь-якою моделлю.

Усі

Створіть власний робочий простір зі ШІ вже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇