agent-formal-verify 0.4.12 → 0.4.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGES.md +150 -0
- package/README.md +5 -3
- package/package.json +2 -1
- package/skills/formal-verify/SKILL.md +17 -19
- package/skills/formal-verify/examples/kani-template/src/lib.rs +5 -6
- package/skills/formal-verify/examples/lean-template/Model/BoundedQueue.statements +10 -45
- package/skills/formal-verify/examples/tla-template/BoundedQueue.matrix +16 -13
- package/skills/formal-verify/examples/tla-template/BoundedQueue.mutations +92 -14
- package/skills/formal-verify/examples/tla-template/BoundedQueue.tla +169 -28
- package/skills/formal-verify/references/evidence.md +1 -1
- package/skills/formal-verify/references/helpers.md +33 -3
- package/skills/formal-verify/references/lean-brief.md +2 -2
- package/skills/formal-verify/references/rust-brief.md +58 -6
- package/skills/formal-verify/references/setup.md +23 -7
- package/skills/formal-verify/references/tla-brief.md +3 -3
- package/skills/formal-verify/scripts/baseline.py +290 -261
- package/skills/formal-verify/scripts/kani-check.sh +3 -1
- package/skills/formal-verify/scripts/kani.py +127 -59
- package/skills/formal-verify/scripts/kani_reader.py +592 -0
- package/skills/formal-verify/scripts/lean-analysis.lean +387 -0
- package/skills/formal-verify/scripts/lean-check.sh +6 -243
- package/skills/formal-verify/scripts/lean.py +484 -0
- package/skills/formal-verify/scripts/lean_mutations.py +195 -0
- package/skills/formal-verify/scripts/lean_records.py +25 -0
- package/skills/formal-verify/scripts/mutate.py +81 -195
- package/skills/formal-verify/scripts/processes.py +266 -0
- package/skills/formal-verify/scripts/python-tools.sh +15 -0
- package/skills/formal-verify/scripts/runner.py +56 -0
- package/skills/formal-verify/scripts/rust_source.py +74 -0
- package/skills/formal-verify/scripts/setup.sh +18 -19
- package/skills/formal-verify/scripts/storage.py +207 -0
- package/skills/formal-verify/scripts/surface.py +27 -0
- package/skills/formal-verify/scripts/sync.py +401 -0
- package/skills/formal-verify/scripts/tlc-matrix.sh +3 -1
- package/skills/formal-verify/scripts/tlc.py +501 -117
- package/skills/formal-verify/scripts/tlc_report.py +516 -0
- package/skills/formal-verify/scripts/tlc_trace.py +167 -0
- package/skills/setup/SKILL.md +1 -1
- package/skills/formal-verify/scripts/lean-mutations.lean +0 -95
- package/skills/formal-verify/scripts/lean-statements.py +0 -161
- package/skills/formal-verify/scripts/lean-tools.sh +0 -24
- package/skills/formal-verify/scripts/tlc-tools.sh +0 -47
- package/skills/formal-verify/scripts/tlc-trace.py +0 -64
|
@@ -4,5 +4,7 @@
|
|
|
4
4
|
# Usage: kani-check.sh <crate-dir> [<fully-qualified-harness> ...]
|
|
5
5
|
set -euo pipefail
|
|
6
6
|
[ "$#" -ge 1 ] || { echo "usage: kani-check.sh <crate-dir> [<harness> ...]"; exit 2; }
|
|
7
|
-
|
|
7
|
+
# shellcheck source=skills/formal-verify/scripts/python-tools.sh
|
|
8
|
+
source "$(dirname "$0")/python-tools.sh"
|
|
9
|
+
require_python || exit 3
|
|
8
10
|
exec python3 "$(dirname "$0")/kani.py" check -- "$@"
|
|
@@ -2,17 +2,29 @@
|
|
|
2
2
|
# Copyright (c) 2026 Michael Denyer
|
|
3
3
|
# SPDX-License-Identifier: GPL-3.0-only
|
|
4
4
|
"""Run the pinned Kani and validate its versioned discovery and result records."""
|
|
5
|
+
import signal
|
|
6
|
+
|
|
7
|
+
if __name__ == "__main__":
|
|
8
|
+
# Python's SIGINT handler raises KeyboardInterrupt, which prints a traceback when it arrives during the imports.
|
|
9
|
+
# Until runner.run installs its own handlers, the default action ends the process by the signal instead.
|
|
10
|
+
if signal.getsignal(signal.SIGINT) is signal.default_int_handler:
|
|
11
|
+
signal.signal(signal.SIGINT, signal.SIG_DFL)
|
|
12
|
+
|
|
5
13
|
import argparse
|
|
6
14
|
import json
|
|
7
15
|
import os
|
|
8
|
-
import
|
|
9
|
-
import subprocess
|
|
16
|
+
import shutil
|
|
10
17
|
import sys
|
|
11
18
|
import tempfile
|
|
12
19
|
from dataclasses import dataclass
|
|
13
20
|
from enum import IntEnum
|
|
14
21
|
from pathlib import Path
|
|
15
22
|
|
|
23
|
+
sys.dont_write_bytecode = True
|
|
24
|
+
import processes
|
|
25
|
+
import runner
|
|
26
|
+
import storage
|
|
27
|
+
|
|
16
28
|
STATUSES = {"Success", "Failure", "Unreachable", "Undetermined", "Satisfied", "Unsatisfiable"}
|
|
17
29
|
# Statuses that pass and statuses that refute the property, by check category; any other is inconclusive.
|
|
18
30
|
OUTCOMES = {
|
|
@@ -26,10 +38,6 @@ class CheckError(Exception):
|
|
|
26
38
|
pass
|
|
27
39
|
|
|
28
40
|
|
|
29
|
-
class Unavailable(Exception):
|
|
30
|
-
pass
|
|
31
|
-
|
|
32
|
-
|
|
33
41
|
class Verdict(IntEnum):
|
|
34
42
|
"""A check's or harness's result, ordered so the worst check decides the harness."""
|
|
35
43
|
PASS = 0
|
|
@@ -41,6 +49,14 @@ class Verdict(IntEnum):
|
|
|
41
49
|
class Harness:
|
|
42
50
|
unwind: int
|
|
43
51
|
source: Path
|
|
52
|
+
should_panic: bool
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class Compiled:
|
|
57
|
+
name: str
|
|
58
|
+
source: Path
|
|
59
|
+
attributes: dict
|
|
44
60
|
|
|
45
61
|
|
|
46
62
|
@dataclass(frozen=True)
|
|
@@ -58,28 +74,53 @@ def search_path(inherited, *directories):
|
|
|
58
74
|
return os.pathsep.join(entries)
|
|
59
75
|
|
|
60
76
|
|
|
77
|
+
@dataclass(frozen=True)
|
|
78
|
+
class CargoMetadata:
|
|
79
|
+
workspace: Path
|
|
80
|
+
target: Path
|
|
81
|
+
packages: tuple
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass
|
|
85
|
+
class CrateSources:
|
|
86
|
+
roots: set
|
|
87
|
+
outputs: set
|
|
88
|
+
|
|
89
|
+
def stage(self, crate, destination):
|
|
90
|
+
"""Copy local packages in their relative layout, omitting Cargo's build directories."""
|
|
91
|
+
anchor = Path(os.path.commonpath(self.roots))
|
|
92
|
+
|
|
93
|
+
def ignore(directory, names):
|
|
94
|
+
# Cargo tags each build directory, including one left behind after the target directory moved.
|
|
95
|
+
# A dangling symlink, such as an editor's lock file, is skipped here because copytree's
|
|
96
|
+
# ignore_dangling_symlinks reaches only the top directory before Python 3.10.
|
|
97
|
+
return [name for name in names if name == ".git" or Path(directory) / name in self.outputs
|
|
98
|
+
or (Path(directory) / name / "CACHEDIR.TAG").is_file()
|
|
99
|
+
or (Path(directory) / name).is_symlink() and not (Path(directory) / name).exists()]
|
|
100
|
+
|
|
101
|
+
for root in self.roots:
|
|
102
|
+
if self.roots.isdisjoint(root.parents):
|
|
103
|
+
shutil.copytree(root, destination / root.relative_to(anchor), ignore=ignore)
|
|
104
|
+
return destination / crate.relative_to(anchor)
|
|
105
|
+
|
|
106
|
+
|
|
61
107
|
class Kani:
|
|
62
108
|
version = "0.68.0"
|
|
63
109
|
|
|
64
110
|
def __init__(self):
|
|
65
111
|
home = Path(os.environ.get("KANI_HOME", Path.home() / ".kani")).resolve()
|
|
66
112
|
self.timeout = os.environ.get("KANI_HARNESS_TIMEOUT", "").strip() or "5m"
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
raise Unavailable(f"KANI_HARNESS_TIMEOUT={self.timeout!r} is not a harness time limit; set a whole "
|
|
70
|
-
"number from 1 to 4294967295 with an optional unit s, m or h, such as 90s or 20m, "
|
|
71
|
-
"or unset it for five minutes")
|
|
72
|
-
# Kani reads a number with no unit as seconds; name the unit when reporting the limit.
|
|
73
|
-
self.limit = limit[1] + (limit[2] or "s")
|
|
113
|
+
# Kani reads a number with no unit as seconds; the label names the unit when reporting the limit.
|
|
114
|
+
self.limit = runner.parse_limit("KANI_HARNESS_TIMEOUT", self.timeout, "harness time limit", "five minutes")[0]
|
|
74
115
|
bundle = home / f"kani-{self.version}"
|
|
75
116
|
remedy = (f"run cargo install --locked kani-verifier --version {self.version} "
|
|
76
117
|
"then cargo kani setup")
|
|
77
118
|
for binary in ("bin/kani-driver", "bin/kani-compiler", "bin/cbmc", "toolchain/bin/rustc", "toolchain/bin/cargo"):
|
|
78
119
|
path = bundle / binary
|
|
79
120
|
if not path.is_file() or not os.access(path, os.X_OK):
|
|
80
|
-
raise Unavailable(f"Kani {self.version} bundle is incomplete; {remedy}")
|
|
121
|
+
raise runner.Unavailable(f"UNAVAILABLE Kani {self.version} bundle is incomplete; {remedy}")
|
|
81
122
|
if any(home.glob("*.tar.gz")):
|
|
82
|
-
raise Unavailable(f"incomplete Kani setup at {home}; finish cargo kani setup before checking")
|
|
123
|
+
raise runner.Unavailable(f"UNAVAILABLE incomplete Kani setup at {home}; finish cargo kani setup before checking")
|
|
83
124
|
self.bundle = bundle
|
|
84
125
|
self.driver = bundle / "bin/kani-driver"
|
|
85
126
|
self.cargo = bundle / "toolchain/bin/cargo"
|
|
@@ -99,26 +140,25 @@ class Kani:
|
|
|
99
140
|
try:
|
|
100
141
|
done = self.run("--version")
|
|
101
142
|
except CheckError as error:
|
|
102
|
-
raise Unavailable(f"Kani {self.version} cannot run: {error}; {remedy}") from error
|
|
143
|
+
raise runner.Unavailable(f"UNAVAILABLE Kani {self.version} cannot run: {error}; {remedy}") from error
|
|
103
144
|
if done.returncode or not done.stdout.startswith(f"Kani Rust Verifier {self.version} (cargo plugin)\n"):
|
|
104
|
-
raise Unavailable(f"Kani {self.version} is required; {remedy}")
|
|
145
|
+
raise runner.Unavailable(f"UNAVAILABLE Kani {self.version} is required; {remedy}")
|
|
105
146
|
|
|
106
|
-
def run(self, *arguments, cwd=None):
|
|
147
|
+
def run(self, *arguments, cwd=None, tmpdir=None):
|
|
148
|
+
env = self.env if tmpdir is None else self.env | {"TMPDIR": str(tmpdir)}
|
|
107
149
|
try:
|
|
108
150
|
# The driver selects Cargo mode from argv[0]; the Cargo wrapper can auto-install.
|
|
109
|
-
return
|
|
110
|
-
["cargo-kani", *arguments], executable=str(self.driver), env=self.env,
|
|
111
|
-
cwd=cwd, capture_output=True, text=True, check=False)
|
|
151
|
+
return processes.run_captured(["cargo-kani", *arguments], executable=str(self.driver), env=env, cwd=cwd)
|
|
112
152
|
except OSError as error:
|
|
113
153
|
raise CheckError(f"cannot execute Kani: {error}") from error
|
|
114
154
|
|
|
115
155
|
def cargo_metadata(self, crate, resolve=False):
|
|
116
156
|
"""Read package declarations; resolve only when finding the full local source graph."""
|
|
117
157
|
try:
|
|
118
|
-
done =
|
|
158
|
+
done = processes.run_captured(
|
|
119
159
|
[str(self.cargo), "metadata", *([] if resolve else ["--no-deps"]), "--format-version", "1",
|
|
120
160
|
"--manifest-path", str(crate / "Cargo.toml")],
|
|
121
|
-
cwd=crate, env=self.env
|
|
161
|
+
cwd=crate, env=self.env)
|
|
122
162
|
except OSError as error:
|
|
123
163
|
raise CheckError(f"cannot read Cargo metadata: {error}") from error
|
|
124
164
|
if done.returncode:
|
|
@@ -127,34 +167,42 @@ class Kani:
|
|
|
127
167
|
report = json.loads(done.stdout)
|
|
128
168
|
if report["version"] != 1:
|
|
129
169
|
raise CheckError("unsupported Cargo metadata version")
|
|
130
|
-
|
|
170
|
+
workspace = Path(report["workspace_root"])
|
|
171
|
+
target = Path(report["target_directory"])
|
|
172
|
+
packages = []
|
|
131
173
|
for package in report["packages"]:
|
|
132
174
|
if package["source"] is None:
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
if not all(path.is_absolute() for path in
|
|
175
|
+
packages.append(Path(package["manifest_path"]).parent)
|
|
176
|
+
packages.extend(Path(dep["path"]) for dep in package["dependencies"] if "path" in dep)
|
|
177
|
+
if not all(path.is_absolute() for path in (workspace, target, *packages)):
|
|
136
178
|
raise CheckError("Cargo metadata returned a relative source path")
|
|
137
|
-
return
|
|
179
|
+
return CargoMetadata(workspace, target, tuple(packages))
|
|
138
180
|
except (ValueError, KeyError, TypeError) as error:
|
|
139
181
|
raise CheckError(f"malformed Cargo metadata: {error}") from error
|
|
140
182
|
|
|
141
|
-
def
|
|
183
|
+
def crate_sources(self, crate):
|
|
142
184
|
"""Find local workspaces, including transitive and optional path dependencies."""
|
|
143
|
-
pending, visited
|
|
185
|
+
pending, visited = {crate}, set()
|
|
186
|
+
sources = CrateSources(set(), set())
|
|
144
187
|
while pending:
|
|
145
188
|
directory = pending.pop()
|
|
146
189
|
if directory in visited:
|
|
147
190
|
continue
|
|
148
191
|
visited.add(directory)
|
|
149
|
-
|
|
150
|
-
roots.update((
|
|
151
|
-
|
|
152
|
-
|
|
192
|
+
metadata = self.cargo_metadata(directory, resolve=directory == crate)
|
|
193
|
+
sources.roots.update((metadata.workspace.resolve(), directory))
|
|
194
|
+
sources.outputs.add(metadata.target.parent.resolve() / metadata.target.name)
|
|
195
|
+
pending.update(path.resolve() for path in metadata.packages)
|
|
196
|
+
return sources
|
|
153
197
|
|
|
154
198
|
|
|
155
199
|
def invoke(crate, work, kani, *arguments, cwd=None):
|
|
200
|
+
# Kani's tools, such as goto-cc, write their own temporary files to TMPDIR. Keep those in the
|
|
201
|
+
# work directory, which the runner removes even when it stops a tool partway.
|
|
202
|
+
tmpdir = work / "tmp"
|
|
203
|
+
tmpdir.mkdir(parents=True, exist_ok=True)
|
|
156
204
|
return kani.run("--manifest-path", str(crate / "Cargo.toml"),
|
|
157
|
-
"--target-dir", str(work / "target"), "-Z", "stubbing", *arguments, cwd=cwd or crate)
|
|
205
|
+
"--target-dir", str(work / "target"), "-Z", "stubbing", *arguments, cwd=cwd or crate, tmpdir=tmpdir)
|
|
158
206
|
|
|
159
207
|
|
|
160
208
|
def read_json(path):
|
|
@@ -164,11 +212,14 @@ def read_json(path):
|
|
|
164
212
|
raise CheckError(f"missing or invalid Kani report {path.name}: {error}") from error
|
|
165
213
|
|
|
166
214
|
|
|
167
|
-
def
|
|
168
|
-
"""
|
|
215
|
+
def compiled(crate, work, kani):
|
|
216
|
+
"""Return each proof harness that Kani compiles in crate's targets, one per target that compiles it.
|
|
217
|
+
|
|
218
|
+
It compiles harness metadata without `list`, which writes into the source directory.
|
|
219
|
+
"""
|
|
169
220
|
if not (crate / "Cargo.toml").is_file():
|
|
170
221
|
raise CheckError(f"{crate}/Cargo.toml is missing")
|
|
171
|
-
workspace = kani.cargo_metadata(crate)
|
|
222
|
+
workspace = kani.cargo_metadata(crate).workspace
|
|
172
223
|
done = invoke(crate, work, kani, "--only-codegen")
|
|
173
224
|
if done.returncode:
|
|
174
225
|
output = done.stdout + done.stderr
|
|
@@ -182,29 +233,45 @@ def discover(crate, work, kani):
|
|
|
182
233
|
"in production code or a dependency, report the Kani target as not checked; a feature "
|
|
183
234
|
"attribute would change the production crate.")
|
|
184
235
|
raise CheckError(f"Kani discovery failed:\n{output}")
|
|
185
|
-
|
|
236
|
+
found = []
|
|
186
237
|
try:
|
|
187
238
|
for metadata in (work / "target").rglob("*.kani-metadata.json"):
|
|
188
239
|
for harness in read_json(metadata)["proof_harnesses"]:
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
source = harness["original_file"]
|
|
194
|
-
if not isinstance(name, str) or not name or not isinstance(source, str) or not source:
|
|
195
|
-
raise CheckError("malformed Kani harness name or source")
|
|
196
|
-
if name in harnesses:
|
|
197
|
-
raise CheckError("duplicate harness names; select a single crate")
|
|
198
|
-
if type(bound) is not int or bound < 1:
|
|
199
|
-
raise CheckError(f"{name} needs #[kani::unwind(N)] with N greater than zero")
|
|
200
|
-
harnesses[name] = Harness(bound, (workspace / source).resolve())
|
|
240
|
+
name, source, attributes = harness["pretty_name"], harness["original_file"], harness["attributes"]
|
|
241
|
+
if not isinstance(name, str) or not name or not isinstance(source, str) or not source or not isinstance(attributes, dict) or "kind" not in attributes:
|
|
242
|
+
raise CheckError("malformed Kani harness name, source or attributes")
|
|
243
|
+
found.append(Compiled(name, (workspace / source).resolve(), attributes))
|
|
201
244
|
except (KeyError, TypeError, AttributeError) as error:
|
|
202
245
|
raise CheckError(f"malformed Kani discovery record: {error!r}") from error
|
|
246
|
+
return found
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def discover(crate, work, kani):
|
|
250
|
+
"""Return the checker's harnesses in crate by name: each `#[kani::proof]` with its unwind bound and source."""
|
|
251
|
+
harnesses = {}
|
|
252
|
+
for harness in compiled(crate, work, kani):
|
|
253
|
+
if harness.attributes.get("kind") != "Proof":
|
|
254
|
+
continue
|
|
255
|
+
bound = harness.attributes.get("unwind_value")
|
|
256
|
+
if harness.name in harnesses:
|
|
257
|
+
raise CheckError("duplicate harness names; select a single crate")
|
|
258
|
+
if type(bound) is not int or bound < 1:
|
|
259
|
+
raise CheckError(f"{harness.name} needs #[kani::unwind(N)] with N greater than zero")
|
|
260
|
+
harnesses[harness.name] = Harness(bound, harness.source, harness.attributes.get("should_panic") is True)
|
|
203
261
|
if not harnesses:
|
|
204
262
|
raise CheckError("no proof harnesses found")
|
|
205
263
|
return harnesses
|
|
206
264
|
|
|
207
265
|
|
|
266
|
+
def reject_should_panic(harnesses, names):
|
|
267
|
+
"""Raise CheckError for the first named harness that Kani verifies with an expected panic."""
|
|
268
|
+
for name in names:
|
|
269
|
+
# Kani reports the expected panic as a failed check, which would read as a refuted property.
|
|
270
|
+
if harnesses[name].should_panic:
|
|
271
|
+
raise CheckError(f"{name} is marked #[kani::should_panic], which the Rust checker does not "
|
|
272
|
+
"support; remove the attribute and assert the condition that leads to the panic")
|
|
273
|
+
|
|
274
|
+
|
|
208
275
|
def harness_result(report, kani, name, returncode):
|
|
209
276
|
"""Return the one harness result in report after checking it agrees with itself and the process."""
|
|
210
277
|
if report.get("metadata", {}).get("version") != "1.0" or report["metadata"].get("kani_version") != kani.version:
|
|
@@ -281,21 +348,20 @@ def verify(crate, work, kani, name, bound, *, cwd=None):
|
|
|
281
348
|
def main():
|
|
282
349
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
283
350
|
commands = parser.add_subparsers(dest="command", required=True)
|
|
284
|
-
commands.add_parser("ready", help="check that the pinned Kani bundle runs")
|
|
351
|
+
commands.add_parser("ready", help="check that the pinned Kani bundle runs, then report the temporary directory's free space")
|
|
285
352
|
check = commands.add_parser("check", help="verify the crate's proof harnesses")
|
|
286
353
|
check.add_argument("crate")
|
|
287
354
|
check.add_argument("harnesses", nargs="*")
|
|
288
355
|
arguments = parser.parse_args()
|
|
289
|
-
|
|
290
|
-
kani = Kani()
|
|
291
|
-
except Unavailable as error:
|
|
292
|
-
print(f"UNAVAILABLE {error}")
|
|
293
|
-
return 3
|
|
356
|
+
kani = Kani()
|
|
294
357
|
if arguments.command == "ready":
|
|
295
358
|
print(f"READY Kani {kani.version}")
|
|
359
|
+
storage.report()
|
|
296
360
|
return 0
|
|
297
361
|
crate, selected = Path(arguments.crate).resolve(), arguments.harnesses
|
|
298
|
-
|
|
362
|
+
temp_root = storage.ensure_temp_root()
|
|
363
|
+
storage.warn_runtime()
|
|
364
|
+
with tempfile.TemporaryDirectory(prefix="formal-kani-", dir=temp_root) as temporary:
|
|
299
365
|
work = Path(temporary)
|
|
300
366
|
try:
|
|
301
367
|
bounds = discover(crate, work, kani)
|
|
@@ -303,6 +369,7 @@ def main():
|
|
|
303
369
|
unknown = set(names) - set(bounds)
|
|
304
370
|
if unknown:
|
|
305
371
|
raise CheckError("unknown harnesses: " + ", ".join(sorted(unknown)))
|
|
372
|
+
reject_should_panic(bounds, names)
|
|
306
373
|
except CheckError as error:
|
|
307
374
|
print(f"FAIL {error}")
|
|
308
375
|
return 1
|
|
@@ -320,4 +387,5 @@ def main():
|
|
|
320
387
|
|
|
321
388
|
|
|
322
389
|
if __name__ == "__main__":
|
|
323
|
-
|
|
390
|
+
# The readiness check runs Kani too, so the signal handling covers all of main.
|
|
391
|
+
runner.run(main)
|