agent-formal-verify 0.4.12 → 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 +136 -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 +4 -3
  12. package/skills/formal-verify/references/lean-brief.md +2 -2
  13. package/skills/formal-verify/references/rust-brief.md +58 -6
  14. package/skills/formal-verify/references/setup.md +23 -7
  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 +127 -59
  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
@@ -10,7 +10,7 @@ whose value differs from the previous state. The first state prints every
10
10
  variable. A "Back to state" line (a liveness lasso) is printed as is.
11
11
  Exits 1 when the log holds no trace.
12
12
 
13
- Usage: tlc-trace.py [tlc.log]
13
+ Usage: tlc_trace.py [tlc.log]
14
14
  """
15
15
  import re
16
16
  import sys
@@ -47,17 +47,23 @@ def states(lines):
47
47
  yield title, values
48
48
 
49
49
 
50
+ def reduce(lines):
51
+ """Return the printed lines of the first error trace, or None when the log holds no trace."""
52
+ out, prev, found = [], {}, False
53
+ for title, values in states(lines):
54
+ found = True
55
+ out.append(f"--- {title}")
56
+ out += [f" {var} = {value}" for var, value in values.items() if prev.get(var) != value]
57
+ prev = values or prev
58
+ return "\n".join(out).split("\n") if found else None
59
+
60
+
50
61
  def main():
51
62
  with (open(sys.argv[1], encoding="utf-8") if len(sys.argv) > 1 else nullcontext(sys.stdin)) as src:
52
- prev, found = {}, False
53
- for title, values in states(src):
54
- found = True
55
- print(f"--- {title}")
56
- for var, value in values.items():
57
- if prev.get(var) != value:
58
- print(f" {var} = {value}")
59
- prev = values or prev
60
- sys.exit(0 if found else 1)
63
+ reduced = reduce(src)
64
+ if reduced is None:
65
+ sys.exit(1)
66
+ print("\n".join(reduced))
61
67
 
62
68
 
63
69
  if __name__ == "__main__":
@@ -8,7 +8,7 @@ description: "Prepare all shared tools for the agent-formal-verify plugin: Java,
8
8
  Prepare the complete shared toolset once, independently of any repository. Verification selects TLA+, Lean and Kani from each repository's current targets. A global plugin installation uses the same tools across repositories.
9
9
 
10
10
  1. Read [tool setup](../formal-verify/references/setup.md) for pinned versions and environment settings. Inspect the operating system and existing runtimes. Reuse installed prerequisites and tool caches.
11
- 2. Ensure a working JDK, Python 3, a SHA256 tool, elan, Rust, the pinned Kani and the pinned TLC JAR are available. Install missing prerequisites through the user's existing package manager or the upstream documented installer, following their installation constraints. Obtain `tla2tools.jar` from the TLA+ release that `scripts/tlc-tools.sh` pins and save it at the path the helper names; the helper verifies its SHA256 and downloads nothing itself. If no suitable installation method is available, or the user has not allowed installation, report the missing prerequisites and their installation instructions.
11
+ 2. Ensure a working JDK, Python 3.9 or later, elan, Rust, the pinned Kani and the pinned TLC JAR are available. Install missing prerequisites through the user's existing package manager or the upstream documented installer, following their installation constraints. Obtain `tla2tools.jar` from the TLA+ release that `scripts/tlc.py` pins and save it at the path the helper names; the helper verifies its SHA256 and downloads nothing itself. If no suitable installation method is available, or the user has not allowed installation, report the missing prerequisites and their installation instructions.
12
12
 
13
13
  Install the Kani version from tool setup with Cargo, then run `cargo kani setup`. The plugin's helpers verify it without installing or downloading it.
14
14
 
@@ -1,95 +0,0 @@
1
- -- Copyright (c) 2026 Michael Denyer
2
- -- SPDX-License-Identifier: GPL-3.0-only
3
- -- Elaborate one source and report declaration identities, ranges and errors.
4
- -- Run through the target project's pinned Lake environment, without building it.
5
- import Lean
6
-
7
- open Lean Elab Command
8
-
9
- private def point (p : Position) : Json := toJson (p.line, p.column)
10
-
11
- -- Older Lean numbers anonymous binders by a file-wide hygiene counter, so an
12
- -- edit to an earlier command renames them without changing the statement.
13
- private partial def unnamed (e : Expr) : Expr := e.replace fun
14
- | .forallE _ t b bi => some (.forallE .anonymous (unnamed t) (unnamed b) bi)
15
- | .lam _ t b bi => some (.lam .anonymous (unnamed t) (unnamed b) bi)
16
- | _ => none
17
-
18
- -- An example's statement is the type of the local Lean binds for its header, and
19
- -- a guard's is its term. Closing over the local context removes the ids of
20
- -- section variables, which shift when an earlier command changes.
21
- private def statement (trees : PersistentArray InfoTree) (check : Syntax) : IO Json := do
22
- let isExample := check.isOfKind ``Parser.Command.example
23
- let target := if isExample then check else check[1]
24
- let wanted (ti : TermInfo) := ti.stx.getPos? == target.getPos? &&
25
- (if isExample then ti.stx.isOfKind ``Parser.Command.declId && ti.expr.isFVar
26
- else ti.stx.getTailPos? == target.getTailPos?)
27
- let found := trees.foldl (init := none) fun found tree => found <|> tree.foldInfo (init := none)
28
- fun ctx info found => found <|> match info with
29
- | .ofTermInfo ti => if wanted ti then some (ctx, ti) else none
30
- | _ => none
31
- let some (ctx, ti) := found | return Json.null
32
- ctx.runMetaM ti.lctx do
33
- let e ← instantiateMVars (← if isExample then Meta.inferType ti.expr else pure ti.expr)
34
- let xs := ti.lctx.foldl (init := #[]) fun xs decl =>
35
- if decl.isImplementationDetail then xs else xs.push decl.toExpr
36
- let e ← Meta.mkLambdaFVars xs e
37
- return if e.hasFVar || e.hasMVar then Json.null else toJson (reprStr (unnamed e))
38
-
39
- private def declarations (instances : Array (Nat × Nat)) : CommandElabM (Array Json) := do
40
- let env ← getEnv
41
- let fileMap ← getFileMap
42
- let names := env.constants.fold (fun acc name _ =>
43
- if env.isImportedConst name then acc else acc.push name) #[]
44
- let mut result := #[]
45
- for name in names do
46
- let some ranges ← findDeclarationRanges? name | continue
47
- let pos := (fileMap.ofPosition ranges.selectionRange.pos).byteIdx
48
- -- Local and scoped instances may no longer be registered in the final environment.
49
- let instanceDecl := Meta.isInstanceCore env name || instances.any fun (start, tail) =>
50
- start ≤ pos && pos < tail
51
- let info := (env.find? name).get!
52
- result := result.push <| Json.mkObj [
53
- ("name", toJson ((privateToUserName? name).getD name).toString),
54
- ("private", toJson (privateToUserName? name).isSome),
55
- ("theorem", toJson (info.isTheorem && !env.isProjectionFn name && !instanceDecl)),
56
- ("type", toJson (reprStr (info.levelParams, unnamed info.type))),
57
- ("start", point ranges.range.pos), ("end", point ranges.range.endPos)]
58
- return result
59
-
60
- unsafe def main (args : List String) : IO UInt32 := do
61
- let [path] := args | throw <| IO.userError "usage: lean-mutations.lean <source.lean>"
62
- enableInitializersExecution
63
- initSearchPath (← findSysroot)
64
- let inputCtx := Parser.mkInputContext (← IO.FS.readFile path) path
65
- let (header, parserState, messages) ← Parser.parseHeader inputCtx
66
- let (env, messages) ← processHeader header {} messages inputCtx
67
- let state ← IO.processCommands inputCtx parserState (Command.mkState env messages {})
68
- let mut commands := #[]
69
- let mut instances := #[]
70
- for stx in state.commands do
71
- if let some instanceStx := stx.find? (·.isOfKind ``Parser.Command.instance) then
72
- if let (some start, some tail) := (instanceStx.getPos?, instanceStx.getTailPos?) then
73
- instances := instances.push (start.byteIdx, tail.byteIdx)
74
- let some start := stx.getPos? | continue
75
- let some tail := stx.getTailPos? | continue
76
- let propertyStx := stx.find? fun cmd =>
77
- cmd.isOfKind ``Parser.Command.guardCmd || cmd.isOfKind ``Parser.Command.example
78
- let property := match propertyStx with
79
- | some cmd => if cmd.isOfKind ``Parser.Command.guardCmd then "#guard" else "example"
80
- | none => ""
81
- let propertyStart := (propertyStx.bind Syntax.getPos?).getD start
82
- let propertyEnd := (propertyStx.bind Syntax.getTailPos?).getD tail
83
- commands := commands.push <| Json.mkObj [
84
- ("property", toJson property),
85
- ("statement", toJson (← propertyStx.mapM (statement state.commandState.infoState.trees))),
86
- ("start", point (inputCtx.fileMap.toPosition propertyStart)),
87
- ("end", point (inputCtx.fileMap.toPosition propertyEnd))]
88
- let (decls, _) ← (Frontend.runCommandElabM (declarations instances)).run { inputCtx } |>.run state
89
- let mut errors := #[]
90
- for msg in state.commandState.messages.toList do
91
- if msg.severity == .error then errors := errors.push (← msg.toJson)
92
- IO.println <| "AFV_LEAN " ++ (Json.mkObj [
93
- ("declarations", toJson decls), ("commands", toJson commands),
94
- ("errors", toJson errors)]).compress
95
- return 0
@@ -1,161 +0,0 @@
1
- #!/usr/bin/env python3
2
- # Copyright (c) 2026 Michael Denyer
3
- # SPDX-License-Identifier: GPL-3.0-only
4
- """Store or check declaration fingerprints emitted by the Lean audit."""
5
-
6
- import argparse
7
- import hashlib
8
- import json
9
- import sys
10
- import tempfile
11
- from pathlib import Path
12
-
13
-
14
- def fingerprint(expression):
15
- return hashlib.sha256(expression.encode("utf-8")).hexdigest()
16
-
17
-
18
- def declarations(audit):
19
- modules = {}
20
- for line in audit.read_text(encoding="utf-8").splitlines():
21
- if not line.startswith("STATEMENT "):
22
- continue
23
- raw = json.loads(line.removeprefix("STATEMENT "))
24
- record = {key: raw[key] for key in ("name", "kind", "type")}
25
- record["type"] = " ".join(record["type"].split())
26
- record["typeHash"] = fingerprint(raw["typeExpr"])
27
- record["valueHash"] = None if raw["valueExpr"] is None else fingerprint(raw["valueExpr"])
28
- modules.setdefault(raw["module"], []).append(record)
29
- return modules
30
-
31
-
32
- def records_by_name(modules, module):
33
- """Return the module's audited records by name, refusing two declarations with one name."""
34
- records = {}
35
- for record in modules.get(module, []):
36
- if record["name"] in records:
37
- raise ValueError(f"ambiguous declaration identity {record['name']} in {module}")
38
- records[record["name"]] = record
39
- return records
40
-
41
-
42
- def read_record(path):
43
- record = json.loads(path.read_text(encoding="utf-8"))
44
- if not isinstance(record, dict) or record.get("format") != 1:
45
- raise ValueError(f"{path}: unsupported statements format")
46
- if not isinstance(record.get("toolchain"), str) or not isinstance(record.get("module"), str):
47
- raise TypeError(f"{path}: missing toolchain or module")
48
- entries = record.get("declarations")
49
- if not isinstance(entries, list) or not entries:
50
- raise ValueError(f"{path}: missing declarations")
51
- seen = set()
52
- for entry in entries:
53
- if not isinstance(entry, dict) or not all(isinstance(entry.get(key), str) for key in ("name", "kind", "type", "typeHash")):
54
- raise ValueError(f"{path}: malformed declaration")
55
- if "valueHash" not in entry or entry["valueHash"] is not None and not isinstance(entry["valueHash"], str):
56
- raise ValueError(f"{path}: malformed value hash")
57
- if entry["name"] in seen:
58
- raise ValueError(f"{path}: duplicate declaration {entry['name']}")
59
- seen.add(entry["name"])
60
- return record
61
-
62
-
63
- def check_orphans(project):
64
- failed = False
65
- for path in sorted(project.rglob("*.statements")):
66
- if ".lake" in path.relative_to(project).parts or path.with_suffix(".lean").is_file():
67
- continue
68
- record = read_record(path)
69
- print(f"FROZEN {path}: source file is missing")
70
- for declaration in record["declarations"]:
71
- print(f"FROZEN {declaration['name']}: statement changed (source deleted)")
72
- failed = True
73
- return int(failed)
74
-
75
-
76
- def freeze(toolchain, modules, sources):
77
- """Record every source's statements, writing none unless all of them can be recorded."""
78
- pending = []
79
- for module, source in sources:
80
- records = records_by_name(modules, module)
81
- if not records:
82
- raise ValueError(f"no declaration records for {source}")
83
- record = {"format": 1, "toolchain": toolchain, "module": module,
84
- "declarations": [records[name] for name in sorted(records)]}
85
- pending.append((source.with_suffix(".statements"), json.dumps(record, ensure_ascii=False, indent=2) + "\n"))
86
- for path, contents in pending:
87
- temporary = None
88
- try:
89
- with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent, delete=False) as stream:
90
- temporary = Path(stream.name)
91
- stream.write(contents)
92
- temporary.replace(path)
93
- finally:
94
- if temporary is not None:
95
- temporary.unlink(missing_ok=True)
96
- print(f"FROZEN {path}: statements recorded; proofs not checked")
97
- return 0
98
-
99
-
100
- def check(toolchain, modules, sources):
101
- """Compare every recorded source's statements with the audit; a source without a record passes."""
102
- failed = False
103
- for module, source in sources:
104
- path = source.with_suffix(".statements")
105
- if not path.exists():
106
- continue
107
- records = records_by_name(modules, module)
108
- frozen = read_record(path)
109
- if frozen["toolchain"] != toolchain:
110
- print(f"FROZEN {path}: toolchain changed from {frozen['toolchain']} to {toolchain}; review and run --freeze")
111
- failed = True
112
- continue
113
- if frozen["module"] != module:
114
- raise ValueError(f"{path}: expected module {module}, found {frozen['module']}")
115
- changed = 0
116
- for old in frozen["declarations"]:
117
- if old["kind"] == "opaque" and old["valueHash"] is None:
118
- print(f"FROZEN {old['name']}: opaque body was not recorded; review the definition and run --freeze")
119
- failed = True
120
- continue
121
- new = records.get(old["name"])
122
- if new is not None and all(old[key] == new[key] for key in ("kind", "typeHash", "valueHash")):
123
- continue
124
- changed += 1
125
- print(f"FROZEN {old['name']}: statement changed")
126
- print(f" old: {old['type']}")
127
- print(f" new: {new['type'] if new else '(deleted)'}")
128
- if new and old["valueHash"] != new["valueHash"]:
129
- print(" definition value changed")
130
- if changed == len(frozen["declarations"]):
131
- print(f"FROZEN {path}: every recorded declaration changed; review the model and toolchain before --freeze")
132
- failed |= changed > 0
133
- return int(failed)
134
-
135
-
136
- def main():
137
- parser = argparse.ArgumentParser(description=__doc__)
138
- commands = parser.add_subparsers(dest="command", required=True)
139
- commands.add_parser("orphans", help="report records whose source file is gone").add_argument("project", type=Path)
140
- for name, purpose in (("freeze", "record each source's statements"), ("check", "compare each recorded source's statements")):
141
- command = commands.add_parser(name, help=purpose)
142
- command.add_argument("toolchain")
143
- command.add_argument("audit", type=Path, help="the audit's output, with its STATEMENT lines")
144
- command.add_argument("module_names", type=Path, help="the module of each source, one per line in source order")
145
- command.add_argument("sources", nargs="+", type=Path)
146
- arguments = parser.parse_args()
147
- if arguments.command == "orphans":
148
- return check_orphans(arguments.project)
149
- names = arguments.module_names.read_text(encoding="utf-8").splitlines()
150
- if len(names) != len(arguments.sources):
151
- raise ValueError("Lake did not return one module per source")
152
- action = freeze if arguments.command == "freeze" else check
153
- return action(arguments.toolchain, declarations(arguments.audit), zip(names, arguments.sources))
154
-
155
-
156
- if __name__ == "__main__":
157
- try:
158
- sys.exit(main())
159
- except (OSError, ValueError, KeyError, TypeError) as error:
160
- print(f"FAIL statements: {error}")
161
- sys.exit(1)
@@ -1,24 +0,0 @@
1
- #!/bin/bash
2
- # Copyright (c) 2026 Michael Denyer
3
- # SPDX-License-Identifier: GPL-3.0-only
4
- # Shared Lean pin lookup; sourcing this file installs nothing.
5
-
6
- # Prints the toolchain pin of the Lake project in $1.
7
- lean_pin() {
8
- [ -f "$1/lean-toolchain" ] || { echo "FAIL $1 has no lean-toolchain pin"; return 1; }
9
- command -v elan > /dev/null || { echo "UNAVAILABLE elan is not on PATH; install elan from https://github.com/leanprover/elan"; return 3; }
10
- tr -d '\r\n' < "$1/lean-toolchain"
11
- }
12
-
13
- lean_pin_ready() {
14
- elan run "$1" lake --version > /dev/null 2>&1
15
- }
16
-
17
- # Prints the pin of the Lake project in $1 when it is ready to run, or why not.
18
- lean_ready_pin() {
19
- local toolchain status
20
- toolchain=$(lean_pin "$1") || { status=$?; echo "$toolchain"; return "$status"; }
21
- lean_pin_ready "$toolchain" \
22
- || { echo "UNAVAILABLE $toolchain is not ready; run bash $(dirname "${BASH_SOURCE[0]}")/setup.sh lean $1"; return 3; }
23
- echo "$toolchain"
24
- }
@@ -1,47 +0,0 @@
1
- #!/bin/bash
2
- # Copyright (c) 2026 Michael Denyer
3
- # SPDX-License-Identifier: GPL-3.0-only
4
- # Shared tool pin and prerequisite checks; nothing here downloads.
5
- TLA_VERSION=v1.7.4
6
- TLA_SHA256=936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88
7
- TLA_RELEASE=https://github.com/tlaplus/tlaplus/releases/tag/$TLA_VERSION
8
- JAVA=${JAVA:-java}
9
- TLC_CACHE=${TLC_CACHE:-$HOME/.cache/tla}
10
- TLC_JAR_SUPPLIED=${TLC_JAR:+yes}
11
- TLC_JAR=${TLC_JAR:-$TLC_CACHE/tla2tools-$TLA_VERSION.jar}
12
-
13
- require_tlc_runtime() {
14
- if ! "$JAVA" -version > /dev/null 2>&1; then
15
- echo "UNAVAILABLE $JAVA has no runtime; install a JDK and set JAVA to its java binary"
16
- return 3
17
- fi
18
- command -v python3 > /dev/null || { echo "UNAVAILABLE python3 is not on PATH; install Python 3"; return 3; }
19
- }
20
-
21
- check_tlc_jar() {
22
- local jar=$1 got
23
- [ -f "$jar" ] || { echo "UNAVAILABLE $jar is missing; save tla2tools.jar from $TLA_RELEASE there, or set TLC_JAR"; return 3; }
24
- if command -v sha256sum > /dev/null; then
25
- got=$(sha256sum "$jar") || { echo "UNAVAILABLE cannot hash $jar with sha256sum; check its permissions"; return 3; }
26
- elif command -v shasum > /dev/null; then
27
- got=$(shasum -a 256 "$jar") || { echo "UNAVAILABLE cannot hash $jar with shasum; check its permissions"; return 3; }
28
- else
29
- echo "UNAVAILABLE install sha256sum or shasum to verify TLC"
30
- return 3
31
- fi
32
- got=${got%% *}
33
- [ "$got" = "$TLA_SHA256" ] || { echo "UNAVAILABLE $jar has sha256 $got, want $TLA_SHA256"; return 3; }
34
- }
35
-
36
- # A JAR the user supplies is trusted; the cached one must match the pin.
37
- tlc_jar_ready() {
38
- local probe
39
- if [ -n "$TLC_JAR_SUPPLIED" ]; then
40
- [ -f "$TLC_JAR" ] || { echo "UNAVAILABLE supplied TLC_JAR $TLC_JAR does not exist"; return 3; }
41
- else
42
- check_tlc_jar "$TLC_JAR" || return $?
43
- fi
44
- probe=$("$JAVA" -cp "$TLC_JAR" tlc2.TLC -help 2>&1) \
45
- || [[ $probe == *"TLC - provides model checking"* ]] \
46
- || { echo "UNAVAILABLE tlc2.TLC cannot run from $TLC_JAR; save a working JAR from $TLA_RELEASE or set TLC_JAR"; echo "$probe"; return 3; }
47
- }