agent-formal-verify 0.4.11 → 0.4.13

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.
Files changed (38) hide show
  1. package/CHANGES.md +140 -0
  2. package/README.md +5 -3
  3. package/package.json +2 -1
  4. package/skills/formal-verify/SKILL.md +11 -13
  5. package/skills/formal-verify/examples/kani-template/src/lib.rs +5 -6
  6. package/skills/formal-verify/examples/lean-template/Model/BoundedQueue.statements +10 -45
  7. package/skills/formal-verify/examples/tla-template/BoundedQueue.matrix +16 -13
  8. package/skills/formal-verify/examples/tla-template/BoundedQueue.mutations +92 -14
  9. package/skills/formal-verify/examples/tla-template/BoundedQueue.tla +169 -28
  10. package/skills/formal-verify/references/evidence.md +1 -1
  11. package/skills/formal-verify/references/helpers.md +5 -4
  12. package/skills/formal-verify/references/lean-brief.md +2 -2
  13. package/skills/formal-verify/references/rust-brief.md +59 -7
  14. package/skills/formal-verify/references/setup.md +24 -8
  15. package/skills/formal-verify/references/tla-brief.md +2 -2
  16. package/skills/formal-verify/scripts/baseline.py +564 -66
  17. package/skills/formal-verify/scripts/kani-check.sh +3 -1
  18. package/skills/formal-verify/scripts/kani.py +130 -54
  19. package/skills/formal-verify/scripts/lean-analysis.lean +387 -0
  20. package/skills/formal-verify/scripts/lean-check.sh +6 -243
  21. package/skills/formal-verify/scripts/lean.py +484 -0
  22. package/skills/formal-verify/scripts/lean_mutations.py +195 -0
  23. package/skills/formal-verify/scripts/lean_records.py +25 -0
  24. package/skills/formal-verify/scripts/mutate.py +81 -195
  25. package/skills/formal-verify/scripts/processes.py +266 -0
  26. package/skills/formal-verify/scripts/python-tools.sh +15 -0
  27. package/skills/formal-verify/scripts/runner.py +56 -0
  28. package/skills/formal-verify/scripts/setup.sh +18 -19
  29. package/skills/formal-verify/scripts/storage.py +207 -0
  30. package/skills/formal-verify/scripts/sync.py +401 -0
  31. package/skills/formal-verify/scripts/tlc-matrix.sh +3 -1
  32. package/skills/formal-verify/scripts/tlc.py +423 -116
  33. package/skills/formal-verify/scripts/{tlc-trace.py → tlc_trace.py} +16 -10
  34. package/skills/setup/SKILL.md +1 -1
  35. package/skills/formal-verify/scripts/lean-mutations.lean +0 -95
  36. package/skills/formal-verify/scripts/lean-statements.py +0 -161
  37. package/skills/formal-verify/scripts/lean-tools.sh +0 -24
  38. package/skills/formal-verify/scripts/tlc-tools.sh +0 -47
@@ -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
- command -v python3 > /dev/null || { echo "UNAVAILABLE python3 is required; install Python 3"; exit 3; }
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,16 +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 subprocess
16
+ import shutil
9
17
  import sys
10
18
  import tempfile
11
19
  from dataclasses import dataclass
12
20
  from enum import IntEnum
13
21
  from pathlib import Path
14
22
 
23
+ sys.dont_write_bytecode = True
24
+ import processes
25
+ import runner
26
+ import storage
27
+
15
28
  STATUSES = {"Success", "Failure", "Unreachable", "Undetermined", "Satisfied", "Unsatisfiable"}
16
29
  # Statuses that pass and statuses that refute the property, by check category; any other is inconclusive.
17
30
  OUTCOMES = {
@@ -25,10 +38,6 @@ class CheckError(Exception):
25
38
  pass
26
39
 
27
40
 
28
- class Unavailable(Exception):
29
- pass
30
-
31
-
32
41
  class Verdict(IntEnum):
33
42
  """A check's or harness's result, ordered so the worst check decides the harness."""
34
43
  PASS = 0
@@ -40,6 +49,14 @@ class Verdict(IntEnum):
40
49
  class Harness:
41
50
  unwind: int
42
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
43
60
 
44
61
 
45
62
  @dataclass(frozen=True)
@@ -57,21 +74,53 @@ def search_path(inherited, *directories):
57
74
  return os.pathsep.join(entries)
58
75
 
59
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
+
60
107
  class Kani:
61
108
  version = "0.68.0"
62
109
 
63
110
  def __init__(self):
64
111
  home = Path(os.environ.get("KANI_HOME", Path.home() / ".kani")).resolve()
65
- self.timeout = os.environ.get("KANI_HARNESS_TIMEOUT") or "5m"
112
+ self.timeout = os.environ.get("KANI_HARNESS_TIMEOUT", "").strip() or "5m"
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]
66
115
  bundle = home / f"kani-{self.version}"
