agent-formal-verify 0.4.8 → 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.
@@ -0,0 +1,413 @@
1
+ #!/usr/bin/env python3
2
+ # Copyright (c) 2026 Michael Denyer
3
+ # SPDX-License-Identifier: GPL-3.0-only
4
+ """Record what each model specifies before agents edit it, and compare it afterwards.
5
+
6
+ A model's surface is a mapping from item name to a canonical value. Every tool
7
+ uses one rule to compare surfaces: a removed item or a changed value is a
8
+ change, and so is an added item whose kind narrows what is checked.
9
+
10
+ .statements Lean. The toolchain, and each declaration's kind, type hash and value hash.
11
+ Added declarations are allowed.
12
+ .matrix TLA+. Each directive of the matrix, and the normalized definitions of Spec,
13
+ of each operator a check or reach line names, and of the operators those
14
+ reference, in the spec each section names. Spec is not followed into its actions.
15
+ .rs Kani. Each harness name, and each kani::assume, kani::any_where, kani::cover! and
16
+ #[kani::stub] anywhere in the file. Added covers and harnesses are allowed.
17
+ Added assumes and stubs are changes.
18
+
19
+ Usage:
20
+ baseline.py record <record-file> <model-file>... record these files, keep the other entries
21
+ baseline.py compare <record-file> exit 1 when a recorded file changed
22
+
23
+ Compare prints UNCHANGED or CHANGED per file, indented lines for each item that
24
+ changed, and a SUMMARY line. Exit codes: 0 unchanged, 1 changed or a record or
25
+ model file that fails to parse, 2 usage error.
26
+ """
27
+ import argparse
28
+ import hashlib
29
+ import importlib.util
30
+ import json
31
+ import re
32
+ import sys
33
+ import tempfile
34
+ from pathlib import Path
35
+ from typing import NamedTuple
36
+
37
+ sys.dont_write_bytecode = True
38
+
39
+ import tlc
40
+
41
+ HERE = Path(__file__).resolve().parent
42
+ FORMAT = 1
43
+ NARROWING = {"lean": (), "tla": (), "kani": ("assume", "stub")}
44
+ KINDS = {".statements": "lean", ".matrix": "tla", ".rs": "kani"}
45
+ STRING = re.compile(r'"(?:\\.|[^"\\])*"', re.DOTALL)
46
+
47
+
48
+ def collapse(text, literals=None):
49
+ if literals is None:
50
+ literals = (match.span() for match in STRING.finditer(text))
51
+ parts, end = [], 0
52
+ for start, stop in literals:
53
+ parts.extend((re.sub(r"\s+", " ", text[end:start]), text[start:stop]))
54
+ end = stop
55
+ parts.append(re.sub(r"\s+", " ", text[end:]))
56
+ return "".join(parts).strip()
57
+
58
+
59
+ class Surface(dict):
60
+ def add(self, name, value=""):
61
+ candidate, count = name, 1
62
+ while candidate in self:
63
+ count += 1
64
+ candidate = f"{name} #{count}"
65
+ self[candidate] = value
66
+
67
+
68
+ def lean_surface(path):
69
+ spec = importlib.util.spec_from_file_location("lean_statements", HERE / "lean-statements.py")
70
+ module = importlib.util.module_from_spec(spec)
71
+ spec.loader.exec_module(module)
72
+ record = module.read_record(path)
73
+ surface = Surface()
74
+ surface.add("toolchain", record["toolchain"])
75
+ for entry in record["declarations"]:
76
+ surface.add(f"declaration {entry['name']}", f"{entry['kind']} {entry['typeHash']} {entry['valueHash'] or '-'}")
77
+ return surface
78
+
79
+
80
+ def blank_tla_comments(text):
81
+ out, i = [], 0
82
+ while i < len(text):
83
+ if text[i] == '"':
84
+ string = STRING.match(text, i)
85
+ if string is None:
86
+ raise ValueError("unterminated TLA+ string")
87
+ out.append(string[0])
88
+ i = string.end()
89
+ elif text.startswith("(*", i):
90
+ depth = 0
91
+ while i < len(text):
92
+ if text.startswith("(*", i):
93
+ depth += 1
94
+ i += 2
95
+ elif text.startswith("*)", i):
96
+ depth -= 1
97
+ i += 2
98
+ if not depth:
99
+ break
100
+ else:
101
+ out.append("\n" if text[i] == "\n" else "")
102
+ i += 1
103
+ out.append(" ")
104
+ elif text.startswith("\\*", i):
105
+ end = text.find("\n", i)
106
+ i = len(text) if end < 0 else end
107
+ out.append(" ")
108
+ else:
109
+ out.append(text[i])
110
+ i += 1
111
+ return "".join(out)
112
+
113
+
114
+ DEFINITION = re.compile(r"(?:LOCAL\s+)?(\w*[A-Za-z]\w*)\s*(?:\((?:[^()]|\([^()]*\))*\)|\[(?:[^\[\]]|\[[^\[\]]*\])*\])?\s*==")
115
+ MODULE_LEVEL = re.compile(r"-{4,}|={4,}|(?:EXTENDS|VARIABLES?|CONSTANTS?|ASSUME|ASSUMPTION|AXIOM|THEOREM|LEMMA|PROPOSITION|COROLLARY|INSTANCE|RECURSIVE|USE|HIDE)\b")
116
+ IDENTIFIER = re.compile(r"\w*[A-Za-z]\w*")
117
+ SUBSCRIPT = r"_(?:\w+|<<[^>]*>>)"
118
+ SPEC_ACTIONS = re.compile(rf"\[\]\[[^\]]*\]{SUBSCRIPT}|[WS]F{SUBSCRIPT}\s*\([^()]*\)")
119
+
120
+
121
+ def begins_in_column_zero(line):
122
+ return line[:1].strip() != ""
123
+
124
+
125
+ def tla_definitions(text):
126
+ found, unreadable, name, lines = {}, set(), None, []
127
+ for line in blank_tla_comments(text).split("\n"):
128
+ if begins_in_column_zero(line):
129
+ match = DEFINITION.match(line)
130
+ header = None if match or MODULE_LEVEL.match(line) or "==" not in line else collapse(line.partition("==")[0])
131
+ if match or header or MODULE_LEVEL.match(line):
132
+ if name:
133
+ found[name] = collapse(" ".join(lines))
134
+ name, lines = (match[1] if match else header), ([line] if match or header else [])
135
+ if header:
136
+ unreadable.add(header)
137
+ continue
138
+ if name:
139
+ lines.append(line)
140
+ if name:
141
+ found[name] = collapse(" ".join(lines))
142
+ return found, unreadable
143
+
144
+
145
+ def tla_closure(definitions, roots):
146
+ seen, pending = set(), list(roots)
147
+ while pending:
148
+ name = pending.pop()
149
+ if name in seen:
150
+ continue
151
+ seen.add(name)
152
+ body = definitions[name].partition("==")[2]
153
+ if name == "Spec":
154
+ body = SPEC_ACTIONS.sub(" ", body)
155
+ pending += [word for word in IDENTIFIER.findall(body) if word in definitions and word != name]
156
+ return seen
157
+
158
+
159
+ def tla_surface(path):
160
+ surface = Surface()
161
+ sections = []
162
+ parsed = list(tlc.directives(tlc.read_raw(path).split("\n")))
163
+ malformed = [directive.message for directive in parsed if isinstance(directive, tlc.Malformed)]
164
+ if malformed:
165
+ raise ValueError(f"{path}: {'; '.join(malformed)}")
166
+ for directive in parsed:
167
+ if isinstance(directive, tlc.Spec):
168
+ if not directive.path:
169
+ raise ValueError(f"{path}: spec line has no path")
170
+ surface.add(f"spec {directive.path}")
171
+ sections.append((directive.path, set()))
172
+ elif isinstance(directive, tlc.Check):
173
+ for name in directive.names:
174
+ surface.add(f"check {sections[-1][0]} {directive.kind} {name}")
175
+ sections[-1][1].update(directive.names)
176
+ elif isinstance(directive, tlc.Reach):
177
+ surface.add(f"reach {sections[-1][0]} {directive.operator} | {collapse(directive.match)}")
178
+ sections[-1][1].add(directive.operator)
179
+ else:
180
+ surface.add(f"run {sections[-1][0]} {collapse(directive.label)}", collapse(directive.constants))
181
+ for spec, operators in sections:
182
+ source = path.parent / spec
183
+ if not source.is_file():
184
+ raise ValueError(f"{path}: spec {spec} not found")
185
+ definitions, unreadable = tla_definitions(tlc.read_raw(source))
186
+ for name in sorted({"Spec", *operators}):
187
+ if name not in definitions:
188
+ raise ValueError(f"{path}: {name} is named in the {spec} section but {source} does not define it")
189
+ for name in sorted(tla_closure(definitions, {"Spec", *operators, *unreadable})):
190
+ surface[f"definition {spec} {name}"] = definitions[name]
191
+ return surface
192
+
193
+
194
+ class RustSource(NamedTuple):
195
+ uncommented: str
196
+ without_comments_or_strings: str
197
+ literals: list
198
+
199
+
200
+ def rust_masks(source):
201
+ text, mask = list(source), list(source)
202
+ literals = []
203
+
204
+ def blank(start, end, *, both):
205
+ for i in range(start, end):
206
+ if source[i] != "\n":
207
+ mask[i] = " "
208
+ if both:
209
+ text[i] = " "
210
+
211
+ i = 0
212
+ while i < len(source):
213
+ if source.startswith("//", i):
214
+ end = source.find("\n", i)
215
+ end = len(source) if end < 0 else end
216
+ blank(i, end, both=True)
217
+ i = end
218
+ elif source.startswith("/*", i):
219
+ depth, start = 0, i
220
+ while i < len(source):
221
+ if source.startswith("/*", i):
222
+ depth, i = depth + 1, i + 2
223
+ elif source.startswith("*/", i):
224
+ depth, i = depth - 1, i + 2
225
+ if not depth:
226
+ break
227
+ else:
228
+ i += 1
229
+ blank(start, i, both=True)
230
+ elif raw := re.compile(r'(?<!\w)[bc]?r(#*)"').match(source, i):
231
+ close = source.find('"' + raw[1], raw.end())
232
+ content_end = len(source) if close < 0 else close
233
+ blank(raw.end(), content_end, both=False)
234
+ i = content_end + 1 + len(raw[1])
235
+ literals.append((raw.start(), min(i, len(source))))
236
+ elif source[i] == '"':
237
+ opening = i
238
+ start = i = i + 1
239
+ while i < len(source) and source[i] != '"':
240
+ i += 2 if source[i] == "\\" else 1
241
+ blank(start, min(i, len(source)), both=False)
242
+ i += 1
243
+ literals.append((opening, min(i, len(source))))
244
+ elif char := re.compile(r"'(?:\\.[^']*|[^'\\])'").match(source, i):
245
+ blank(char.start() + 1, char.end() - 1, both=False)
246
+ i = char.end()
247
+ literals.append(char.span())
248
+ else:
249
+ i += 1
250
+ return RustSource("".join(text), "".join(mask), literals)
251
+
252
+
253
+ def after_closing(mask, opener):
254
+ closer = {"(": ")", "[": "]"}[mask[opener]]
255
+ depth = 0
256
+ for i in range(opener, len(mask)):
257
+ depth += (mask[i] == mask[opener]) - (mask[i] == closer)
258
+ if not depth:
259
+ return i + 1
260
+ raise ValueError(f"unbalanced {mask[opener]} at offset {opener}")
261
+
262
+
263
+ KANI_ATTRIBUTE = r"#\s*\[\s*(?:cfg_attr\s*\(\s*kani\s*,\s*)?kani\s*::\s*"
264
+ MACROS = (
265
+ ("assume", re.compile(r"\bkani\s*::\s*assume\s*\(")),
266
+ ("assume", re.compile(r"\bkani\s*::\s*any_where\s*(?:::\s*<[^<>]*(?:<[^<>]*>[^<>]*)*>\s*)?\(")),
267
+ ("cover", re.compile(r"\bkani\s*::\s*cover\s*!\s*\(")),
268
+ ("stub", re.compile(KANI_ATTRIBUTE + r"stub\s*\(")),
269
+ )
270
+ PROOF = re.compile(KANI_ATTRIBUTE + r"proof(?:_for_contract\s*\([^)]*\))?\s*\)?\s*\]")
271
+ FUNCTION = re.compile(r"(?:pub(?:\s*\([^)]*\))?\s+)?(?:(?:async|unsafe|const)\s+)*fn\s+(\w+)")
272
+ KANI_TOKEN = re.compile(r"\bkani\s*::\s*(?:assume|any_where|cover|stub|proof)\w*\b")
273
+ RENAMING_IMPORT = re.compile(r"\buse\s+[^;]*?(?<![\w:])(?:::\s*)?kani\b[^;]*?(?:\bas\b|\*|\b(?:assume|any_where|cover|stub|proof)\w*\b)|\bextern\s+crate\s+kani\s+as\b")
274
+
275
+
276
+ def kani_surface(path):
277
+ source = rust_masks(path.read_text(encoding="utf-8"))
278
+ text, mask = source.uncommented, source.without_comments_or_strings
279
+ if renaming := RENAMING_IMPORT.search(mask):
280
+ raise ValueError(f"{path}: '{collapse(renaming[0])}' brings a Kani assumption, cover, stub or harness attribute in under another name; write each as kani::<name> so the record can read it")
281
+ surface = Surface()
282
+ spans, read = [], []
283
+ for kind, pattern in MACROS:
284
+ for match in pattern.finditer(mask):
285
+ end = after_closing(mask, match.end() - 1)
286
+ read.append((match.start(), end))
287
+ argument = rust_masks(text[match.end():end - 1])
288
+ spans.append((match.start(), kind, collapse(argument.uncommented, argument.literals)))
289
+ for match in PROOF.finditer(mask):
290
+ read.append(match.span())
291
+ i = match.end()
292
+ while True:
293
+ i = len(mask) - len(mask[i:].lstrip())
294
+ if mask.startswith("#", i):
295
+ i = after_closing(mask, mask.index("[", i))
296
+ else:
297
+ break
298
+ name = FUNCTION.match(mask, i)
299
+ if not name:
300
+ raise ValueError(f"{path}: #[kani::proof] at offset {match.start()} is not followed by a function")
301
+ spans.append((match.start(), "harness", name[1]))
302
+ for token in KANI_TOKEN.finditer(mask):
303
+ if not any(start <= token.start() < end for start, end in read):
304
+ line = mask.count("\n", 0, token.start()) + 1
305
+ raise ValueError(f"{path}:{line}: '{collapse(token[0])}' is in a form the record cannot read; write kani::assume(...), kani::any_where(...), kani::cover!(...), #[kani::stub(...)] or #[kani::proof], alone or under #[cfg_attr(kani, ...)]")
306
+ for _, kind, item in sorted(spans):
307
+ surface.add(f"{kind} {item}")
308
+ return surface
309
+
310
+
311
+ SURFACES = {"lean": lean_surface, "tla": tla_surface, "kani": kani_surface}
312
+
313
+
314
+ def digest(surface):
315
+ return hashlib.sha256(json.dumps(surface, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")).hexdigest()
316
+
317
+
318
+ def read_record(path):
319
+ record = json.loads(path.read_text(encoding="utf-8"))
320
+ models = record.get("models") if isinstance(record, dict) else None
321
+ if not isinstance(models, dict) or record.get("format") != FORMAT:
322
+ raise ValueError(f"{path}: unsupported record format")
323
+ for model, entry in models.items():
324
+ if not isinstance(entry, dict) or entry.get("kind") not in SURFACES or not isinstance(entry.get("surface"), dict):
325
+ raise ValueError(f"{path}: malformed entry for {model}")
326
+ return models
327
+
328
+
329
+ def write_record(path, models):
330
+ path.parent.mkdir(parents=True, exist_ok=True)
331
+ temporary = None
332
+ try:
333
+ with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent, delete=False) as stream:
334
+ temporary = Path(stream.name)
335
+ stream.write(json.dumps({"format": FORMAT, "models": models}, ensure_ascii=False, indent=2, sort_keys=True) + "\n")
336
+ temporary.replace(path)
337
+ finally:
338
+ if temporary is not None:
339
+ temporary.unlink(missing_ok=True)
340
+
341
+
342
+ def record(record_path, files):
343
+ for file in files:
344
+ if file.suffix not in KINDS:
345
+ print(f"usage: {file} has no model surface; expected one of {', '.join(KINDS)}")
346
+ return 2
347
+ models = read_record(record_path) if record_path.exists() else {}
348
+ updates = {}
349
+ for file in files:
350
+ kind = KINDS[file.suffix]
351
+ surface = SURFACES[kind](file.resolve())
352
+ updates[str(file.resolve())] = {"kind": kind, "digest": digest(surface), "surface": surface}
353
+ for model, entry in updates.items():
354
+ print(f"RECORDED {model} {entry['digest']}")
355
+ previous = models.get(model, {}).get("digest")
356
+ if previous and previous != entry["digest"]:
357
+ print(f" previous {previous}")
358
+ write_record(record_path, {**models, **updates})
359
+ return 0
360
+
361
+
362
+ def differences(kind, old, new):
363
+ lines = []
364
+ for name in old:
365
+ if name not in new:
366
+ lines.append(f" removed {name}")
367
+ elif old[name] != new[name]:
368
+ lines += [f" changed {name}", f" old: {old[name]}", f" new: {new[name]}"]
369
+ lines += [f" added {name}" for name in new if name not in old and name.split(" ", 1)[0] in NARROWING[kind]]
370
+ return lines
371
+
372
+
373
+ def compare(record_path):
374
+ if not record_path.is_file():
375
+ print(f"usage: record file {record_path} does not exist; run record first")
376
+ return 2
377
+ models = read_record(record_path)
378
+ changed = 0
379
+ for model, entry in models.items():
380
+ try:
381
+ if not Path(model).is_file():
382
+ lines = [" file is missing"]
383
+ else:
384
+ lines = differences(entry["kind"], entry["surface"], SURFACES[entry["kind"]](Path(model)))
385
+ except (OSError, ValueError, KeyError, TypeError) as error:
386
+ lines = [f" FAIL {error}"]
387
+ changed += bool(lines)
388
+ print(f"{'CHANGED' if lines else 'UNCHANGED'} {model}")
389
+ if lines:
390
+ print("\n".join(lines))
391
+ print(f"SUMMARY {len(models) - changed} unchanged, {changed} changed")
392
+ return int(changed > 0)
393
+
394
+
395
+ def main():
396
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
397
+ commands = parser.add_subparsers(dest="command", required=True)
398
+ recording = commands.add_parser("record", help="record or update the entries for these model files")
399
+ recording.add_argument("record_file", type=Path)
400
+ recording.add_argument("models", nargs="+", type=Path)
401
+ commands.add_parser("compare", help="compare every recorded model with its file").add_argument("record_file", type=Path)
402
+ arguments = parser.parse_args()
403
+ if arguments.command == "record":
404
+ return record(arguments.record_file, arguments.models)
405
+ return compare(arguments.record_file)
406
+
407
+
408
+ if __name__ == "__main__":
409
+ try:
410
+ sys.exit(main())
411
+ except (OSError, ValueError, KeyError, TypeError) as error:
412
+ print(f"FAIL baseline: {error}")
413
+ sys.exit(1)
@@ -66,6 +66,7 @@ class Kani:
66
66
  if any(home.glob("*.tar.gz")):
67
67
  raise Unavailable(f"incomplete Kani setup at {home}; finish cargo kani setup before checking")
68
68
  self.driver = bundle / "bin/kani-driver"
69
+ self.cargo = bundle / "toolchain/bin/cargo"
69
70
  self.env = os.environ | {
70
71
  "KANI_HOME": str(home),
71
72
  "RUSTUP_TOOLCHAIN": str((bundle / "toolchain").resolve()),
@@ -95,6 +96,42 @@ class Kani:
95
96
  except OSError as error:
96
97
  raise CheckError(f"cannot execute Kani: {error}") from error
97
98
 
99
+ def source_roots(self, crate, work):
100
+ """Find each local package's workspace, including transitive and optional path dependencies."""
101
+ pending, visited, roots = {crate}, set(), set()
102
+ while pending:
103
+ directory = pending.pop()
104
+ if directory in visited:
105
+ continue
106
+ visited.add(directory)
107
+ try:
108
+ done = subprocess.run(
109
+ [str(self.cargo), "metadata", *(["--no-deps"] if directory != crate else []),
110
+ "--format-version", "1", "--manifest-path", str(directory / "Cargo.toml")],
111
+ cwd=work, env=self.env, capture_output=True, text=True, check=False)
112
+ except OSError as error:
113
+ raise CheckError(f"cannot read Cargo metadata: {error}") from error
114
+ if done.returncode:
115
+ raise CheckError(f"Cargo metadata failed for {directory}:\n{done.stdout}{done.stderr}")
116
+ try:
117
+ report = json.loads(done.stdout)
118
+ if report["version"] != 1:
119
+ raise CheckError("unsupported Cargo metadata version")
120
+ paths = [Path(report["workspace_root"]), directory]
121
+ for package in report["packages"]:
122
+ if package["source"] is not None:
123
+ continue
124
+ paths.append(Path(package["manifest_path"]).parent)
125
+ paths.extend(Path(dependency["path"]) for dependency in package["dependencies"] if "path" in dependency)
126
+ if not all(path.is_absolute() for path in paths):
127
+ raise CheckError("Cargo metadata returned a relative source path")
128
+ roots.add(paths[0].resolve())
129
+ roots.add(directory)
130
+ pending.update(path.resolve() for path in paths[2:])
131
+ except (ValueError, KeyError, TypeError) as error:
132
+ raise CheckError(f"malformed Cargo metadata: {error}") from error
133
+ return roots
134
+
98
135
 
99
136
  def invoke(crate, work, kani, *arguments):
100
137
  return kani.run("--manifest-path", str(crate / "Cargo.toml"),
@@ -3,8 +3,13 @@
3
3
  # SPDX-License-Identifier: GPL-3.0-only
4
4
  # Builds a Lean 4 model with Lake, then audits every declaration of every built
5
5
  # module. Fails when the build fails, a declaration uses sorry or rests on an
6
- # axiom beyond propext, Classical.choice and Quot.sound, or no Lake library
7
- # owns a .lean file in the project. Otherwise prints the build output and PASS.
6
+ # axiom beyond propext, Classical.choice and Quot.sound, no Lake library owns a
7
+ # .lean file in the project, a theorem named <Property>.witness does not state
8
+ # that the hypotheses of <Property> hold together, or the pin's leanchecker
9
+ # rejects a built module on kernel replay. Otherwise prints the build output,
10
+ # a WITNESS line for each property and PASS. A property without a witness
11
+ # passes, and so does a pin that ships no leanchecker; the PASS line counts the
12
+ # first and reports the replay as unavailable for the second.
8
13
  # Named files limit the check to those sources, so agents that share a project
9
14
  # can each check their own model; a run without them checks the whole project.
10
15
  # Needs a pin of Lean 4.20.0 or later, the first whose Lake builds a module by
@@ -26,9 +31,7 @@ HERE=$(cd "$(dirname "$0")" && pwd)
26
31
  dir=$(cd "$dir" && pwd)
27
32
  # shellcheck source=skills/formal-verify/scripts/lean-tools.sh
28
33
  source "$HERE/lean-tools.sh"
29
- toolchain=$(lean_pin "$dir") || { status=$?; echo "$toolchain"; exit "$status"; }
30
- lean_pin_ready "$toolchain" \
31
- || { echo "UNAVAILABLE $toolchain is not ready; run bash $HERE/setup.sh lean $dir"; exit 3; }
34
+ toolchain=$(lean_ready_pin "$dir") || { status=$?; echo "$toolchain"; exit "$status"; }
32
35
 
33
36
  work=$(mktemp -d)
34
37
  trap 'rm -rf "$work"' EXIT
@@ -74,9 +77,13 @@ sorries=$(grep -cE "$sorry" "$log")
74
77
  audit_status=0
75
78
  : > "$work/audit.out"
76
79
  if [ "$status" -eq 0 ]; then
80
+ # The module of each source, in source order, for the audit's imports and the frozen records.
81
+ unexpected=$(grep -v '/\.lake/build/lib/lean/.*\.olean$' "$work/oleans")
82
+ [ -z "$unexpected" ] || { echo "FAIL $scope: cannot identify the module of $unexpected"; exit 1; }
83
+ sed -e 's|^.*/\.lake/build/lib/lean/||' -e 's|\.olean$||' -e 's|/|.|g' "$work/oleans" > "$work/modules"
77
84
  {
78
85
  echo "import Lean"
79
- sed -e 's|^.*/\.lake/build/lib/lean/||' -e 's|\.olean$||' -e 's|/|.|g' -e 's|^|import |' "$work/oleans"
86
+ sed 's|^|import |' "$work/modules"
80
87
  cat << 'EOF'
81
88
  open Lean in
82
89
  private def hasTheoremParent (env : Environment) : Name → Bool
@@ -84,14 +91,43 @@ private def hasTheoremParent (env : Environment) : Name → Bool
84
91
  | .str parent _ | .num parent _ =>
85
92
  (match env.find? parent with | some (.thmInfo _) => true | _ => false) || hasTheoremParent env parent
86
93
 
94
+ private def oneLine (s : String) : String :=
95
+ (s.foldl (fun (acc, gap) c =>
96
+ if c.isWhitespace then (acc, true) else ((if gap then acc.push ' ' else acc).push c, false)) ("", false)).1
97
+
98
+ open Lean Meta in
99
+ private def witnessLine (property : ConstantInfo) (witness? : Option ConstantInfo) : MetaM String :=
100
+ forallTelescope property.type fun xs _ => do
101
+ let name := property.name
102
+ let binders ← xs.mapM fun x => return (x, ← inferType x)
103
+ let hyps ← binders.filterM fun (_, type) => isProp type
104
+ if hyps.isEmpty then return s!"WITNESS no-hypotheses {name}"
105
+ let proofs := hyps.map (·.1.fvarId!)
106
+ for (x, type) in binders do
107
+ if type.hasAnyFVar proofs.contains then
108
+ return s!"WITNESS unavailable {name}: the type of {← ppExpr x} uses the proof of a hypothesis"
109
+ let vars := binders.filter fun (x, _) => !proofs.contains x.fvarId!
110
+ let all := hyps.pop.foldr (fun (_, hyp) rest => mkAnd hyp rest) hyps.back!.2
111
+ -- Explicit binders printed with their types let the statement be copied into the model.
112
+ let expected ← vars.foldrM (fun (x, type) body => do
113
+ mkAppM ``Exists #[.lam (← x.fvarId!.getUserName) type (body.abstract #[x]) .default]) all
114
+ let shown := oneLine (← withOptions (·.setBool `pp.funBinderTypes true) (ppExpr expected)).pretty
115
+ let some witness := witness? | return s!"WITNESS absent {name}: no theorem {name}.witness states {shown}"
116
+ let levels ← mkFreshLevelMVars property.levelParams.length
117
+ if ← isDefEq witness.type (expected.instantiateLevelParams property.levelParams levels) then
118
+ return s!"WITNESS checked {name}"
119
+ return s!"WITNESS failed {name}: {name}.witness must state {shown}"
120
+
87
121
  open Lean Elab Command in
88
122
  #eval show CommandElabM Unit from do
89
123
  let env ← getEnv
90
124
  let freezing := (← IO.getEnv "AFV_FREEZE") == some "1"
91
125
  let modules := (env.imports.map (·.module)).erase `Lean
126
+ for module in env.header.moduleNames do IO.println s!"IMPORTED {module.toString (escape := false)}"
92
127
  let standard : Array Name := #[``propext, ``Classical.choice, ``Quot.sound]
93
128
  let names := env.constants.fold (fun acc name info => if info matches .axiomInfo _ then acc else acc.push name) #[]
94
129
  let mut audited := 0
130
+ let mut theorems : Array (Name × Name × ModuleIdx) := #[]
95
131
  for name in names do
96
132
  let some idx := env.getModuleIdxFor? name | continue
97
133
  unless modules.contains env.header.moduleNames[idx.toNat]! do continue
@@ -122,6 +158,19 @@ open Lean Elab Command in
122
158
  ("typeExpr", toJson (reprStr (info.levelParams, info.type))),
123
159
  ("valueExpr", value), ("type", toJson pp.pretty)]
124
160
  IO.println s!"STATEMENT {record.compress}"
161
+ if info matches .thmInfo _ then theorems := theorems.push (name, userName, idx)
162
+ for (name, userName, idx) in theorems.qsort (·.1.toString < ·.1.toString) do
163
+ let pairedWitness := match userName with
164
+ | .str parent "witness" => theorems.any fun (_, user, owner) => owner == idx && user == parent
165
+ | _ => false
166
+ if name != userName || pairedWitness then continue
167
+ if env.isProjectionFn name || Meta.isInstanceCore env name then continue
168
+ if (← findDeclarationRanges? name).isNone then continue
169
+ let witness? := theorems.find? fun (_, user, owner) => owner == idx && user == userName ++ `witness
170
+ let line ← liftTermElabM <| tryCatchRuntimeEx
171
+ (witnessLine (env.find? name).get! (witness?.bind (env.find? ·.1)))
172
+ fun error => return s!"WITNESS unavailable {name}: {oneLine (← error.toMessageData.toString)}"
173
+ IO.println line
125
174
  IO.println s!"AUDITED {audited} declarations"
126
175
  EOF
127
176
  } > "$work/Audit.lean"
@@ -149,7 +198,7 @@ if [ "$status" -ne 0 ] || { [ "$freeze" -eq 0 ] && [ "$sorries" -ne 0 ]; } || [
149
198
  || echo "$toolchain cannot build a module by its source path; pin Lean 4.20.0 or later"
150
199
  if [ "$audit_status" -ne 0 ]; then
151
200
  echo "the axiom audit did not run or found no declarations:"
152
- grep -v '^[[:space:]]*$' "$work/audit.out" | tail -40
201
+ grep -v -e '^[[:space:]]*$' -e '^IMPORTED ' "$work/audit.out" | tail -40
153
202
  ! grep -q 'environment already contains' "$work/audit.out" \
154
203
  || echo "two modules declare the same name; put each model in a namespace of its own"
155
204
  fi
@@ -157,7 +206,7 @@ if [ "$status" -ne 0 ] || { [ "$freeze" -eq 0 ] && [ "$sorries" -ne 0 ]; } || [
157
206
  fi
158
207
  mode=check
159
208
  [ "$freeze" -eq 0 ] || mode=freeze
160
- python3 "$HERE/lean-statements.py" "$mode" "$toolchain" "$work/audit.out" "$work/oleans" "${sources[@]}" > "$work/statements.out"
209
+ python3 "$HERE/lean-statements.py" "$mode" "$toolchain" "$work/audit.out" "$work/modules" "${sources[@]}" > "$work/statements.out"
161
210
  statement_status=$?
162
211
  if [ "$statement_status" -ne 0 ]; then
163
212
  echo "FAIL $scope: frozen statements differ or could not be checked"
@@ -168,4 +217,34 @@ cat "$work/statements.out"
168
217
  # #eval output arrives as info blocks that can span lines.
169
218
  grep -v '^[[:space:]]*$' "$log"
170
219
  [ "$freeze" -eq 0 ] || exit 0
171
- echo "PASS $scope: $(grep '^AUDITED ' "$work/audit.out" | cut -d' ' -f2) declarations checked, no unfinished proof (sorry), no added axiom"
220
+
221
+ witnesses() { grep -c "^WITNESS $1 " "$work/audit.out"; }
222
+ failed=$(witnesses failed)
223
+ [ "$failed" -eq 0 ] || echo "FAIL $scope: $failed witnesses do not state their property's hypotheses"
224
+ grep '^WITNESS ' "$work/audit.out"
225
+ [ "$failed" -eq 0 ] || exit 1
226
+
227
+ # The build trusts a declaration that a command adds to the environment without
228
+ # a kernel check. leanchecker replays every declaration of the built modules
229
+ # through the kernel and rejects it. Use its exact-module replayer rather than
230
+ # its CLI's prefix search, which also finds deleted sources' cached objects.
231
+ # A named module rests on the project modules it imports, so replay those too.
232
+ replay=unavailable
233
+ if [ -x "$(elan run "$toolchain" lean --print-prefix)/bin/leanchecker" ]; then
234
+ cp "$work/modules" "$work/replay-modules"
235
+ while IFS= read -r module; do
236
+ [ ! -f "$dir/.lake/build/lib/lean/${module//.//}.olean" ] || printf '%s\n' "$module" >> "$work/replay-modules"
237
+ done < <(sed -n 's/^IMPORTED //p' "$work/audit.out")
238
+ sort -u "$work/replay-modules" -o "$work/replay-modules"
239
+ replay=passed
240
+ AFV_REPLAY_MODULES="$work/replay-modules" elan run "$toolchain" lake --dir "$dir" env lean "$HERE/lean-replay.lean" > "$work/replay.out" 2>&1 || replay=failed
241
+ fi
242
+ case $replay in
243
+ passed) echo "REPLAYED $(grep -c '^replaying ' "$work/replay.out") modules through the Lean kernel" ;;
244
+ failed)
245
+ echo "FAIL $scope: kernel replay rejected a built module"
246
+ cat "$work/replay.out"
247
+ exit 1 ;;
248
+ unavailable) echo "UNAVAILABLE kernel replay: $toolchain ships no leanchecker" ;;
249
+ esac
250
+ echo "PASS $scope: $(grep '^AUDITED ' "$work/audit.out" | cut -d' ' -f2) declarations checked, no unfinished proof (sorry), no added axiom, kernel replay $replay, $(witnesses checked) witnesses checked, $(witnesses absent) absent, $(witnesses unavailable) unavailable, $(witnesses no-hypotheses) properties without hypotheses"