sisi 0.1.0: a shared rulebook and verification tool for AI coding agents
ci / tests (macos-latest, python 3.11) (push) Canceled after 0s
ci / tests (macos-latest, python 3.13) (push) Canceled after 0s
ci / tests (macos-latest, python 3.9) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.11) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.13) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.9) (push) Canceled after 0s

Contracts with a ladder of checks, an end-of-turn gate, retrospectives and
shared lessons, time-to-delivery measurement, a library of 140 verification
techniques and 20 recipes, personal data kept outside the clone, and
releases with rollback. Standard library only.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-22 22:29:02 -07:00
commit 2fc1fe9c2d
223 files changed
+22163

No files matched your search

+54
View File
@@ -0,0 +1,54 @@
---
id: aeneas-rust-to-lean
title: Translating Rust to Lean with Charon and Aeneas to prove real code
answers: Can I prove a property of my actual Rust function, not of a hand-written model of it?
rung: 1
section: prove
languages: rust
kinds: general, parsing, money
cost: high
detect: aeneas --help
ran_here: no
verified: docs
---
## Use when
- The Rust is safe, mostly functional code (no heavy trait objects, little unsafe) and you want an unbounded proof about it.
- You need the proof to be about the compiled-from source, so `proof-bridging` is not enough.
## Do not use when
- A bounded proof will do. `kani` is far cheaper.
- The code uses features Charon cannot translate (many closures, async, `dyn` traits). Check what it supports first.
## Set up
Both tools are built from source; there is no package install. From the Aeneas and Charon READMEs (github.com/AeneasVerif/aeneas, .../charon): you need `rustup` (Charon pins its own nightly), OCaml 5 with opam (`opam switch create 5.3.0`, then `opam install src --deps-only --with-test` in the Aeneas checkout), and Lean. In the Aeneas checkout `make setup-charon` builds Charon at the commit in `charon-pin`, and `make` builds `bin/aeneas`. Put `charon` and `aeneas` on PATH. Not installed here, so nothing below was run.
Translate, from inside the crate:
```
charon cargo --preset=aeneas # writes <crate_name>.llbc
aeneas -backend lean my_crate.llbc -dest lean/
```
`-backend` also takes `fstar`, `coq` and `hol4`. Generated Lean files import the `Aeneas` package, so the Lean project needs it: `lake new`, copy `lean-toolchain` from `backends/lean` in the Aeneas repo, and require it in the lakefile with `[[require]] name = "aeneas" path = "PATH_TO_AENEAS_REPO/backends/lean"` (or `require aeneas from "PATH..."` in a `lakefile.lean`). Aeneas emits definitions in a `Result` monad for panics and overflow. Flags change between releases (both projects publish nightly releases); check `charon --help` and `aeneas --help`.
## Minimal example
A Rust function to prove things about:
```rust
pub fn add_cents(a: u32, b: u32) -> Option<u32> { a.checked_add(b) }
```
Aeneas emits a Lean `add_cents` returning a `Result`. You then write a theorem in a separate Lean file that says: if the result is `ok (some c)` then `c.val = a.val + b.val`, and prove it with the Aeneas tactics `step` (older releases called it `progress`; `step*` repeats it) and `scalar_tac` (arithmetic on bounded integers). The exact names and goal shapes depend on the generated code and library version, so copy the pattern from the Aeneas repository's `tests/lean/Tutorial/` (`Solutions.lean` uses `step as ⟨ ... ⟩` and `scalar_tac`). Not confirmed by running here.
## Run
`lake build --wfail` in the Lean project, after regenerating the Lean files from the current Rust.
Passing looks like: exit 0, and the audit of `lean-axiom-audit` is clean. Failure: Lean errors on the open goal.
## As a contract check
```json
{"id": "prove-add-cents-aeneas", "claim": "add_cents is exact or None, proved on the Lean translation of the Rust", "kind": "money", "rung": 1, "cmd": "bash -c 'charon cargo --preset=aeneas && aeneas -backend lean my_crate.llbc -dest lean/ && cd lean && lake build --wfail'", "expect": {"exit": 0}, "timeout_s": 3600, "tier": "deep"}
```
## What a pass does not prove
- The translation must be regenerated on every Rust change; a stale `lean/` dir proves the old code. The command above regenerates first.
- Aeneas's own semantics are trusted, and the proof assumes the Rust compiler follows them.
- Unsafe code and unsupported features are excluded or axiomatised; read the generated file for `axiom` and `opaque`.
- Not run here: the charon and aeneas invocations, `-dest`, and the tactic names were checked against the READMEs, the Aeneas command-line source and its Lean tutorial, but the example theorem was not compiled.
+67
View File
@@ -0,0 +1,67 @@
---
id: cbmc
title: CBMC bounded model checking for C
answers: Can this C code overflow, read out of bounds or break an assert for any input within a loop bound?
rung: 1
section: prove
languages: c
kinds: general, parsing
cost: medium
detect: cbmc --version
ran_here: yes
verified: ran
---
## Use when
- C code with buffers, indexes and integer arithmetic needs a check over all inputs up to a loop bound.
- You want memory-safety and overflow checks without writing a contract language.
## Do not use when
- You need unbounded proofs. Use `frama-c-wp`.
- The code is Rust. Use `kani`, which is built on CBMC.
## Set up
Install `cbmc` from your package manager or releases (github.com/diffblue/cbmc). Tried with 6.11.0, the binary that Kani bundles (`~/.kani/kani-*/bin/cbmc`). A C compiler is not needed for checking.
## Minimal example
`a.c`:
```c
#include <assert.h>
#include <stdint.h>
int clamp(int lo, int hi, int x) { return x < lo ? lo : (x > hi ? hi : x); }
uint32_t sum(const uint8_t *a, unsigned n) {
uint32_t s = 0;
for (unsigned i = 0; i < n; i++) s += a[i];
return s;
}
int main(void) {
int lo, hi, x; /* uninitialised = any value */
__CPROVER_assume(lo <= hi);
int r = clamp(lo, hi, x);
assert(lo <= r && r <= hi);
uint8_t buf[4];
unsigned n;
__CPROVER_assume(n <= 4);
assert(sum(buf, n) <= 4 * 255);
return 0;
}
```
## Run
`cbmc a.c --bounds-check --pointer-check --signed-overflow-check --unwind 5 --unwinding-assertions`
Passing looks like: `VERIFICATION SUCCESSFUL`, exit 0, and `** 0 of N failed`. Failure: `VERIFICATION FAILED` and exit 10 (seen after changing the assert to `lo < r`). `--unwinding-assertions` makes a loop that needs more iterations than `--unwind` fail instead of passing silently.
## As a contract check
```json
{"id": "prove-clamp-cbmc", "claim": "clamp stays in [lo, hi] and sum has no memory errors for n <= 4", "kind": "general", "rung": 1, "cmd": "cbmc a.c --bounds-check --pointer-check --signed-overflow-check --unwind 5 --unwinding-assertions", "expect": {"exit": 0, "stdout_contains": "VERIFICATION SUCCESSFUL"}, "tier": "deep", "timeout_s": 900}
```
## What a pass does not prove
- Only paths within the unwind bound and the `assume`s. Omit `--unwinding-assertions` and the bound is not even checked.
- An unsatisfiable `__CPROVER_assume` makes everything pass; add a reachability assertion such as `__CPROVER_assert(0, "reached")` expecting failure, or use `--cover location`, to see the point is reached.
- Library calls without a model are treated as returning any value, which may cause false alarms but not false passes.
+56
View File
@@ -0,0 +1,56 @@
---
id: creusot
title: Creusot deductive verification for Rust
answers: Does this Rust code satisfy its contracts for all inputs, proved through Why3?
rung: 1
section: prove
languages: rust
kinds: general
cost: high
detect: cargo creusot --help
ran_here: no
verified: docs
---
## Use when
- You want proofs for safe Rust including ownership-heavy code (it models borrows prophetically) and are comfortable with the Why3 ecosystem.
- Contracts as attributes (`#[requires]`, `#[ensures]`, `#[logic]`) suit you better than a separate macro block.
## Do not use when
- You need low set-up cost. Use `kani`. Creusot needs opam, Why3 and SMT solvers.
- Unsafe or heavily dynamic code is involved.
## Set up
From the Creusot README and guide ("Installation"): there is no `cargo install`. Needs `rustup`, `opam` (for Why3 and `why3find`) and `curl` (to download the provers alt-ergo, z3, cvc4 and cvc5). Then:
git clone https://github.com/creusot-rs/creusot
cd creusot
./INSTALL # a few minutes; makes a private opam switch under ~/.local/share/creusot/_opam
cargo creusot --help # check the install
Create a project with `cargo creusot new project-name`, or add the contracts crate to an existing one (the crate is now `creusot-std`, imported as `creusot_std`; if the compiler says its items are missing, the guide's troubleshooting section shows a `[patch.crates-io]` entry pointing at the checkout). Not installed here, so the example was not run.
## Minimal example
```rust
use creusot_std::prelude::*;
#[requires(a@ + b@ <= u32::MAX@)]
#[ensures(result@ == a@ + b@)]
pub fn add(a: u32, b: u32) -> u32 { a + b }
```
`x@` is the logical (mathematical) value of `x`. Spec language details change by release; follow the guide's current examples.
## Run
`cargo creusot` compiles the crate to Coma (into `verif/`) and then runs the provers through Why3find. The two steps can be run separately: `cargo creusot --only=coma` and `cargo creusot --only=prove`. A Coma file can be named to prove just that one; `-i` opens the Why3 IDE when a proof fails; `--replay` only re-checks existing proofs (`proof.json`). There is no `cargo creusot prove` subcommand in the current guide.
Passing looks like: the guide says a successful run "gives us the certainty that functions defined in this package satisfy their contracts". It does not state what the output or exit status looks like for unproved goals; check on a deliberately wrong contract that `cargo creusot` exits non-zero before relying on exit alone. Only libraries and binaries are compiled, not tests or examples.
## As a contract check
```json
{"id": "prove-add-creusot", "claim": "add returns the exact sum when it fits in u32", "kind": "general", "rung": 1, "cmd": "cargo creusot", "expect": {"exit": 0}, "timeout_s": 1800, "tier": "deep"}
```
## What a pass does not prove
- Only the contracts written; functions marked `#[trusted]` are assumed. Grep for `trusted`.
- Proofs by SMT solvers can time out; whether an unproved goal makes `cargo creusot` exit non-zero is not documented, so test it.
- Not run here; commands come from the Creusot README, guide and command-line reference. `#[trusted]` (also in the guide) skips checking of the function body, and the `x@` notation for the logical value is as in the guide's quick start.
+56
View File
@@ -0,0 +1,56 @@
---
id: crosshair
title: CrossHair symbolic checking of Python contracts
answers: Can I find any inputs that break this Python function's contract or type annotations?
rung: 2
section: prove
languages: python
kinds: general, parsing
cost: low
detect: crosshair --version
ran_here: yes
verified: ran
---
## Use when
- Pure Python functions with a docstring contract (`pre:` / `post:`) or PEP 316 / icontract / deal contracts.
- You want a solver to hunt for counterexamples before writing property tests.
- You want it to replay found inputs as ordinary tests.
## Do not use when
- The function does I/O, uses C extensions heavily or hashing-dependent logic: the solver gives up.
- You need a proof. Silence from CrossHair means "none found in the time given", so this is rung 2 here. Use `dafny`, `z3-smt` or `lean4-proofs` for rung 1.
## Set up
`pip install crosshair-tool` (5.4.1 observed; use a virtualenv). Contracts live in docstrings.
## Minimal example
`cc.py`:
```python
def clamp(lo: int, hi: int, x: int) -> int:
"""
pre: lo <= hi
post: lo <= __return__ <= hi
"""
if x < lo:
return lo
if x > hi:
return hi
return x
```
Add a function with a false postcondition to see failure, for example `post: __return__ >= 0` on `return x - 1 if x > 0 else x`.
## Run
`crosshair check cc.py --per_condition_timeout=30`
Passing looks like: no output and exit 0. Failure: a line like `cc.py:14: error: false when calling bad(-1) (which returns -1)` and exit 1 (observed). `--per_condition_timeout` bounds the search per function.
## As a contract check
```json
{"id": "prove-clamp-crosshair", "claim": "clamp satisfies its postcondition for all inputs CrossHair can find in 30 seconds", "kind": "general", "rung": 2, "cmd": "crosshair check cc.py --per_condition_timeout=30", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 600}
```
## What a pass does not prove
- A time-limited search that found nothing; it does not say it covered all paths. Raise the timeout once and see whether a failure appears.
- It checks only the contract you wrote. A weak or missing `post:` passes everything.
- Add a failing function as a canary to confirm the run really analyses your file.
+65
View File
@@ -0,0 +1,65 @@
---
id: dafny
title: Dafny verified algorithms that compile to a target language
answers: Does this algorithm meet its specification for all inputs, and can I run the verified code?
rung: 1
section: prove
languages: dafny
kinds: general, state-machine
cost: medium
detect: dafny --version
ran_here: yes
verified: ran
---
## Use when
- You are writing an algorithm or data structure from scratch and can write it in Dafny, then compile to Python, Go, Java, C# or JavaScript.
- You want pre/postconditions and loop invariants checked by an SMT solver for all inputs.
- A spec-first workflow fits: `requires`/`ensures` first, body second.
## Do not use when
- The code already exists in Rust, C or Python and must be verified as is. Use `verus`, `kani`, `frama-c-wp` or `crosshair`.
- The compiled output must meet tight performance or integration needs the target backend cannot.
## Set up
Download the release zip from github.com/dafny-lang/dafny/releases (4.11.0 tried; it includes its own runtime, Z3 included) and unzip. No global install needed: call `./dafny/dafny`.
## Minimal example
`a.dfy`:
```dafny
method Abs(x: int) returns (y: int)
ensures y >= 0 && (y == x || y == -x)
{
if x < 0 { y := -x; } else { y := x; }
}
method SumTo(n: nat) returns (s: nat)
ensures s == n * (n + 1) / 2
{
s := 0;
var i := 0;
while i < n
invariant i <= n && s == i * (i + 1) / 2
{
i := i + 1;
s := s + i;
}
}
method Main() { var r := Abs(-3); print r, "\n"; }
```
## Run
`dafny verify a.dfy`, then `dafny run --target:py a.dfy` to compile and run on Python.
Passing looks like: exit 0 and `Dafny program verifier finished with 4 verified, 0 errors`. Failure: an error with the failing line and `finished with 3 verified, 1 error`, exit 4 (observed after changing `s + i` to `s + i + 1`). Use `--verification-time-limit <seconds>` (default 30) to bound each assertion batch; a timeout is reported as an error.
## As a contract check
```json
{"id": "prove-sumto-dafny", "claim": "SumTo and Abs satisfy their postconditions for all inputs", "kind": "general", "rung": 1, "cmd": "dafny verify a.dfy", "expect": {"exit": 0, "stdout_contains": "0 errors"}, "tier": "deep", "timeout_s": 600}
```
## What a pass does not prove
- Only the written `ensures`. A weak postcondition (say `ensures true`) verifies trivially; review the specs.
- `assume` statements, `{:axiom}` and `{:verify false}` skip proof; grep for them. Termination is checked unless `decreases *` is used.
- The compiled program is trusted to match: the compiler and runtime are not verified. Target-language integers and I/O are outside the proof.
@@ -0,0 +1,65 @@
---
id: exhaustive-small-domain
title: Brute-forcing every input when the domain is small enough
answers: Does this function give the right answer for every possible input, because I tried them all?
rung: 1
section: prove
languages: any
kinds: general, money, parsing
cost: low
detect:
ran_here: yes
verified: ran
---
## Use when
- The input domain is small: every `u8`, every `u16`, every pair of `u8` (65,536), every string up to length 3 over a small alphabet.
- You have a reference you trust (a wider type, a formula, a slow obvious version) to compare against.
- A proof tool would be heavier than a loop that finishes in seconds.
## Do not use when
- The domain is `u32` pairs or larger (about 1.8e19 cases). Use `kani`, `z3-smt` or a property test (rung 2).
- You would need to sample. Sampling is a property test, not this.
## Set up
Nothing. Count the cases first: `domain_size = product of each input's range`. Keep it under roughly 1e9 for fast code and write the number in the test.
## Minimal example
```rust
#[test]
fn every_u8_is_accepted_or_refused_correctly() {
for v in 0..=u8::MAX {
assert_eq!(Percent::new(v).is_some(), v <= 100);
}
}
#[test]
fn every_u16_checked_add_matches_the_wide_sum() {
let mut n = 0u64;
for a in 0..=u16::MAX {
for b in 0..=u16::MAX {
let w = a as u32 + b as u32;
assert_eq!(a.checked_add(b).map(u32::from), (w <= 65535).then_some(w));
n += 1;
}
}
assert_eq!(n, 65_536 * 65_536); // proves the loop ran over the whole domain
}
```
In Python use `itertools.product(range(256), repeat=2)` and assert the count.
## Run
`cargo test --release every_`
Passing looks like: exit 0 and `test result: ok. 2 passed`. The full pair loop takes a few seconds in release mode. Failure: the first failing input is in the panic message.
## As a contract check
```json
{"id": "many-inputs-u16-add", "claim": "checked_add on u16 matches the exact sum for every pair of u16 values", "kind": "general", "rung": 1, "cmd": "cargo test --release every_", "expect": {"exit": 0, "stdout_contains": "test result: ok"}, "tier": "deep", "timeout_s": 600}
```
## What a pass does not prove
- It proves the claim only on that domain. A function on `u64` tested over `u16` is a sample of it, so call it rung 2 then.
- The reference answer can itself be wrong; derive it independently.
- Assert the loop count (as above) so that an edited range or an early `continue` cannot shrink the domain silently.
- If the domain is too large to finish, do not cut it down and still call it exhaustive.
+60
View File
@@ -0,0 +1,60 @@
---
id: flux-refinement-types
title: Flux refinement types for Rust
answers: Can my Rust signatures carry value constraints (positive, in range, indexes in bounds) that the compiler checks?
rung: 1
section: prove
languages: rust
kinds: general
cost: medium
detect: command -v cargo-flux
ran_here: no
verified: docs
---
## Use when
- The properties are small value constraints on arguments and results: an index below a length, a non-zero divisor, a sum within a bound.
- You want checking close to type checking, with little proof effort, and mostly automatic inference of loop invariants.
## Do not use when
- The property is relational or complex (sorted, permutation, money laws). Use `verus`, `lean4-proofs` or `kani`.
- You cannot use Flux's pinned nightly toolchain.
## Set up
From the Flux book ("Installing and Running Flux"): the only way to use Flux is to build it from source. Requirements: `rustup`, `liquid-fixpoint` (nightly binaries on its GitHub releases) and `z3` 4.15 or later, both on PATH. Then either `curl -fsSL https://raw.githubusercontent.com/flux-rs/flux/main/install.sh | bash`, or:
git clone https://github.com/flux-rs/flux && cd flux
cargo xtask install # installs `flux` and `cargo-flux`, and the sysroot in ~/.flux/sysroot
The repository's `rust-toolchain.toml` pins the nightly. To use it in a Cargo package, add to `Cargo.toml`:
[package.metadata.flux]
enabled = true
[dependencies]
flux-rs = { git = "https://github.com/flux-rs/flux.git" }
Not installed here, so the example was not run.
## Minimal example
```rust
use flux_rs::attrs::*;
#[spec(fn(x: i32{x > 0}) -> i32{v: v > x})]
fn bump(x: i32) -> i32 { x + 1 }
```
On a single file run with the standalone `flux` binary, write the attribute as `#[flux::spec(...)]` instead. Overflow of `x + 1` is checked only if you switch on `check-overflow` in the `[package.metadata.flux]` section (default `none`; see the book's "Checking Overflows"); this example passes without it.
## Run
`cargo flux` (a package), or `flux --crate-type=lib path/to/file.rs` (one file; it accepts the same flags as `rustc`).
Passing looks like: no errors reported. Failure: the book's example shows `error[FLUX]: postcondition might not hold` with the source location (a wrong body such as `x - 1`). The book does not state the exit status; the driver is a rustc wrapper and should exit non-zero on errors, but confirm with a deliberately wrong body.
## As a contract check
```json
{"id": "prove-bump-flux", "claim": "bump returns a value greater than its positive argument", "kind": "general", "rung": 1, "cmd": "cargo flux", "expect": {"exit": 0}, "timeout_s": 900, "tier": "deep"}
```
## What a pass does not prove
- Only the refinements stated in signatures; unannotated code gets default (weak) types. `#[flux_rs::trusted]` (`#[flux::trusted]` on a single file) skips checking.
- Annotations are written by you; a trivially true refinement verifies trivially.
- Not run here; commands and messages come from the Flux book. Check the check: change the body to `x - 1` and confirm `cargo flux` fails.
+51
View File
@@ -0,0 +1,51 @@
---
id: frama-c-wp
title: Frama-C WP for C with ACSL contracts
answers: Does this C function meet its contract and avoid undefined behaviour for all inputs?
rung: 1
section: prove
languages: c
kinds: general, parsing
cost: high
detect: frama-c -version
ran_here: no
verified: docs
---
## Use when
- Small, critical C functions (parsers, buffers, arithmetic, drivers) need a proof that holds for all inputs, with no unwinding bounds.
- You can write ACSL contracts (`requires`, `ensures`, `assigns`, loop invariants) in comments.
## Do not use when
- You only need a bounded check with minimal effort. Use `cbmc`.
- The code relies on heavy pointer aliasing, floating point, or concurrency without a plan.
## Set up
Install with opam (the Frama-C site's recipe: `opam init --compiler 4.14.1`, `eval $(opam env)`, `opam install frama-c`). Per the WP manual (written for Frama-C 33.0 "Arsenic", July 2026), the WP plug-in ships with Frama-C, needs the Why3 platform and at least one external prover, and opam installs Alt-Ergo and Why3 automatically; WP finds provers on `$PATH` and in the Why3 configuration. Not installed here, so nothing below was run.
## Minimal example
`abs.c`:
```c
#include <limits.h>
/*@ requires x > INT_MIN;
assigns \nothing;
ensures \result >= 0 && (\result == x || \result == -x);
*/
int my_abs(int x) { return x < 0 ? -x : x; }
```
## Run
`frama-c -wp -wp-rte -wp-timeout 20 abs.c`
Passing looks like: a line `[wp] Proved goals: N / N` (the manual shows `[wp] Proved goals: 4 / 4`; a run with a failure shows `Proved goals: 6 / 7` and an `Unknown:` count). `-wp-rte` adds the no-undefined-behaviour obligations (overflow, bounds) and `-wp-timeout` is the per-goal prover timeout in seconds (default 2). The manual does not document an exit status for unproved goals, and Frama-C is commonly seen exiting 0 with unproved goals, so the contract tests the text. Real output may pad the numbers with extra spaces, so the pattern allows them:
`frama-c ... | grep -E 'Proved goals: +([0-9]+) / \1$'` (the backreference is GNU grep).
## As a contract check
```json
{"id": "prove-abs-framac", "claim": "my_abs meets its contract and has no runtime errors when x > INT_MIN", "kind": "general", "rung": 1, "cmd": "bash -c \"frama-c -wp -wp-rte -wp-timeout 20 abs.c | tee /dev/stderr | grep -E 'Proved goals: +([0-9]+) / \\\\1$'\"", "expect": {"exit": 0}, "timeout_s": 900, "tier": "deep"}
```
## What a pass does not prove
- Only the written contract, under a memory model that assumes no aliasing the contract does not allow. `assigns` clauses must be right.
- All goals proved means none were skipped by `-wp-timeout`; a timeout counts as unproved, which the `N / N` test catches.
- Not run here; the output format is from the WP manual's examples. Confirm the exit status and spacing of the `Proved goals` line on your version, and check the check by weakening the `ensures` so a goal fails.
@@ -0,0 +1,66 @@
---
id: illegal-states-unrepresentable
title: Making illegal states unrepresentable with types, checked by a compile-fail test
answers: Is it impossible, not just unlikely, for callers to build an invalid value or call an operation in the wrong state?
rung: 1
section: prove
languages: rust, typescript
kinds: general, state-machine, money
cost: low
detect: cargo --version
ran_here: yes
verified: ran
---
## Use when
- A value has a validity rule (a percentage 0 to 100, a non-empty list, a validated email) that is currently checked in many places.
- An object has phases (closed then open, draft then posted) and calls are only legal in some of them.
- You want the compiler to reject misuse, and a test that proves it does.
## Do not use when
- The rule depends on runtime data the type cannot hold (a balance across accounts). Use a runtime check plus `kani` or tests.
- A quick enum or `Option` already forces the case. Do not add types for show.
## Set up
Rust: nothing extra. Make fields private and expose a constructor that validates (parse, don't validate: return `Option`/`Result` once at the edge, then pass the type everywhere). Use enums and exhaustive `match` with no `_` arm; use the typestate pattern with a type parameter for phases. For compile-fail tests use `compile_fail` doctests, or the `trybuild` crate (add under `[dev-dependencies]`) to compare compiler output.
TypeScript: see `typescript-type-level`.
## Minimal example
```rust
pub struct Percent(u8); // private field
impl Percent {
pub fn new(v: u8) -> Option<Percent> { (v <= 100).then_some(Percent(v)) }
pub fn get(self) -> u8 { self.0 }
}
pub struct Conn<S>(std::marker::PhantomData<S>);
pub struct Open; pub struct Closed;
impl Conn<Closed> { pub fn open(self) -> Conn<Open> { Conn(std::marker::PhantomData) } }
impl Conn<Open> { pub fn send(&self, _b: &[u8]) {} }
/// ```compile_fail
/// use ise::Percent;
/// let p = Percent(250); // private field: must not compile
/// ```
///
/// ```compile_fail
/// use ise::Conn;
/// Conn::new().send(b"x"); // a closed connection has no `send`
/// ```
pub struct CompileFailTests;
```
(Add `Conn::new() -> Conn<Closed>`.) The crate is named `ise` in the doctests.
## Run
`cargo test --doc`
Passing looks like: exit 0 and `test src/lib.rs - CompileFailTests (line N) - compile fail ... ok`. Failure: a `compile_fail` test whose code does compile shows `Test compiled successfully, but it's marked 'compile_fail'.` and exits 101. With `trybuild`, `cargo test` compares the real compiler message with a stored `.stderr` file.
## As a contract check
```json
{"id": "prove-percent-unrepresentable", "claim": "A Percent above 100 and a send on a closed connection cannot be written: both fail to compile", "kind": "general", "rung": 1, "cmd": "cargo test --doc", "expect": {"exit": 0, "stdout_contains": "compile fail"}, "tier": "deep", "timeout_s": 600}
```
## What a pass does not prove
- A `compile_fail` test passes on any compile error, including a typo. Observed: adding an error code like `compile_fail,E0451` is not enforced on stable (a wrong code still passed). Use `trybuild`, which pins the message, for tests that must fail for the right reason.
- Rules the type cannot express remain open; construction inside the defining module bypasses private-field checks. Keep the smart constructor the only way in, and review `unsafe` and `Default`/`Deserialize` impls that could build invalid values.
+54
View File
@@ -0,0 +1,54 @@
---
id: isabelle
title: Isabelle/HOL proofs with Sledgehammer
answers: Is this property proved by machine, with automatic proof search to help?
rung: 1
section: prove
languages: any
kinds: general, state-machine
cost: high
detect: isabelle version
ran_here: no
verified: docs
---
## Use when
- Your team already uses Isabelle, or you build on the Archive of Formal Proofs.
- You want strong automation: Sledgehammer calls external provers and returns a proof line to paste in.
- The claim is about algorithms or specifications over lists, sets and numbers.
## Do not use when
- You have no existing Isabelle investment. `lean4-proofs` has better command-line tooling for agents.
- A bounded check is enough (`kani`, `cbmc`).
## Set up
Download the bundle for your platform from isabelle.in.tum.de (current release: Isabelle2026, October 2026; it includes its own Java, ML system and provers). On Linux, unpack it and put its `bin/` on PATH (the install page shows `Isabelle2026/bin/isabelle`). Not installed here, so the example was not run. A session is a directory with a `ROOT` file:
```
session Demo = HOL +
theories Demo
```
## Minimal example
`Demo.thy`:
```isabelle
theory Demo imports Main begin
theorem rev_rev: "rev (rev xs) = xs"
by simp
end
```
When a goal resists, write `sledgehammer` in the interactive editor, take the proof it prints (`by (metis ...)`), and replace the call. Do not leave `sledgehammer` or `sorry` in committed files.
## Run
`isabelle build -D .` (`-D DIR` includes a session directory and selects its sessions; `-d DIR` only makes sessions known; `-j N` runs N jobs in parallel; `-v` is verbose).
Passing looks like: exit 0, with the build log reporting the session `Demo` as finished (exact wording is not in the system manual). The manual says the overall return code is the status of the set of selected sessions, so a session that fails to build gives a non-zero exit (conventionally 1) and the log names the failing theory and step. The manuals read here do not say whether a plain `isabelle build` rejects `sorry` or `oops` (or what the `quick_and_dirty` option changes), so do not rely on the build alone: grep the sources for both, as in the contract below.
## As a contract check
```json
{"id": "prove-demo-isabelle", "claim": "The Isabelle session builds and contains no sorry", "kind": "general", "rung": 1, "cmd": "bash -c 'isabelle build -D . && ! grep -R -E \"\\\\b(sorry|oops)\\\\b\" --include=*.thy .'", "expect": {"exit": 0}, "timeout_s": 3600, "tier": "deep"}
```
## What a pass does not prove
- Only the stated theorem about the Isabelle definitions.
- Not run here. `isabelle build -D`, the `ROOT` syntax and the exit-status rule come from the Isabelle system manual; whether the build itself rejects `sorry` is unconfirmed (see Run).
- The grep also flags the word inside comments, which is the safe direction. Check the check: put a `sorry` in a scratch lemma and confirm the contract fails.
+56
View File
@@ -0,0 +1,56 @@
---
id: kani-proof-hygiene
title: Keeping Kani proofs honest: covers, bounds, canary, harness list, time caps
answers: Are my Kani proofs vacuous, silently skipped, or cut off, so that "verified" means less than it says?
rung: 1
section: prove
languages: rust
kinds: general, money
cost: medium
detect: cargo kani --version
ran_here: yes
verified: ran
---
## Use when
- You have Kani harnesses and a CI check that says "all verified".
- Harnesses use `kani::assume`, `unwind`, or restricted inputs, where an over-tight bound makes a proof pass for no reason.
- The suite is slow, or you split it into fast and slow sets.
## Do not use when
- There are no Kani harnesses yet. See `kani`.
## Set up
A Rust and Lean 4 project does all of this in `justfile` with a shell wrapper around `cargo kani`. Copy the ideas, not its domain code.
## Minimal example
1. Cover every interesting case. `kani::cover!(cond, "message")` fails the check if `cond` is unreachable under the harness's assumptions:
```rust
#[kani::proof]
fn vacuous() {
let x: u8 = kani::any();
kani::assume(x > 10 && x < 5); // impossible: nothing is checked
assert!(x == 99);
kani::cover!(x > 0, "never reached");
}
```
2. A canary for a known tool bug: keep a harness marked `#[kani::should_panic]` that exercises the buggy construct; when a Kani upgrade fixes the bug it starts failing and tells you to drop the workaround.
3. A harness list check: enumerate harnesses (`grep` for `#[kani::proof]`), then fail on duplicate names and on a name in the slow list that no harness has.
4. Time caps: `cargo kani -j "$(nproc)" -Z unstable-options --harness-timeout 900s`, and wrap the run in `timeout 1800`.
## Run
`cargo kani --output-format terse | tee kani.log` then
`grep -E '\*\* [0-9]+ of [0-9]+ cover properties satisfied' kani.log | awk '$2 != $4 {bad=1} END {exit bad}'`
Passing looks like: for the vacuous harness above, Kani itself prints `** 0 of 1 cover properties satisfied (1 unreachable)` yet `VERIFICATION:- SUCCESSFUL` and exits 0 (observed, 0.68.0). The awk line then exits 1; that is how the check catches it. Also require the line `Complete - N successfully verified harnesses, 0 failures, N total` with N equal to the number of harnesses you listed. A timed-out harness is reported, not silently passed; a missing line means the run was cut off.
## As a contract check
```json
{"id": "prove-kani-honest", "claim": "All Kani harnesses verify, the expected number ran, and every cover! is satisfiable", "kind": "general", "rung": 1, "cmd": "bash scripts/kani-check.sh", "expect": {"exit": 0, "stdout_contains": "successfully verified harnesses"}, "tier": "deep", "timeout_s": 3600}
```
`scripts/kani-check.sh` runs steps 3 and 4 and the awk test above.
## What a pass does not prove
- `cover!` shows each marked case is reachable, not that your marks cover all the cases that matter. Add one for each branch a reviewer would ask about.
- A harness proved on a smaller representation (e.g. `i64`) says nothing about the real type; see `proof-bridging`.
- The canary only watches the one bug you thought of. `--harness-timeout` needs `-Z unstable-options` and may change; check `cargo kani --help` after upgrades.
+67
View File
@@ -0,0 +1,67 @@
---
id: kani
title: Kani bounded model checking for Rust
answers: Can this Rust function panic, overflow or break an assertion for any input within a bound?
rung: 1
section: prove
languages: rust
kinds: general, money, parsing
cost: medium
detect: cargo kani --version
ran_here: yes
verified: ran
---
## Use when
- A small, mostly pure function (money arithmetic, index maths, bounded parsers, state transitions) must hold for all inputs, not a sample.
- You want "cannot panic or overflow" for every value of the input types, such as every `u32`.
- A property test would be the next best thing but you want a proof within the bound.
## Do not use when
- The claim needs unbounded sizes or heavy loops over big data; use `lean4-proofs` or `verus`.
- The function does I/O, threads or unsupported FFI.
- You have not read `kani-proof-hygiene`. A Kani pass can be vacuous.
## Set up
`cargo install --locked kani-verifier && cargo kani setup` (once; downloads a nightly toolchain and CBMC). Put harnesses under `#[cfg(kani)]` so normal builds ignore them.
## Minimal example
`src/lib.rs`:
```rust
pub fn add_cents(a: u32, b: u32) -> Option<u32> { a.checked_add(b) }
#[cfg(kani)]
mod proofs {
use super::*;
#[kani::proof]
fn add_cents_is_exact_or_none() {
let a: u32 = kani::any();
let b: u32 = kani::any();
let wide = a as u64 + b as u64;
match add_cents(a, b) {
Some(s) => assert_eq!(s as u64, wide),
None => assert!(wide > u32::MAX as u64),
}
kani::cover!(add_cents(a, b).is_none(), "overflow case reachable");
kani::cover!(add_cents(a, b).is_some(), "ok case reachable");
}
}
```
Loops need `#[kani::unwind(N)]`; restrict inputs with `kani::assume(...)`, sparingly.
## Run
`cargo kani --output-format terse`
Passing looks like: exit 0, `2 of 2 cover properties satisfied`, `VERIFICATION:- SUCCESSFUL` and `Complete - 1 successfully verified harnesses, 0 failures, 1 total.` (Kani 0.68.0). Failure: `VERIFICATION:- FAILED` with the failing check and a nonzero exit. To select one harness use `--harness <fully::qualified::name> --exact`; an unqualified name with `--exact` is refused.
## As a contract check
```json
{"id": "prove-add-cents-kani", "claim": "add_cents never wraps: Some(sum) is exact and None only when the sum exceeds u32::MAX", "kind": "money", "rung": 1, "cmd": "cargo kani --output-format terse", "expect": {"exit": 0, "stdout_contains": "successfully verified harnesses, 0 failures"}, "tier": "deep", "timeout_s": 1800}
```
## What a pass does not prove
- Only inputs within the harness: `unwind` bounds, array lengths, `kani::assume`. Beyond them nothing is claimed.
- An over-tight `assume` or unreachable code makes the pass vacuous. See `kani-proof-hygiene`.
- Harness code can be wrong. Confirm each harness can fail: flip an assertion and see `FAILED`.
- Its model of the standard library has gaps (e.g. known bugs on bulk copies of symbolic length); a pass is not a statement about the real binary.
+72
View File
@@ -0,0 +1,72 @@
---
id: klee
title: KLEE symbolic execution of C programs
answers: Which inputs make this C program crash, overflow or break an assert, found by exploring its paths?
rung: 1
section: prove
languages: c, c++
kinds: general, parsing
cost: high
detect: klee --version
ran_here: no
verified: docs
---
## Use when
- C programs or functions with many branches where you want generated inputs that reach each path and trigger errors.
- You want concrete test cases for each path as a by-product.
## Do not use when
- You want a simpler tool: `cbmc` is easier to run and gives a proof within a bound.
- The code does a lot of I/O, threads, floating point or deep loops over symbolic sizes.
## Set up
Easiest is the Docker image (from the KLEE Docker page; 3.0 is the current tag there):
docker pull klee/klee:3.0
docker run --rm -ti --ulimit='stack=-1:-1' klee/klee:3.0 # then `klee --version` inside
The `--ulimit` avoids stack overflows inside KLEE. Building from source needs LLVM (the site recommends LLVM 18), clang and an SMT solver; see klee-se.org. Programs include `klee/klee.h`; compile with `-I` pointing at KLEE's `include` directory. Not installed here, so the example was not run.
## Minimal example
`a.c`:
```c
#include <klee/klee.h>
int clamp(int lo, int hi, int x) { return x < lo ? lo : (x > hi ? hi : x); }
int main(void) {
int lo, hi, x;
klee_make_symbolic(&lo, sizeof lo, "lo");
klee_make_symbolic(&hi, sizeof hi, "hi");
klee_make_symbolic(&x, sizeof x, "x");
klee_assume(lo <= hi);
int r = clamp(lo, hi, x);
klee_assert(lo <= r && r <= hi);
return 0;
}
```
## Run
```
clang -I /path/to/klee/include -emit-llvm -c -g -O0 -Xclang -disable-O0-optnone a.c -o a.bc
klee a.bc
```
The tutorial says `-O0 -Xclang -disable-O0-optnone` is preferred over plain `-O0` on LLVM newer than 5.0. Output goes to `klee-out-N/` (lowest unused N) with a `klee-last` symlink to the newest.
Passing looks like (from the tutorial):
KLEE: done: total instructions = 33
KLEE: done: completed paths = 3
KLEE: done: partially completed paths = 0
KLEE: done: generated tests = 3
with no `KLEE: ERROR` lines and no `test*.err` files in `klee-last/`. Failure: `KLEE: ERROR: ... ASSERTION FAIL` and a file `test000001.assert.err` next to the `.ktest` that reproduces it (the file docs give the pattern `test<N>.<error-type>.err`; `ktest-tool` prints a `.ktest`). The KLEE docs fetched do not state the exit status; KLEE is generally reported to exit 0 even when it found errors, so test for the `.err` files rather than the exit code, and confirm that on your version.
## As a contract check
```json
{"id": "prove-clamp-klee", "claim": "KLEE finds no assertion failure or memory error in clamp", "kind": "general", "rung": 1, "cmd": "bash -c 'klee a.bc && ! ls klee-last/*.err 2>/dev/null'", "expect": {"exit": 0}, "timeout_s": 1800, "tier": "deep"}
```
## What a pass does not prove
- Only completes if exploration ends before limits (`--max-time`, `--max-memory`); if it stops early the pass is partial. Look for "partially completed paths = 0".
- Symbolic sizes and the modelled environment (`--posix-runtime`, `--libc=uclibc`) bound what is covered.
- Commands and output come from the KLEE tutorial and docs, not from a run here.
+53
View File
@@ -0,0 +1,53 @@
---
id: lean-axiom-audit
title: Making a Lean proof trustworthy: no sorry, only the standard axioms
answers: Does my Lean proof really prove the theorem, or does it rely on sorry or an extra axiom?
rung: 1
section: prove
languages: any
kinds: general
cost: low
detect: lake --version
ran_here: yes
verified: ran
---
## Use when
- A Lean project is the evidence for a claim and a green `lake build` must mean the proof is complete.
- An agent wrote or edited proofs; `sorry`, `axiom` and `native_decide` are easy to slip in.
- You want a CI step that fails on anything but the standard axioms.
## Do not use when
- There is no Lean proof. See `lean4-proofs`.
## Set up
List the theorems that carry the claim in one file, `Audit.lean`, so the list is reviewed in one place:
```lean
import Demo
#print axioms clamp_le
#print axioms add_zero'
```
## Minimal example
```
lake build --wfail
lake env lean Audit.lean | tee audit.txt
! grep -v -E "depends on axioms: \[(propext|Quot.sound|Classical.choice)(, (propext|Quot.sound|Classical.choice))*\]$|does not depend on any axioms" audit.txt
```
The third line fails if any output line is not one of the allowed forms. The three allowed axioms are `propext`, `Classical.choice`, `Quot.sound`. This is the filter a Rust and Lean 4 project uses in its `prove` recipe.
## Run
Put the three lines in a script, `audit-lean.sh`, with `set -euo pipefail`.
Passing looks like: exit 0 and output such as `'clamp_le' depends on axioms: [propext, Classical.choice, Quot.sound]`. Failure shows `depends on axioms: [sorryAx]` for a theorem that uses `sorry` (observed: `lake build` itself exited 0 and only warned; `--wfail` made it exit 1). `native_decide` shows `Lean.ofReduceBool`, and a custom `axiom` appears by name; both fail the filter.
## As a contract check
```json
{"id": "prove-lean-axioms", "claim": "The Lean theorems depend on no sorry and only the three standard axioms", "kind": "general", "rung": 1, "cmd": "bash audit-lean.sh", "expect": {"exit": 0, "stdout_contains": "depends on axioms"}, "tier": "deep", "timeout_s": 1800}
```
## What a pass does not prove
- That the theorem statements say what you meant. Axiom-clean proofs of the wrong statement pass.
- Only theorems listed in `Audit.lean` are audited; a new theorem not listed is not. Compare the list against the project's theorems in review, or generate it.
- A trailing `sorry` in a file `Audit.lean` does not import is not seen; build the whole library.
- If `Audit.lean` prints nothing (a typo in a name raises an error, which is good) make sure the script checks that the output is non-empty.
+56
View File
@@ -0,0 +1,56 @@
---
id: lean4-proofs
title: Proving properties in Lean 4 with a lake project and lake build
answers: Is this property true for all inputs, with a machine-checked proof rather than tests?
rung: 1
section: prove
languages: any
kinds: general, money, state-machine
cost: high
detect: lake --version
ran_here: yes
verified: ran
---
## Use when
- The claim is a law over all inputs of a function you can write in Lean (or a model of your code): sums are conserved, a rounding step is within half a unit, an operation is its own inverse.
- Tests and Kani only cover bounded cases and you need the law at any size.
- You can state the law as a `theorem` and let `lake build` be the judge.
## Do not use when
- The code under test is Rust or C and you need the proof about that code. Use `aeneas-rust-to-lean`, `kani` or `verus`.
- The property is a quick bounded check. `kani` or `exhaustive-small-domain` cost far less.
## Set up
```
lake new demo # then in lakefile.toml set defaultTargets = ["Demo"] and delete the lean_exe stanza and Main.lean
cd demo
```
`lean-toolchain` pins the Lean version; commit it and `lake-manifest.json`. Mathlib is optional: add `[[require]] name = "mathlib" scope = "leanprover-community"` to `lakefile.toml` only when you need it (a first build downloads a large cache; run `lake exe cache get`). Without Mathlib, the tactics `simp`, `omega` and `decide` already handle most arithmetic.
## Minimal example
`Demo/Basic.lean`:
```lean
def clamp (lo hi x : Nat) : Nat := if x < lo then lo else if hi < x then hi else x
theorem clamp_le (lo hi x : Nat) (h : lo ≤ hi) :
lo ≤ clamp lo hi x ∧ clamp lo hi x ≤ hi := by
unfold clamp
split <;> (try split) <;> omega
```
The agent loop: edit, run `lake build`, read the error (it shows the unsolved goal), adjust. Put `sorry` in one place at a time to see the goal, then replace it. `lake env lean Demo/Basic.lean` checks one file faster.
## Run
`lake build --wfail`
Passing looks like: exit 0 with lines like `✔ Built Demo.Basic`. A wrong proof gives `error:` with the goal and exit 1 (observed). Plain `lake build` exits 0 even when a proof contains `sorry` (it only warns), so use `--wfail` and the audit in `lean-axiom-audit`.
## As a contract check
```json
{"id": "prove-clamp-lean", "claim": "clamp stays within [lo, hi] for all Nat inputs, proved in Lean 4", "kind": "general", "rung": 1, "cmd": "lake build --wfail", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 1800}
```
## What a pass does not prove
- It proves the theorem about the Lean definition. If the definition is not the real code, add a bridge (`proof-bridging`, `aeneas-rust-to-lean`).
- A theorem that is easier than the claim (wrong statement, hypotheses that cannot hold) builds fine. Read the statement, and prove a non-trivial instance with `example`.
- `sorry` and extra axioms pass the build; see `lean-axiom-audit`.
+57
View File
@@ -0,0 +1,57 @@
---
id: liquid-haskell
title: LiquidHaskell refinement types for Haskell
answers: Do my Haskell functions respect value constraints (non-zero divisors, in-range indexes, length-preserving) for all inputs?
rung: 1
section: prove
languages: haskell
kinds: general
cost: medium
detect: ghc --version
ran_here: no
verified: docs
---
## Use when
- Haskell code where totality and value constraints matter: safe division, bounds, sorted or length-indexed lists.
- You want checks written as comments next to the types, so the code still compiles with plain GHC.
## Do not use when
- The code is not Haskell. See the entries for your language.
- The GHC version you need is newer than the LiquidHaskell release supports: only one GHC version is supported at a time (currently 9.14.1).
## Set up
From the LiquidHaskell README: install Z3 4.15.1 or newer on PATH, then in the project directory
cabal install --lib liquidhaskell liquid-prelude liquid-vector --package-env . --force-reinstalls
(`--package-env .` writes a `.ghc.environment*` file so only GHC runs started from this directory see the plugin). Put `{-# OPTIONS_GHC -fplugin=LiquidHaskell #-}` at the top of each checked module. LiquidHaskell supports exactly one GHC version at a time: the latest release (v0.9.14.1, May 2026) builds with GHC 9.14.1, and the previous release (v0.9.12.2) is the last one for GHC 9.12.2. Use the LiquidHaskell release that matches your GHC. Not installed here (no Haskell toolchain), so the example was not run.
## Minimal example
```haskell
{-# OPTIONS_GHC -fplugin=LiquidHaskell #-}
module Safe where
{-@ safeDiv :: Int -> {v:Int | v /= 0} -> Int @-}
safeDiv :: Int -> Int -> Int
safeDiv x y = x `div` y
ok :: Int
ok = safeDiv 10 2
-- bad = safeDiv 10 0 -- uncomment: rejected at compile time
```
## Run
`ghc -fplugin=LiquidHaskell Safe.hs` (the README's command), or in a Cabal project add `-fplugin=LiquidHaskell` to `ghc-options` with `liquidhaskell` and `liquid-prelude` in `build-depends` and run `cabal build`. GHC does not rerun the plugin on modules it considers up to date, so after a first pass force a rebuild (`-fforce-recomp`, or touch the file) before trusting a pass.
Passing looks like: the compile succeeds. Failure: a refinement type error from the plugin at the offending call, and a failed compile (non-zero exit as for any GHC error). The exact error wording (older versions printed `Liquid Type Mismatch`; the older `liquid Safe.hs` printed `LIQUID: SAFE`) was not confirmed here.
## As a contract check
```json
{"id": "prove-safediv-liquid", "claim": "safeDiv is never called with a zero divisor", "kind": "general", "rung": 1, "cmd": "ghc -fforce-recomp -fplugin=LiquidHaskell Safe.hs", "expect": {"exit": 0}, "timeout_s": 1800, "tier": "deep"}
```
## What a pass does not prove
- Only annotated specs; `{-@ lazy @-}`, `assume` and `{-@ LIQUID "--no-termination" @-}` weaken or skip checking. Grep for them.
- Modules without the plugin line are not checked at all; make sure the plugin line is on every module that matters.
- Not run here; commands come from the LiquidHaskell README. Check the check: uncomment `bad = safeDiv 10 0` and confirm the compile fails.
+57
View File
@@ -0,0 +1,57 @@
---
id: proof-bridging
title: Bridging a proof on a simplified type to the real type with a differential test
answers: My proof was done on a simpler representation (like i64); does the real code (like Decimal) behave the same?
rung: 2
section: prove
languages: any
kinds: money, general
cost: medium
detect:
ran_here: yes
verified: ran
---
## Use when
- A proof tool handles only a simple model (Kani on `i64`, Lean on `Nat`, Dafny on `int`) and the production code uses another type (`Decimal`, `BigInt`, floating point, a struct).
- You want to say the proof carries over to the real code, with evidence you can run.
## Do not use when
- You can prove the real type directly (`aeneas-rust-to-lean`, `verus`). Do that instead.
- The two types differ in the property you proved (rounding, overflow, ordering): then the bridge must show where they agree, and the claim shrinks to that region.
## Set up
Write the model function and the real function with the same shape. In the test, generate inputs, run both, convert the model result to the real type, and assert equal. Include an independent exact reference (a big-integer or rational one) as a third voice when the model is lossy. Use `proptest` in Rust or `hypothesis` in Python for random inputs, plus a fixed list of edge cases (zero, minimum, maximum, ties, negatives).
## Minimal example
```rust
fn halve_model(x: i64) -> i64 { x / 2 } // what the proof covers
fn halve_real(x: i128) -> i128 { x / 2 } // what production runs (wider type)
#[test]
fn bridge_agrees() {
let mut s: u64 = 0x9E37_79B9_7F4A_7C15; // fixed seed: reproducible
for _ in 0..100_000 {
s ^= s << 13; s ^= s >> 7; s ^= s << 17; // xorshift
let x = s as i64;
assert_eq!(halve_model(x) as i128, halve_real(x as i128));
}
}
```
State in the test's doc comment which proof it carries (`kani proof halve_is_floor`), over which inputs, and what is assumed equal.
## Run
`cargo test bridge`
Passing looks like: exit 0 and `test tests::bridge_agrees ... ok`. Failure: the first disagreeing input in the panic message.
## As a contract check
```json
{"id": "prove-bridge-i64-to-wide", "claim": "The real halve agrees with the proved i64 model on 100000 seeded inputs and the edge cases", "kind": "money", "rung": 2, "cmd": "cargo test bridge", "expect": {"exit": 0, "stdout_contains": "test result: ok"}, "tier": "deep", "timeout_s": 600}
```
## What a pass does not prove
- It samples, so the bridge is rung 2, and the proved claim for the real type is only as strong as the bridge. Say so in the contract claim.
- The bridge must show: same results where both are defined; both refuse (error or `None`) on the same inputs; behaviour at the model's bounds; and every wrapper between the proof and the real call. A wrapper that is not in the bridge is unproved.
- Compare against an independent exact reference where the model truncates (for example integer division drops fractions that `Decimal` keeps), or you test two things that share a flaw.
- Generators that rarely hit edges miss them; list ties, zero, min and max explicitly.
+48
View File
@@ -0,0 +1,48 @@
---
id: prusti
title: Prusti verification for Rust
answers: Does this Rust function satisfy its pre- and postconditions for all inputs?
rung: 1
section: prove
languages: rust
kinds: general
cost: high
detect: cargo prusti --version
ran_here: no
verified: docs
---
## Use when
- You are already on a Rust toolchain Prusti supports and want Viper-based proofs with contract attributes.
- The code is safe Rust with moderate complexity, and unbounded proofs are needed.
## Do not use when
- Status, checked on the repository: Prusti is not abandoned. It moved from `viperproject/prusti-dev` to `prusti/prusti`, has commits almost daily in November 2026 and publishes nightly pre-release builds. But its last non-pre-release was in February 2024 (`v-2024-02-28-1817`), and the user guide warns that some syntax it describes exists only in the "LatestDev" build. Expect the stable binary to be old; on current Rust prefer `verus`, `creusot` or `kani`, and check which Rust toolchain your Prusti build pins (the repository's `rust-toolchain` pins a nightly, `nightly-2026-08-15` at the time of writing).
- Your Rust is recent and you want the old stable build: it supports only the nightly it was built against, so it often cannot compile modern crates.
## Set up
Download a precompiled build from github.com/prusti/prusti/releases (Ubuntu, Windows, macOS; "Pre-release" builds are the current ones), or use the VS Code extension "Prusti Assistant", or build from source (`rustup`, `./x.py setup`, `./x.py build --release`). Every option provides `prusti-rustc` and `cargo-prusti`. Add the contracts crate to the project with `cargo add prusti-contracts` and put `use prusti_contracts::*;` in the file. Not installed here, so the example was not run.
## Minimal example
```rust
use prusti_contracts::*;
#[requires(a >= 0 && a < i32::MAX)]
#[ensures(result == a + 1)]
fn inc(a: i32) -> i32 { a + 1 }
```
## Run
`cargo prusti` from the crate root (Prusti on a single file: `prusti-rustc --edition=2018 path/to/file.rs`). By default Prusti also verifies absence of integer overflow and of reachable `panic!`/`unreachable!`; a `Prusti.toml` can switch overflow checks off.
Passing looks like: the guide says "Prusti should report that verification succeeded" (exact message not quoted there). Failure is reported like a compiler error with the prefix `Prusti: verification error`, for example `error: [Prusti: verification error] statement might panic`. The guide does not state the exit status; as a rustc wrapper it should exit non-zero on errors, but confirm with a wrong postcondition.
## As a contract check
```json
{"id": "prove-inc-prusti", "claim": "inc returns a + 1 for every a below i32::MAX", "kind": "general", "rung": 1, "cmd": "cargo prusti", "expect": {"exit": 0}, "timeout_s": 1800, "tier": "deep"}
```
## What a pass does not prove
- Only annotated functions; `#[trusted]` ones are assumed. Grep for it.
- Quantifiers and loops need invariants that the tool may fail to use, giving false alarms rather than false passes.
- Not run here; commands come from the Prusti README and user guide. The guide itself notes some syntax needs the LatestDev build, so the snippet may differ by version.
+56
View File
@@ -0,0 +1,56 @@
---
id: rocq
title: Rocq (formerly Coq) proofs, and when to pick it over Lean
answers: Is this property proved by machine, in a prover with a large existing library of verified programs?
rung: 1
section: prove
languages: any
kinds: general, state-machine
cost: high
detect: rocq --version
ran_here: no
verified: docs
---
## Use when
- You depend on an existing Rocq development (CompCert, Iris, VST, Fiat Crypto, MathComp) or the team already knows it.
- You need extraction of verified code to OCaml or Haskell.
- The proof is about C via VST, or concurrent separation logic via Iris.
## Do not use when
- You are starting fresh and have no reason to prefer it. Prefer `lean4-proofs`: faster builds, better agent tooling, and `lake build` as one oracle.
- A bounded check will do (`kani`, `cbmc`).
## Set up
Install through opam (version 2.1 or newer). Rocq packages are not in the default opam repository, so add theirs first:
opam repo add rocq-released https://rocq-prover.org/opam/released
opam install rocq-prover
rocq -v
The package is `rocq-prover` (the old name was `coq`); the binary is `rocq`, and the batch compiler is `rocq compile` (alias `rocq c`). The current reference manual documents only `rocq`-prefixed commands and does not mention `coqc`, so on a modern install use `rocq compile`; an older `coq` install has `coqc`. Not installed here, so nothing was run.
For a Dune build (the manual calls Dune support experimental), `dune-project` has a `(lang dune 3.x)` line and `(using rocq 0.14)` (Dune docs, Dune 3.25; the Rocq language version is not the Rocq version), and a `dune` file has `(rocq.theory (name Demo))`. Without Dune: `rocq makefile -f _CoqProject -o CoqMakefile`, then `make -f CoqMakefile`.
## Minimal example
`Demo.v`:
```coq
Theorem add_zero_r : forall n : nat, n + 0 = n.
Proof. intros n. induction n; simpl; auto. Qed.
Print Assumptions add_zero_r.
```
## Run
`dune build` (or `rocq compile Demo.v` for one file; name the logical path with `-Q . Demo` when needed; the file name must be a valid identifier, so `to-to.v` fails).
Passing looks like: exit 0 (the manual does not document `rocq compile` exit codes; a Rocq error such as an unsolved goal fails the compile and Dune reports it). `Print Assumptions add_zero_r.` prints `Closed under the global context` when no axioms are used; any listed axiom, or `Admitted.` in the source, means the proof is incomplete. Dune normally hides the output of successful rules, so to see the `Print Assumptions` line compile the file directly with `rocq compile`, and grep the sources as well.
## As a contract check
```json
{"id": "prove-demo-rocq", "claim": "The Rocq development builds with no Admitted lemmas", "kind": "general", "rung": 1, "cmd": "bash -c 'dune build && ! grep -R -E \"Admitted|admit\\.\" --include=*.v .'", "expect": {"exit": 0}, "timeout_s": 3600, "tier": "deep"}
```
## What a pass does not prove
- Only the stated theorem about the Rocq definitions; the link to real code is a separate problem (`proof-bridging`).
- `Admitted` and `Axiom` pass the build; the grep and `Print Assumptions` catch them.
- Not run here. The opam commands, `rocq compile` and the Dune stanzas come from the Rocq install page, refman and Dune docs; the exit status of `rocq compile` is not documented in them.
+70
View File
@@ -0,0 +1,70 @@
---
id: spark-ada
title: SPARK (Ada) proofs with GNATprove
answers: Is this Ada code free of runtime errors and does it meet its contracts, proved?
rung: 1
section: prove
languages: ada
kinds: general
cost: medium
detect: gnatprove --version
ran_here: no
verified: docs
---
## Use when
- The project is in Ada and needs absence of runtime errors (overflow, range, index) or functional contracts proved.
- Safety standards ask for proof evidence.
## Do not use when
- The code is not Ada. Choose the entry for its language.
## Set up
Get GNATprove from Alire (`alr with gnatprove` in an Alire project, then `eval $(alr printenv)`), or install a GNAT toolchain plus GNATprove from AdaCore (see the SPARK user guide, "Installation of GNATprove"). Put `SPARK_Mode` on the code to prove (`pragma SPARK_Mode (On);` in a package spec and body, or `with SPARK_Mode` on declarations) and have a project file. Not installed here, so the example was not run.
`proj.gpr`:
project Proj is
for Source_Dirs use (".");
for Object_Dir use "obj";
end Proj;
## Minimal example
`bounds.ads`:
package Bounds with SPARK_Mode is
function Clamp (Lo, Hi, X : Integer) return Integer
with Pre => Lo <= Hi,
Post => Clamp'Result in Lo .. Hi;
end Bounds;
`bounds.adb`:
package body Bounds with SPARK_Mode is
function Clamp (Lo, Hi, X : Integer) return Integer is
begin
if X < Lo then return Lo;
elsif X > Hi then return Hi;
else return X;
end if;
end Clamp;
end Bounds;
GNATprove checks the postcondition and every runtime check in the body.
## Run
`gnatprove -P proj.gpr --level=2 --checks-as-errors=on`
`--level` runs from 0 (fast) to 4 (most powerful); level 2 is cvc5, z3 and Alt-Ergo with a 5 second timeout and counterexamples on. Raise the level or `--timeout` when a prover cannot decide.
Passing looks like: exit 0 and a summary table in which every check is "Proved". Failure shows messages such as `medium: postcondition might fail` and, only with `--checks-as-errors=on`, exits non-zero. The SPARK user guide states that GNATprove otherwise "returns with an exit status of zero, even when unproved check messages and warnings are issued". Use `--warnings=error` as well if warnings should fail the run.
## As a contract check
```json
{"id": "prove-clamp-spark", "claim": "Clamp has no runtime errors and satisfies its postcondition", "kind": "general", "rung": 1, "cmd": "gnatprove -P proj.gpr --level=2 --checks-as-errors=on", "expect": {"exit": 0}, "timeout_s": 1800, "tier": "deep"}
```
## What a pass does not prove
- Only code in `SPARK_Mode`; code outside it (`SPARK_Mode => Off`) is assumed. Search for `pragma Assume` and `Annotate`.
- Only contracts as written.
- Without `--checks-as-errors=on` a run with unproved checks still exits 0, so a contract on the exit code alone would pass vacuously. Commands and exit-status behaviour come from the SPARK user guide, not from a run here.
+68
View File
@@ -0,0 +1,68 @@
---
id: typescript-type-level
title: TypeScript strict mode, branded types, exhaustive never checks, type tests
answers: Does the TypeScript compiler reject misuse of this API: wrong units, unhandled cases, invalid states?
rung: 1
section: prove
languages: typescript
kinds: general, money, state-machine
cost: low
detect: npx --no-install tsc --version
ran_here: yes
verified: ran
---
## Use when
- Values are easy to mix up (cents vs dollars, user id vs order id) and you want the compiler to stop it.
- A union grows over time and every `switch` over it must handle new members.
- You want type-level behaviour tested, so a refactor cannot silently weaken a type.
## Do not use when
- The rule is about runtime values only. A brand does not validate; it needs a smart constructor that does.
- You wrote `as any` or `// @ts-ignore` to get it to compile; the check is then worthless.
## Set up
`npm i -D typescript` (7.0.2 tried; `tsd` 0.33 for dedicated type tests). `tsconfig.json`: `{"compilerOptions": {"strict": true, "noEmit": true, "target": "ES2022", "module": "ES2022", "moduleResolution": "bundler", "types": []}, "include": ["src"]}`.
## Minimal example
`src/brand.ts`:
```ts
declare const brand: unique symbol;
export type Cents = number & { readonly [brand]: "Cents" };
export function cents(n: number): Cents {
if (!Number.isInteger(n)) throw new RangeError("cents must be an integer");
return n as Cents;
}
export type Shape = { kind: "circle"; r: number } | { kind: "square"; s: number };
export function area(sh: Shape): number {
switch (sh.kind) {
case "circle": return 3 * sh.r * sh.r;
case "square": return sh.s * sh.s;
default: { const _x: never = sh; return _x; } // fails if a case is missing
}
}
export function pay(_c: Cents): void {}
```
`src/brand.test-d.ts` (type test, type-checked only, never run):
```ts
import { pay, cents } from "./brand";
pay(cents(5));
// @ts-expect-error a plain number is not Cents
pay(5);
```
`@ts-expect-error` itself fails the build if the next line has no error, so the test cannot rot.
## Run
`npx tsc -p .`
Passing looks like: no output, exit 0. Failure: `error TS2345: Argument of type 'number' is not assignable to parameter of type 'Cents'` (removing the `@ts-expect-error` line), or `Type '{ kind: "square"; ... }' is not assignable to type 'never'` after deleting the `square` case; exit 2 or 1 (nonzero). With `tsd`, run `npx tsd` and use `expectError` and `expectType`.
## As a contract check
```json
{"id": "prove-cents-brand", "claim": "A plain number cannot be passed where Cents is required, and area handles every Shape", "kind": "general", "rung": 1, "cmd": "npx tsc -p .", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300}
```
## What a pass does not prove
- Types are erased at runtime; data arriving from JSON or the network is unchecked unless parsed by a validator (zod and similar) that returns the branded type.
- `any`, `as` casts, `@ts-ignore` and `@ts-expect-error` placed on the wrong line defeat it. Grep for them and add `noImplicitAny` (part of `strict`).
- TypeScript's type system is intentionally unsound in places (array covariance, index access without `noUncheckedIndexedAccess`).
+64
View File
@@ -0,0 +1,64 @@
---
id: verus
title: Verus deductive verification for Rust
answers: Does this Rust code meet its requires/ensures specification for all inputs, with no size bound?
rung: 1
section: prove
languages: rust
kinds: general, state-machine
cost: high
detect: verus --version
ran_here: no
verified: docs
---
## Use when
- You write new Rust (or a core module) that needs unbounded proofs: data structures, allocators, protocols, algorithms with loops.
- You can accept writing specs and loop invariants inline in the Rust file, and ghost code.
- `kani` bounds are too small and a separate Lean model would drift from the code.
## Do not use when
- You need to verify existing unmodified Rust with traits and iterators everywhere: Verus supports a subset.
- A bounded proof is enough. `kani` takes minutes to set up.
## Set up
Download a release binary from github.com/verus-lang/verus/releases (the weekly point releases are recommended), unzip it, and run `./verus`. It tells you which `rustup` toolchain it pins (for example `rustup install 1.86.0-x86_64-unknown-linux-gnu`) and how to install it; repeat until `./verus` stops complaining. For a Cargo project the release also ships `cargo-verus`; put both on PATH, then `cargo verus new --bin my_project`, or in an existing crate `cargo add vstd` and add `[package.metadata.verus]` with `verify = true` to `Cargo.toml` (details in the guide chapter "Using Verus via Cargo"). Not installed here, so the example was not run.
## Minimal example
`max.rs`:
```rust
use vstd::prelude::*;
verus! {
fn max(a: u32, b: u32) -> (r: u32)
ensures r >= a, r >= b, r == a || r == b
{
if a > b { a } else { b }
}
} // verus!
fn main() {}
```
Loops need `invariant` and `decreases` clauses; arithmetic overflow is a proof obligation unless the type is `int`.
## Run
`verus max.rs`, or in a Cargo project `cargo verus verify` (not `cargo verus focus`, which skips the proofs of dependencies).
Passing looks like (from the guide):
note: verifying root module
verification results:: 1 verified, 0 errors
Failure prints `error: assertion failed` (or a failed `ensures`) with the source location, then `error: aborting due to previous error` and `verification results:: 0 verified, 1 errors`. The guide does not state the process exit status; Verus is a rustc-based driver and should exit non-zero on errors, but confirm it with a deliberately wrong spec before relying on exit alone. The contract below also checks the text. `verus file.rs --compile` additionally builds a binary.
## As a contract check
```json
{"id": "prove-max-verus", "claim": "max returns one of its arguments and is at least both", "kind": "general", "rung": 1, "cmd": "verus max.rs", "expect": {"exit": 0, "stdout_contains": "verified, 0 errors"}, "timeout_s": 900, "tier": "deep"}
```
## What a pass does not prove
- Only the `ensures` you wrote and only functions inside `verus!`; code outside it is trusted. Search for `#[verifier::external]`, `assume(`, `admit(` and `external_body`, which skip proof.
- Verus and its trusted specs of `vstd` are part of what you trust.
- Check the check can fail: weaken the body and confirm an error appears, and that the exit status is non-zero.
- Commands and output format were read from the Verus guide and INSTALL.md, not run here.
+55
View File
@@ -0,0 +1,55 @@
---
id: z3-smt
title: Encoding a property directly for Z3 (Python or SMT-LIB)
answers: Does a counterexample to this property exist, found by a solver, when no verifier fits my language?
rung: 1
section: prove
languages: any
kinds: general, money, parsing
cost: medium
detect: python3 -c "import z3"
ran_here: yes
verified: ran
---
## Use when
- The property is a bit-level or arithmetic fact (overflow tests, rounding, bit tricks, small state-transition rules) you can restate as formulas.
- No verifier covers your language, or you want a quick independent check of a formula.
## Do not use when
- You can verify the real code (`kani`, `cbmc`, `dafny`). Re-encoding invites mistakes.
- The claim has unbounded loops, heap structures or floating-point subtleties.
## Set up
In a throwaway virtualenv: `python3 -m venv .venv && .venv/bin/pip install z3-solver`. The package also provides the `z3` command-line program for SMT-LIB files.
## Minimal example
`z.py`. Claim: for 32-bit unsigned `a`, `b`, `(a + b) < a` holds exactly when the addition overflowed.
```python
from z3 import BitVec, Solver, ULT, UGE, ZeroExt, sat, unsat
a, b = BitVec("a", 32), BitVec("b", 32)
wrapped_smaller = ULT(a + b, a)
really_overflowed = UGE(ZeroExt(32, a) + ZeroExt(32, b), 2**32)
s = Solver()
s.add(wrapped_smaller != really_overflowed) # ask for a counterexample
r = s.check()
assert r == unsat, f"counterexample: {s.model()}" if r == sat else f"solver said {r}"
print("proved: overflow test is exact for all 32-bit a, b")
```
The same in SMT-LIB (`a.smt2`): declare `a`, `b` as `(_ BitVec 32)`, assert the negated claim, `(check-sat)`; expect `unsat`.
## Run
`python3 z.py` or `z3 a.smt2`
Passing looks like: `proved: ...` with exit 0; for SMT-LIB the single word `unsat`. Failure: `sat` (a model is a counterexample). Changing `>=` to `>` in `really_overflowed` gave the counterexample `a = 3489660928, b = 805306368` (their sum is exactly 2^32) and exit 1. The result `unknown` (timeout) is not a pass; the script asserts `unsat`.
## As a contract check
```json
{"id": "prove-overflow-test-z3", "claim": "(a + b) < a is equivalent to unsigned 32-bit overflow", "kind": "general", "rung": 1, "cmd": "python3 z.py", "expect": {"exit": 0, "stdout_contains": "proved"}, "tier": "deep", "timeout_s": 300}
```
## What a pass does not prove
- Only the formulas, not your code. A wrong translation proves something else; test the encoding against concrete values with `s.add(a == 3, ...)` expecting `sat`.
- You proved the negation is unsatisfiable. Check the formulas are not trivially unsat: assert that the model without the final constraint is `sat`.
- `z3-solver` versions differ in `unknown` behaviour; set `s.set("timeout", ms)` and treat `unknown` as failure.