67
116
  remedy = (f"run cargo install --locked kani-verifier --version {self.version} "
68
117
  "then cargo kani setup")
69
118
  for binary in ("bin/kani-driver", "bin/kani-compiler", "bin/cbmc", "toolchain/bin/rustc", "toolchain/bin/cargo"):
70
119
  path = bundle / binary
71
120
  if not path.is_file() or not os.access(path, os.X_OK):
72
- raise Unavailable(f"Kani {self.version} bundle is incomplete; {remedy}")
121
+ raise runner.Unavailable(f"UNAVAILABLE Kani {self.version} bundle is incomplete; {remedy}")
73
122
  if any(home.glob("*.tar.gz")):
74
- 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")
75
124
  self.bundle = bundle
76
125
  self.driver = bundle / "bin/kani-driver"
77
126
  self.cargo = bundle / "toolchain/bin/cargo"
@@ -91,26 +140,25 @@ class Kani:
91
140
  try:
92
141
  done = self.run("--version")
93
142
  except CheckError as error:
94
- 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
95
144
  if done.returncode or not done.stdout.startswith(f"Kani Rust Verifier {self.version} (cargo plugin)\n"):
96
- raise Unavailable(f"Kani {self.version} is required; {remedy}")
145
+ raise runner.Unavailable(f"UNAVAILABLE Kani {self.version} is required; {remedy}")
97
146
 
98
- 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)}
99
149
  try:
100
150
  # The driver selects Cargo mode from argv[0]; the Cargo wrapper can auto-install.
101
- return subprocess.run(
102
- ["cargo-kani", *arguments], executable=str(self.driver), env=self.env,
103
- 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)
104
152
  except OSError as error:
105
153
  raise CheckError(f"cannot execute Kani: {error}") from error
106
154
 
107
155
  def cargo_metadata(self, crate, resolve=False):
108
156
  """Read package declarations; resolve only when finding the full local source graph."""
109
157
  try:
110
- done = subprocess.run(
158
+ done = processes.run_captured(
111
159
  [str(self.cargo), "metadata", *([] if resolve else ["--no-deps"]), "--format-version", "1",
112
160
  "--manifest-path", str(crate / "Cargo.toml")],
113
- cwd=crate, env=self.env, capture_output=True, text=True, check=False)
161
+ cwd=crate, env=self.env)
114
162
  except OSError as error:
115
163
  raise CheckError(f"cannot read Cargo metadata: {error}") from error
116
164
  if done.returncode:
@@ -119,34 +167,42 @@ class Kani:
119
167
  report = json.loads(done.stdout)
120
168
  if report["version"] != 1:
121
169
  raise CheckError("unsupported Cargo metadata version")
122
- paths = [Path(report["workspace_root"])]
170
+ workspace = Path(report["workspace_root"])
171
+ target = Path(report["target_directory"])
172
+ packages = []
123
173
  for package in report["packages"]:
124
174
  if package["source"] is None:
125
- paths.append(Path(package["manifest_path"]).parent)
126
- paths.extend(Path(dep["path"]) for dep in package["dependencies"] if "path" in dep)
127
- if not all(path.is_absolute() for path in paths):
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)):
128
178
  raise CheckError("Cargo metadata returned a relative source path")
129
- return paths
179
+ return CargoMetadata(workspace, target, tuple(packages))
130
180
  except (ValueError, KeyError, TypeError) as error:
131
181
  raise CheckError(f"malformed Cargo metadata: {error}") from error
132
182
 
133
- def source_roots(self, crate):
183
+ def crate_sources(self, crate):
134
184
  """Find local workspaces, including transitive and optional path dependencies."""
135
- pending, visited, roots = {crate}, set(), set()
185
+ pending, visited = {crate}, set()
186
+ sources = CrateSources(set(), set())
136
187
  while pending:
137
188
  directory = pending.pop()
138
189
  if directory in visited:
139
190
  continue
140
191
  visited.add(directory)
141
- paths = self.cargo_metadata(directory, resolve=directory == crate)
142
- roots.update((paths[0].resolve(), directory))
143
- pending.update(path.resolve() for path in paths[1:])
144
- return roots
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
145
197
 
146
198
 
