agent-formal-verify 0.4.5 → 0.4.9
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 +44 -0
- package/README.md +1 -1
- package/package.json +1 -1
- package/skills/formal-verify/SKILL.md +24 -7
- package/skills/formal-verify/examples/kani-template/src/lib.rs +6 -0
- package/skills/formal-verify/examples/lean-template/Model/BoundedQueue.lean +22 -7
- package/skills/formal-verify/examples/lean-template/Model/BoundedQueue.mutations +6 -1
- package/skills/formal-verify/examples/lean-template/Model/BoundedQueue.statements +34 -6
- package/skills/formal-verify/examples/lean-template/lean-toolchain +1 -1
- package/skills/formal-verify/references/lean-brief.md +24 -4
- package/skills/formal-verify/references/review-brief.md +45 -0
- package/skills/formal-verify/references/rust-brief.md +14 -6
- package/skills/formal-verify/references/setup.md +1 -1
- package/skills/formal-verify/references/tla-brief.md +3 -2
- package/skills/formal-verify/scripts/baseline.py +413 -0
- package/skills/formal-verify/scripts/kani.py +37 -0
- package/skills/formal-verify/scripts/lean-check.sh +88 -9
- package/skills/formal-verify/scripts/lean-mutations.lean +95 -0
- package/skills/formal-verify/scripts/lean-replay.lean +19 -0
- package/skills/formal-verify/scripts/lean-statements.py +61 -39
- package/skills/formal-verify/scripts/lean-tools.sh +9 -0
- package/skills/formal-verify/scripts/mutate.py +271 -138
- package/skills/formal-verify/scripts/tlc-matrix.sh +4 -167
- package/skills/formal-verify/scripts/tlc.py +310 -0
|
@@ -0,0 +1,95 @@
|
|
|
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
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
-- Copyright (c) 2026 Michael Denyer
|
|
2
|
+
-- SPDX-License-Identifier: GPL-3.0-only
|
|
3
|
+
-- Replay exact modules with the pin's checker, without its CLI's prefix search.
|
|
4
|
+
import LeanChecker
|
|
5
|
+
|
|
6
|
+
open Lean
|
|
7
|
+
|
|
8
|
+
unsafe def replayModules : IO Unit := do
|
|
9
|
+
initSearchPath (← findSysroot)
|
|
10
|
+
let some path ← IO.getEnv "AFV_REPLAY_MODULES"
|
|
11
|
+
| throw <| IO.userError "AFV_REPLAY_MODULES must name a module list"
|
|
12
|
+
for module in (← IO.FS.lines path) do
|
|
13
|
+
IO.println s!"replaying {module}"
|
|
14
|
+
try replayFromImports module.toName
|
|
15
|
+
catch error =>
|
|
16
|
+
IO.eprintln s!"leanchecker found a problem in {module}"
|
|
17
|
+
throw error
|
|
18
|
+
|
|
19
|
+
#eval replayModules
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
# SPDX-License-Identifier: GPL-3.0-only
|
|
4
4
|
"""Store or check declaration fingerprints emitted by the Lean audit."""
|
|
5
5
|
|
|
6
|
+
import argparse
|
|
6
7
|
import hashlib
|
|
7
8
|
import json
|
|
8
9
|
import sys
|
|
@@ -28,6 +29,16 @@ def declarations(audit):
|
|
|
28
29
|
return modules
|
|
29
30
|
|
|
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
|
+
|
|
31
42
|
def read_record(path):
|
|
32
43
|
record = json.loads(path.read_text(encoding="utf-8"))
|
|
33
44
|
if not isinstance(record, dict) or record.get("format") != 1:
|
|
@@ -62,36 +73,38 @@ def check_orphans(project):
|
|
|
62
73
|
return int(failed)
|
|
63
74
|
|
|
64
75
|
|
|
65
|
-
def
|
|
66
|
-
|
|
67
|
-
return check_orphans(Path(sys.argv[2]))
|
|
68
|
-
mode, toolchain, audit, oleans, *sources = sys.argv[1:]
|
|
69
|
-
modules = declarations(Path(audit))
|
|
70
|
-
paths = Path(oleans).read_text(encoding="utf-8").splitlines()
|
|
71
|
-
if len(paths) != len(sources):
|
|
72
|
-
raise ValueError("Lake did not return one module per source")
|
|
76
|
+
def freeze(toolchain, modules, sources):
|
|
77
|
+
"""Record every source's statements, writing none unless all of them can be recorded."""
|
|
73
78
|
pending = []
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
if mode != "freeze" and not path.exists():
|
|
78
|
-
continue
|
|
79
|
-
marker = "/.lake/build/lib/lean/"
|
|
80
|
-
if marker not in olean or not olean.endswith(".olean"):
|
|
81
|
-
raise ValueError(f"cannot identify module from {olean}")
|
|
82
|
-
module = olean.rsplit(marker, 1)[1].removesuffix(".olean").replace("/", ".")
|
|
83
|
-
current = {}
|
|
84
|
-
for record in modules.get(module, []):
|
|
85
|
-
if record["name"] in current:
|
|
86
|
-
raise ValueError(f"ambiguous declaration identity {record['name']} in {module}")
|
|
87
|
-
current[record["name"]] = record
|
|
88
|
-
if mode == "freeze" and not current:
|
|
79
|
+
for module, source in sources:
|
|
80
|
+
records = records_by_name(modules, module)
|
|
81
|
+
if not records:
|
|
89
82
|
raise ValueError(f"no declaration records for {source}")
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
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():
|
|
94
106
|
continue
|
|
107
|
+
records = records_by_name(modules, module)
|
|
95
108
|
frozen = read_record(path)
|
|
96
109
|
if frozen["toolchain"] != toolchain:
|
|
97
110
|
print(f"FROZEN {path}: toolchain changed from {frozen['toolchain']} to {toolchain}; review and run --freeze")
|
|
@@ -101,7 +114,7 @@ def main():
|
|
|
101
114
|
raise ValueError(f"{path}: expected module {module}, found {frozen['module']}")
|
|
102
115
|
changed = 0
|
|
103
116
|
for old in frozen["declarations"]:
|
|
104
|
-
new =
|
|
117
|
+
new = records.get(old["name"])
|
|
105
118
|
if new is not None and all(old[key] == new[key] for key in ("kind", "typeHash", "valueHash")):
|
|
106
119
|
continue
|
|
107
120
|
changed += 1
|
|
@@ -113,20 +126,29 @@ def main():
|
|
|
113
126
|
if changed == len(frozen["declarations"]):
|
|
114
127
|
print(f"FROZEN {path}: every recorded declaration changed; review the model and toolchain before --freeze")
|
|
115
128
|
failed |= changed > 0
|
|
116
|
-
for path, contents in pending:
|
|
117
|
-
temporary = None
|
|
118
|
-
try:
|
|
119
|
-
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent, delete=False) as stream:
|
|
120
|
-
temporary = Path(stream.name)
|
|
121
|
-
stream.write(contents)
|
|
122
|
-
temporary.replace(path)
|
|
123
|
-
finally:
|
|
124
|
-
if temporary is not None:
|
|
125
|
-
temporary.unlink(missing_ok=True)
|
|
126
|
-
print(f"FROZEN {path}: statements recorded; proofs not checked")
|
|
127
129
|
return int(failed)
|
|
128
130
|
|
|
129
131
|
|
|
132
|
+
def main():
|
|
133
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
134
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
135
|
+
commands.add_parser("orphans", help="report records whose source file is gone").add_argument("project", type=Path)
|
|
136
|
+
for name, purpose in (("freeze", "record each source's statements"), ("check", "compare each recorded source's statements")):
|
|
137
|
+
command = commands.add_parser(name, help=purpose)
|
|
138
|
+
command.add_argument("toolchain")
|
|
139
|
+
command.add_argument("audit", type=Path, help="the audit's output, with its STATEMENT lines")
|
|
140
|
+
command.add_argument("module_names", type=Path, help="the module of each source, one per line in source order")
|
|
141
|
+
command.add_argument("sources", nargs="+", type=Path)
|
|
142
|
+
arguments = parser.parse_args()
|
|
143
|
+
if arguments.command == "orphans":
|
|
144
|
+
return check_orphans(arguments.project)
|
|
145
|
+
names = arguments.module_names.read_text(encoding="utf-8").splitlines()
|
|
146
|
+
if len(names) != len(arguments.sources):
|
|
147
|
+
raise ValueError("Lake did not return one module per source")
|
|
148
|
+
action = freeze if arguments.command == "freeze" else check
|
|
149
|
+
return action(arguments.toolchain, declarations(arguments.audit), zip(names, arguments.sources))
|
|
150
|
+
|
|
151
|
+
|
|
130
152
|
if __name__ == "__main__":
|
|
131
153
|
try:
|
|
132
154
|
sys.exit(main())
|
|
@@ -13,3 +13,12 @@ lean_pin() {
|
|
|
13
13
|
lean_pin_ready() {
|
|
14
14
|
elan run "$1" lake --version > /dev/null 2>&1
|
|
15
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
|
+
}
|