147
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)
148
204
  return kani.run("--manifest-path", str(crate / "Cargo.toml"),
149
- "--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)
150
206
 
151
207
 
152
208
  def read_json(path):
@@ -156,11 +212,14 @@ def read_json(path):
156
212
  raise CheckError(f"missing or invalid Kani report {path.name}: {error}") from error
157
213
 
158
214
 
159
- def discover(crate, work, kani):
160
- """Compile current harness metadata without `list`, which writes into the source directory."""
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
+ """
161
220
  if not (crate / "Cargo.toml").is_file():
162
221
  raise CheckError(f"{crate}/Cargo.toml is missing")
163
- workspace = kani.cargo_metadata(crate)[0]
222
+ workspace = kani.cargo_metadata(crate).workspace
164
223
  done = invoke(crate, work, kani, "--only-codegen")
165
224
  if done.returncode:
166
225
  output = done.stdout + done.stderr
@@ -174,37 +233,53 @@ def discover(crate, work, kani):
174
233
  "in production code or a dependency, report the Kani target as not checked; a feature "
175
234
  "attribute would change the production crate.")
176
235
  raise CheckError(f"Kani discovery failed:\n{output}")
177
- harnesses = {}
236
+ found = []
178
237
  try:
179
238
  for metadata in (work / "target").rglob("*.kani-metadata.json"):
180
239
  for harness in read_json(metadata)["proof_harnesses"]:
181
- if harness["attributes"]["kind"] != "Proof":
182
- continue
183
- name = harness["pretty_name"]
184
- bound = harness["attributes"].get("unwind_value")
185
- source = harness["original_file"]
186
- if not isinstance(name, str) or not name or not isinstance(source, str) or not source:
187
- raise CheckError("malformed Kani harness name or source")
188
- if name in harnesses:
189
- raise CheckError("duplicate harness names; select a single crate")
190
- if type(bound) is not int or bound < 1:
191
- raise CheckError(f"{name} needs #[kani::unwind(N)] with N greater than zero")
192
- 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))
193
244
  except (KeyError, TypeError, AttributeError) as error:
194
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)
195
261
  if not harnesses:
196
262
  raise CheckError("no proof harnesses found")
197
263
  return harnesses
198
264
 
199
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
+
200
275
  def harness_result(report, kani, name, returncode):
201
276
  """Return the one harness result in report after checking it agrees with itself and the process."""
202
277
  if report.get("metadata", {}).get("version") != "1.0" or report["metadata"].get("kani_version") != kani.version:
203
278
  raise CheckError("unsupported Kani result schema or version")
204
279
  if any(detail.get("harness_id") == name and detail.get("exit_status") == "timeout"
205
280
  for detail in report.get("error_details", [])):
206
- raise CheckError(f"the solver did not finish within KANI_HARNESS_TIMEOUT={kani.timeout}; "
207
- "narrow the harness or raise the limit")
281
+ raise CheckError(f"the solver did not finish within the {kani.limit} harness limit; "
282
+ "narrow the harness or set KANI_HARNESS_TIMEOUT to a longer limit")
208
283
  verification = report["verification_results"]
209
284
  summary, results = verification["summary"], verification["results"]
210
285
  if summary["status"] != "completed" or summary["executed"] != 1 or summary["total_harnesses"] != 1:
@@ -273,21 +348,20 @@ def verify(crate, work, kani, name, bound, *, cwd=None):
273
348
  def main():
274
349
  parser = argparse.ArgumentParser(description=__doc__)
275
350
  commands = parser.add_subparsers(dest="command", required=True)
276
- 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")
277
352
  check = commands.add_parser("check", help="verify the crate's proof harnesses")
278
353
  check.add_argument("crate")
279
354
  check.add_argument("harnesses", nargs="*")
280
355
  arguments = parser.parse_args()
281
- try:
282
- kani = Kani()
283
- except Unavailable as error:
284
- print(f"UNAVAILABLE {error}")
285
- return 3
356
+ kani = Kani()
286
357
  if arguments.command == "ready":
287
358
  print(f"READY Kani {kani.version}")
359
+ storage.report()
288
360
  return 0
289
361
  crate, selected = Path(arguments.crate).resolve(), arguments.harnesses
290
- with tempfile.TemporaryDirectory(prefix="formal-kani-") as temporary:
362
+ temp_root = storage.ensure_temp_root()
363
+ storage.warn_runtime()
364
+ with tempfile.TemporaryDirectory(prefix="formal-kani-", dir=temp_root) as temporary:
291
365
  work = Path(temporary)
292
366
  try:
293
367
  bounds = discover(crate, work, kani)
@@ -295,6 +369,7 @@ def main():
295
369
  unknown = set(names) - set(bounds)
296
370
  if unknown:
297
371
  raise CheckError("unknown harnesses: " + ", ".join(sorted(unknown)))
372
+ reject_should_panic(bounds, names)
298
373
  except CheckError as error:
299
374
  print(f"FAIL {error}")
300
375
  return 1
@@ -312,4 +387,5 @@ def main():
312
387
 
313
388
 
314
389
  if __name__ == "__main__":
315
- sys.exit(main())
390
+ # The readiness check runs Kani too, so the signal handling covers all of main.
391
+ runner.run(main)