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.
Files changed (43) hide show
  1. package/CHANGES.md +150 -0
  2. package/README.md +5 -3
  3. package/package.json +2 -1
  4. package/skills/formal-verify/SKILL.md +17 -19
  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 +33 -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 +3 -3
  16. package/skills/formal-verify/scripts/baseline.py +290 -261
  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/kani_reader.py +592 -0
  20. package/skills/formal-verify/scripts/lean-analysis.lean +387 -0
  21. package/skills/formal-verify/scripts/lean-check.sh +6 -243
  22. package/skills/formal-verify/scripts/lean.py +484 -0
  23. package/skills/formal-verify/scripts/lean_mutations.py +195 -0
  24. package/skills/formal-verify/scripts/lean_records.py +25 -0
  25. package/skills/formal-verify/scripts/mutate.py +81 -195
  26. package/skills/formal-verify/scripts/processes.py +266 -0
  27. package/skills/formal-verify/scripts/python-tools.sh +15 -0
  28. package/skills/formal-verify/scripts/runner.py +56 -0
  29. package/skills/formal-verify/scripts/rust_source.py +74 -0
  30. package/skills/formal-verify/scripts/setup.sh +18 -19
  31. package/skills/formal-verify/scripts/storage.py +207 -0
  32. package/skills/formal-verify/scripts/surface.py +27 -0
  33. package/skills/formal-verify/scripts/sync.py +401 -0
  34. package/skills/formal-verify/scripts/tlc-matrix.sh +3 -1
  35. package/skills/formal-verify/scripts/tlc.py +501 -117
  36. package/skills/formal-verify/scripts/tlc_report.py +516 -0
  37. package/skills/formal-verify/scripts/tlc_trace.py +167 -0
  38. package/skills/setup/SKILL.md +1 -1
  39. package/skills/formal-verify/scripts/lean-mutations.lean +0 -95
  40. package/skills/formal-verify/scripts/lean-statements.py +0 -161
  41. package/skills/formal-verify/scripts/lean-tools.sh +0 -24
  42. package/skills/formal-verify/scripts/tlc-tools.sh +0 -47
  43. package/skills/formal-verify/scripts/tlc-trace.py +0 -64
@@ -0,0 +1,516 @@
1
+ # Copyright (c) 2026 Michael Denyer
2
+ # SPDX-License-Identifier: GPL-3.0-only
3
+ """Render TLC error and reach-witness traces as Mermaid, inline SVG, and self-contained HTML."""
4
+ from __future__ import annotations
5
+
6
+ import dataclasses
7
+ import html
8
+ import json
9
+ import os
10
+ import re
11
+ import sys
12
+ import time
13
+ from pathlib import Path
14
+
15
+ sys.dont_write_bytecode = True
16
+ import runner
17
+ import tlc_trace
18
+
19
+
20
+ def _esc(text: str) -> str:
21
+ return html.escape(text, quote=True)
22
+
23
+
24
+ def _flatten(text: str) -> str:
25
+ return " ".join(text.split())
26
+
27
+
28
+ def _truncate(text: str, limit: int) -> str:
29
+ return text if len(text) <= limit else text[: limit - 3] + "..."
30
+
31
+
32
+ # Characters that Mermaid reads as syntax or, like U+FEFF, as whitespace, and the space or bracket inside words that its stateDiagram lexer
33
+ # reads anywhere on a line, ignoring case: "direction LR" and the like, and "[[fork]]", "[[join]]" or "[[choice]]".
34
+ _MERMAID_SPECIAL = re.compile(r'[&#"<>:;{}\ufeff]|(?i:(?<=direction) (?=tb|bt|rl|lr)|\[(?=\[(?:fork|join|choice)\]\]))')
35
+
36
+
37
+ def _sanitize_mermaid(text: str) -> str:
38
+ # Mermaid renders an entity code such as #123; as the character it names, so the label keeps the TLA+ text.
39
+ cleaned = _MERMAID_SPECIAL.sub(lambda m: f"#{ord(m.group())};", _flatten(text))
40
+ while "%%" in cleaned:
41
+ cleaned = cleaned.replace("%%", "% %")
42
+ return cleaned
43
+
44
+
45
+ def _mermaid_step_label(step: tlc_trace.Step) -> str:
46
+ action = _sanitize_mermaid(step.action or "Step")
47
+ if not step.changed:
48
+ return f"State {step.number}: {action} | unchanged"
49
+ parts = [f"{_sanitize_mermaid(d.name)}={_sanitize_mermaid(_truncate(_flatten(d.new), 32))}" for d in step.changed[:2]]
50
+ extra = len(step.changed) - 2
51
+ if extra > 0:
52
+ parts.append(f"(+{extra} more)")
53
+ return f"State {step.number}: {action} | {', '.join(parts)}"
54
+
55
+
56
+ def to_mermaid(trace: tlc_trace.Trace, *, kind: str = "fail", title: str = "") -> str:
57
+ """Render a TLC trace as a Mermaid stateDiagram-v2 string."""
58
+ lines = ["stateDiagram-v2"]
59
+ if title.strip():
60
+ lines.append(f"%% {_sanitize_mermaid(title)}")
61
+ if not trace.steps:
62
+ return "\n".join(lines) + "\n"
63
+ first_by_num: dict[int, int] = {}
64
+ for idx, step in enumerate(trace.steps):
65
+ first_by_num.setdefault(step.number, idx + 1)
66
+ lines.append(f'state "{_mermaid_step_label(step)}" as S{idx + 1}')
67
+ lines.append("[*] --> S1")
68
+ for idx, step in enumerate(trace.steps[1:], start=1):
69
+ action = _sanitize_mermaid(step.action)
70
+ suffix = f" : {action}" if action else ""
71
+ lines.append(f"S{idx} --> S{idx + 1}{suffix}")
72
+ last_node = f"S{len(trace.steps)}"
73
+ target_num = first_by_num.get(trace.lasso.target) if trace.lasso is not None else None
74
+ if trace.lasso is not None:
75
+ lasso_action = _sanitize_mermaid(trace.lasso.action)
76
+ lasso_label = f"Back to state {trace.lasso.target}"
77
+ if lasso_action:
78
+ lasso_label += f" - {lasso_action}"
79
+ if target_num is not None:
80
+ lines.append(f"{last_node} --> S{target_num} : {lasso_label}")
81
+ else:
82
+ lines.append(f"note right of {last_node} : {lasso_label}")
83
+ lines.extend([
84
+ "classDef fail fill:#fef2f2,stroke:#dc2626,color:#991b1b,stroke-width:2px",
85
+ "classDef reach fill:#f0fdf4,stroke:#16a34a,color:#166534,stroke-width:2px",
86
+ "classDef lasso fill:#fffbeb,stroke:#d97706,color:#92400e,stroke-dasharray:5 3",
87
+ ])
88
+ terminal_class = "reach" if kind == "witness" else "fail"
89
+ lines.append(f"class {last_node} {terminal_class}")
90
+ if target_num is not None:
91
+ lines.append(f"class S{target_num} lasso")
92
+ return "\n".join(lines) + "\n"
93
+
94
+
95
+ def _step_badge(idx: int, step: tlc_trace.Step) -> str:
96
+ if idx == 0:
97
+ return "initial"
98
+ if step.changed:
99
+ return f"{len(step.changed)} changed"
100
+ return "unchanged"
101
+
102
+
103
+ def _svg_node(idx: int, step: tlc_trace.Step, y: int, trace_id: str, classes: list[str]) -> str:
104
+ node_x, node_w, node_h = 16, 248, 68
105
+ action = _esc(_truncate(_flatten(step.action or "Step"), 30))
106
+ badge = _esc(_step_badge(idx, step))
107
+ cls_str = _esc(" ".join(classes))
108
+ tid = _esc(trace_id)
109
+ return "\n".join([
110
+ f' <g class="{cls_str}" data-trace-id="{tid}" data-step-index="{idx}" data-step-number="{step.number}" role="button" tabindex="0">',
111
+ f' <rect x="{node_x}" y="{y}" width="{node_w}" height="{node_h}" rx="8" ry="8" class="trace-box" />',
112
+ f' <text x="{node_x + 12}" y="{y + 22}" class="trace-title">State {step.number}</text>',
113
+ f' <text x="{node_x + node_w - 12}" y="{y + 22}" text-anchor="end" class="trace-badge">{badge}</text>',
114
+ f' <text x="{node_x + 12}" y="{y + 46}" class="trace-action">{action}</text>',
115
+ " </g>",
116
+ ])
117
+
118
+
119
+ def _svg_lasso(last_y: int, target_y: int, lasso: tlc_trace.Lasso, safe_id: str) -> str:
120
+ node_right, node_h = 16 + 248, 68
121
+ y1 = last_y + node_h // 2 + (8 if last_y == target_y else 0)
122
+ y2 = target_y + node_h // 2 - (8 if last_y == target_y else 0)
123
+ ctrl_x = node_right + 56
124
+ label_x = node_right + 44
125
+ label_y = (y1 + y2) // 2
126
+ action = _truncate(_flatten(lasso.action), 22) if lasso.action else ""
127
+ parts = [
128
+ (
129
+ f' <path d="M {node_right} {y1} C {ctrl_x} {y1}, {ctrl_x} {y2}, {node_right + 4} {y2}" '
130
+ f'fill="none" stroke="#dc2626" stroke-width="2" stroke-dasharray="6 4" '
131
+ f'marker-end="url(#arrow-lasso-{safe_id})" class="trace-lasso-path" />'
132
+ ),
133
+ f' <text x="{label_x}" y="{label_y - 4}" class="trace-lasso-label">Back to state {lasso.target}</text>',
134
+ ]
135
+ if action:
136
+ parts.append(f' <text x="{label_x}" y="{label_y + 12}" class="trace-lasso-action">{_esc(action)}</text>')
137
+ return "\n".join(parts)
138
+
139
+
140
+ def render_svg(trace: tlc_trace.Trace, *, trace_id: str, kind: str = "fail") -> str:
141
+ """Render a vertical interactive HTML5 SVG state chain for a TLC trace (without xmlns)."""
142
+ steps = trace.steps
143
+ safe_id = re.sub(r"[^a-zA-Z0-9_-]", "-", trace_id) or "trace"
144
+ node_x, node_w, node_h, gap, pad_y = 16, 248, 68, 28, 16
145
+ index_by_num: dict[int, int] = {}
146
+ for idx, step in enumerate(steps):
147
+ index_by_num.setdefault(step.number, idx)
148
+ lasso_idx = index_by_num.get(trace.lasso.target) if trace.lasso else None
149
+ width = node_x + node_w + (176 if lasso_idx is not None else 16)
150
+ height = pad_y * 2 + max(1, len(steps)) * node_h + max(0, len(steps) - 1) * gap
151
+ parts = [
152
+ (
153
+ f'<svg class="trace-svg" viewBox="0 0 {width} {height}" width="{width}" height="{height}" '
154
+ f'role="img" aria-label="{_esc(f"Trace {trace_id} with {len(steps)} states")}">'
155
+ ),
156
+ " <defs>",
157
+ f' <marker id="arrow-{safe_id}" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto">',
158
+ ' <path d="M 0 1 L 10 5 L 0 9 z" fill="#64748b" />',
159
+ " </marker>",
160
+ f' <marker id="arrow-lasso-{safe_id}" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto">',
161
+ ' <path d="M 0 1 L 10 5 L 0 9 z" fill="#dc2626" />',
162
+ " </marker>",
163
+ " </defs>",
164
+ ]
165
+ cx = node_x + node_w // 2
166
+ for idx in range(len(steps) - 1):
167
+ y1 = pad_y + idx * (node_h + gap) + node_h
168
+ y2 = y1 + gap - 4
169
+ parts.append(f' <line x1="{cx}" y1="{y1}" x2="{cx}" y2="{y2}" stroke="#64748b" stroke-width="2" marker-end="url(#arrow-{safe_id})" />')
170
+ for idx, step in enumerate(steps):
171
+ y = pad_y + idx * (node_h + gap)
172
+ classes = ["trace-node"]
173
+ if idx == len(steps) - 1:
174
+ classes.append("trace-node-reach" if kind == "witness" else "trace-node-fail")
175
+ classes.append("is-selected")
176
+ if lasso_idx == idx:
177
+ classes.append("trace-node-lasso")
178
+ parts.append(_svg_node(idx, step, y, trace_id, classes))
179
+ if lasso_idx is not None and trace.lasso is not None:
180
+ last_y = pad_y + (len(steps) - 1) * (node_h + gap)
181
+ target_y = pad_y + lasso_idx * (node_h + gap)
182
+ parts.append(_svg_lasso(last_y, target_y, trace.lasso, safe_id))
183
+ parts.append("</svg>")
184
+ return "\n".join(parts)
185
+
186
+
187
+ _STYLE = """
188
+ :root { color-scheme: light; --bg: #f8fafc; --card: #ffffff; --border: #cbd5e1; --text: #0f172a; --muted: #475569; --pass: #15803d; --pass-bg: #dcfce7; --fail: #b91c1c; --fail-bg: #fee2e2; --warn: #b45309; --warn-bg: #fef3c7; --accent: #2563eb; }
189
+ * { box-sizing: border-box; }
190
+ body { margin: 0; padding: 24px; font: 14px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: var(--bg); color: var(--text); }
191
+ .page { max-width: 1280px; margin: 0 auto; display: grid; gap: 20px; }
192
+ .card { background: var(--card); border: 1px solid var(--border); border-radius: 10px; padding: 18px 20px; }
193
+ .header-top { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; justify-content: space-between; }
194
+ .meta { display: flex; flex-wrap: wrap; gap: 16px; color: var(--muted); font-size: 13px; margin-top: 8px; }
195
+ .badge { display: inline-block; padding: 2px 10px; border-radius: 999px; font-weight: 600; font-size: 12px; text-transform: uppercase; }
196
+ .badge-pass, .badge-witness { background: var(--pass-bg); color: var(--pass); }
197
+ .badge-fail, .badge-missing, .badge-unreached, .badge-incomplete, .badge-no-run, .badge-malformed { background: var(--fail-bg); color: var(--fail); }
198
+ table { width: 100%; border-collapse: collapse; font-size: 13px; }
199
+ th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--border); vertical-align: top; }
200
+ th { font-weight: 600; color: var(--muted); background: #f1f5f9; }
201
+ pre, code { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12px; }
202
+ pre { margin: 0; white-space: pre-wrap; word-break: break-word; }
203
+ .trace-grid { display: grid; grid-template-columns: minmax(280px, auto) 1fr; gap: 20px; align-items: start; margin-top: 12px; }
204
+ @media (max-width: 860px) { .trace-grid { grid-template-columns: 1fr; } }
205
+ .trace-nav { display: flex; align-items: center; gap: 10px; margin-top: 8px; }
206
+ button { cursor: pointer; padding: 5px 12px; border: 1px solid var(--border); border-radius: 6px; background: #fff; color: var(--text); font: inherit; font-size: 13px; }
207
+ button:hover { border-color: var(--accent); color: var(--accent); }
208
+ .trace-svg { max-width: 100%; height: auto; display: block; }
209
+ .trace-node { cursor: pointer; }
210
+ .trace-box { fill: #fff; stroke: #94a3b8; stroke-width: 1.5; }
211
+ .trace-node-fail .trace-box { fill: #fef2f2; stroke: #dc2626; }
212
+ .trace-node-reach .trace-box { fill: #f0fdf4; stroke: #16a34a; }
213
+ .trace-node-lasso .trace-box { stroke-dasharray: 5 3; }
214
+ .trace-node.is-selected .trace-box { stroke: var(--accent); stroke-width: 3; }
215
+ .trace-title { font: 600 13px sans-serif; fill: #0f172a; }
216
+ .trace-badge { font: 600 11px sans-serif; fill: #475569; }
217
+ .trace-action { font: 12px ui-monospace, monospace; fill: #334155; }
218
+ .trace-lasso-label { font: 600 11px sans-serif; fill: #b91c1c; }
219
+ .trace-lasso-action { font: 11px ui-monospace, monospace; fill: #7f1d1d; }
220
+ .lasso-banner { background: var(--warn-bg); color: var(--warn); padding: 6px 10px; border-radius: 6px; font-size: 13px; margin: 8px 0; }
221
+ .mermaid-details { margin-top: 14px; border-top: 1px solid var(--border); padding-top: 10px; }
222
+ .mermaid-actions { display: flex; align-items: center; gap: 10px; margin: 8px 0; }
223
+ .copy-status { color: var(--pass); font-size: 12px; font-weight: 600; }
224
+ .empty-note { color: var(--muted); font-style: italic; }
225
+ """.strip()
226
+
227
+ _SCRIPT = """
228
+ (() => {
229
+ const stateByTrace = new Map();
230
+ function renderStep(traceIdx, stepIdx) {
231
+ const data = stateByTrace.get(traceIdx);
232
+ if (!data || !data.steps.length) return;
233
+ const clamped = Math.max(0, Math.min(stepIdx, data.steps.length - 1));
234
+ data.current = clamped;
235
+ const step = data.steps[clamped];
236
+ const counter = document.getElementById("step-counter-" + traceIdx);
237
+ if (counter) counter.textContent = "Step " + (clamped + 1) + " / " + data.steps.length;
238
+ const header = document.getElementById("step-header-" + traceIdx);
239
+ if (header) header.textContent = "State " + step.number + " — " + (step.action || "Step");
240
+ document.querySelectorAll('.trace-node[data-trace-id="trace-' + traceIdx + '"]').forEach((node) => {
241
+ node.classList.toggle("is-selected", Number(node.dataset.stepIndex) === clamped);
242
+ });
243
+ const diffBody = document.getElementById("diff-body-" + traceIdx);
244
+ if (diffBody) {
245
+ diffBody.textContent = "";
246
+ if (!step.changed.length) {
247
+ const tr = document.createElement("tr");
248
+ const td = document.createElement("td");
249
+ td.colSpan = 3;
250
+ td.className = "empty-note";
251
+ td.textContent = "No variable changes in this step.";
252
+ tr.appendChild(td);
253
+ diffBody.appendChild(tr);
254
+ } else {
255
+ for (const item of step.changed) {
256
+ const tr = document.createElement("tr");
257
+ for (const val of [item.name, item.old === null ? "(initial)" : item.old, item.new]) {
258
+ const td = document.createElement("td");
259
+ const pre = document.createElement("pre");
260
+ pre.textContent = val;
261
+ td.appendChild(pre);
262
+ tr.appendChild(td);
263
+ }
264
+ diffBody.appendChild(tr);
265
+ }
266
+ }
267
+ }
268
+ const snapSummary = document.getElementById("snapshot-summary-" + traceIdx);
269
+ if (snapSummary) snapSummary.textContent = "Full State Snapshot (" + step.values.length + " variables)";
270
+ const snapBody = document.getElementById("snapshot-body-" + traceIdx);
271
+ if (snapBody) {
272
+ snapBody.textContent = "";
273
+ for (const pair of step.values) {
274
+ const tr = document.createElement("tr");
275
+ for (const val of pair) {
276
+ const td = document.createElement("td");
277
+ const pre = document.createElement("pre");
278
+ pre.textContent = val;
279
+ td.appendChild(pre);
280
+ tr.appendChild(td);
281
+ }
282
+ snapBody.appendChild(tr);
283
+ }
284
+ }
285
+ }
286
+ document.querySelectorAll('script[type="application/json"][id^="trace-data-"]').forEach((el) => {
287
+ const idx = el.id.slice("trace-data-".length);
288
+ const parsed = JSON.parse(el.textContent);
289
+ stateByTrace.set(idx, { steps: parsed.steps || [], current: Math.max(0, (parsed.steps || []).length - 1) });
290
+ });
291
+ document.querySelectorAll(".trace-node[data-trace-id]").forEach((node) => {
292
+ const select = () => renderStep(node.dataset.traceId.replace(/^trace-/, ""), Number(node.dataset.stepIndex));
293
+ node.addEventListener("click", select);
294
+ node.addEventListener("keydown", (ev) => {
295
+ if (["Enter", "NumpadEnter", "Space"].includes(ev.code)) { ev.preventDefault(); select(); }
296
+ });
297
+ });
298
+ document.querySelectorAll("button[data-action][data-trace-id]").forEach((btn) => {
299
+ btn.addEventListener("click", () => {
300
+ const idx = btn.dataset.traceId.replace(/^trace-/, "");
301
+ const data = stateByTrace.get(idx);
302
+ if (!data) return;
303
+ renderStep(idx, data.current + (btn.dataset.action === "prev" ? -1 : 1));
304
+ });
305
+ });
306
+ document.querySelectorAll("button.copy-mermaid").forEach((btn) => {
307
+ btn.addEventListener("click", async () => {
308
+ const code = document.getElementById(btn.dataset.copyTarget);
309
+ const status = btn.parentElement && btn.parentElement.querySelector(".copy-status");
310
+ if (!code) return;
311
+ const text = code.textContent || "";
312
+ let copied = false;
313
+ if (navigator.clipboard && navigator.clipboard.writeText) {
314
+ try {
315
+ await navigator.clipboard.writeText(text);
316
+ copied = true;
317
+ } catch {
318
+ copied = false;
319
+ }
320
+ }
321
+ if (!copied) {
322
+ const ta = document.createElement("textarea");
323
+ try {
324
+ ta.value = text;
325
+ document.body.appendChild(ta);
326
+ ta.select();
327
+ copied = Boolean(document.execCommand && document.execCommand("copy"));
328
+ } catch {
329
+ copied = false;
330
+ } finally {
331
+ ta.remove();
332
+ }
333
+ }
334
+ if (copied) {
335
+ if (status) { status.textContent = "Copied!"; setTimeout(() => { status.textContent = ""; }, 1500); }
336
+ } else if (status) {
337
+ status.textContent = "Copy failed";
338
+ }
339
+ });
340
+ });
341
+ })();
342
+ """.strip()
343
+
344
+
345
+ def _safe_json(payload: object) -> str:
346
+ raw = json.dumps(payload, ensure_ascii=False)
347
+ return (
348
+ raw.replace("&", "\\u0026")
349
+ .replace("<", "\\u003c")
350
+ .replace(">", "\\u003e")
351
+ .replace("\u2028", "\\u2028")
352
+ .replace("\u2029", "\\u2029")
353
+ )
354
+
355
+
356
+ def _result_type(result: object) -> str:
357
+ if result.outcome.value == "malformed":
358
+ return "error"
359
+ return "reach" if result.operator else "run"
360
+
361
+
362
+ def _result_label(result: object) -> str:
363
+ if result.operator:
364
+ return f"reach {result.operator} {result.label}".strip()
365
+ return result.label or "-"
366
+
367
+
368
+ def _table_row(idx: int, result: object) -> str:
369
+ outcome_val = result.outcome.value
370
+ badge_cls = f"badge-{outcome_val.replace(' ', '-')}"
371
+ checks = ", ".join(result.checks) if result.checks else "-"
372
+ parts = []
373
+ if result.trace is not None and bool(result.trace.steps):
374
+ parts.append(f'<a href="#trace-{idx}">View trace ({len(result.trace.steps)})</a>')
375
+ if result.lines:
376
+ joined = _esc("\n".join(result.lines))
377
+ parts.append(f"<details><summary>Output ({len(result.lines)} lines)</summary><pre>{joined}</pre></details>")
378
+ ref = " ".join(parts) or "-"
379
+ cells = [
380
+ _esc(_result_type(result)),
381
+ _esc(result.name or "-"),
382
+ _esc(_result_label(result)),
383
+ f"<code>{_esc(result.constants or '-')}</code>",
384
+ _esc(checks),
385
+ f'<span class="badge {badge_cls}">{_esc(outcome_val.upper())}</span>',
386
+ _esc(result.detail or "-"),
387
+ f"{result.duration_s:.2f}s",
388
+ ref,
389
+ ]
390
+ return "<tr>" + "".join(f"<td>{cell}</td>" for cell in cells) + "</tr>"
391
+
392
+
393
+ def _diff_rows(step: tlc_trace.Step) -> str:
394
+ if not step.changed:
395
+ return '<tr><td colspan="3" class="empty-note">No variable changes in this step.</td></tr>'
396
+ rows = []
397
+ for diff in step.changed:
398
+ before = "(initial)" if diff.old is None else diff.old
399
+ rows.append(f"<tr><td><pre>{_esc(diff.name)}</pre></td><td><pre>{_esc(before)}</pre></td><td><pre>{_esc(diff.new)}</pre></td></tr>")
400
+ return "".join(rows)
401
+
402
+
403
+ def _snapshot_rows(step: tlc_trace.Step) -> str:
404
+ return "".join(f"<tr><td><pre>{_esc(name)}</pre></td><td><pre>{_esc(val)}</pre></td></tr>" for name, val in step.values)
405
+
406
+
407
+ def _trace_card(idx: int, result: object) -> str:
408
+ trace = result.trace
409
+ kind = "witness" if result.outcome.value == "witness" else "fail"
410
+ title = f"{result.name} {_result_label(result)}".strip()
411
+ last_idx = len(trace.steps) - 1
412
+ last_step = trace.steps[last_idx]
413
+ badge_cls = f"badge-{result.outcome.value.replace(' ', '-')}"
414
+ lasso_html = ""
415
+ if trace.lasso is not None:
416
+ lasso_text = f"Loop back to state {trace.lasso.target}" + (f" ({trace.lasso.action})" if trace.lasso.action else "")
417
+ lasso_html = f'<div class="lasso-banner">{_esc(lasso_text)}</div>'
418
+ mermaid_text = to_mermaid(trace, kind=kind, title=title)
419
+ svg_html = render_svg(trace, trace_id=f"trace-{idx}", kind=kind)
420
+ return "\n".join([
421
+ f'<article class="card trace-card" id="trace-{idx}">',
422
+ ' <div class="header-top">',
423
+ f' <h3>{_esc(title)}</h3>',
424
+ f' <span class="badge {badge_cls}">{_esc(result.outcome.value.upper())}</span>',
425
+ " </div>",
426
+ f' <p>{_esc(result.detail)}</p>',
427
+ ' <div class="trace-grid">',
428
+ ' <div class="trace-left">',
429
+ svg_html,
430
+ ' <div class="trace-nav">',
431
+ f' <button type="button" data-action="prev" data-trace-id="trace-{idx}">Prev</button>',
432
+ f' <span id="step-counter-{idx}">Step {last_idx + 1} / {len(trace.steps)}</span>',
433
+ f' <button type="button" data-action="next" data-trace-id="trace-{idx}">Next</button>',
434
+ " </div>",
435
+ " </div>",
436
+ f' <div class="trace-right" id="trace-panel-{idx}">',
437
+ f' <h4 id="step-header-{idx}">State {last_step.number} — {_esc(last_step.action or "Step")}</h4>',
438
+ lasso_html,
439
+ " <table><thead><tr><th>Variable</th><th>Before</th><th>After</th></tr></thead>",
440
+ f' <tbody id="diff-body-{idx}">{_diff_rows(last_step)}</tbody></table>',
441
+ f' <details style="margin-top:12px"><summary id="snapshot-summary-{idx}">Full State Snapshot ({len(last_step.values)} variables)</summary>',
442
+ ' <table><thead><tr><th>Variable</th><th>Value</th></tr></thead>',
443
+ f' <tbody id="snapshot-body-{idx}">{_snapshot_rows(last_step)}</tbody></table>',
444
+ " </details>",
445
+ " </div>",
446
+ " </div>",
447
+ ' <details class="mermaid-details">',
448
+ " <summary>Mermaid stateDiagram-v2</summary>",
449
+ ' <div class="mermaid-actions">',
450
+ f' <button type="button" class="copy-mermaid" data-copy-target="mermaid-{idx}">Copy Mermaid</button>',
451
+ ' <span class="copy-status" aria-live="polite"></span>',
452
+ " </div>",
453
+ f' <pre><code id="mermaid-{idx}">{_esc(mermaid_text)}</code></pre>',
454
+ " </details>",
455
+ f' <script type="application/json" id="trace-data-{idx}">{_safe_json(dataclasses.asdict(trace))}</script>',
456
+ "</article>",
457
+ ])
458
+
459
+
460
+ def render_html(matrix_name: str, results: list, summary: str, *, only: str = "", generated_at: str | None = None) -> str:
461
+ """Render a complete, self-contained HTML5 report for a TLC matrix run."""
462
+ # A file name argument that is not UTF-8 arrives with lone surrogates, which the UTF-8 page cannot hold.
463
+ matrix_name = os.fsencode(matrix_name).decode("utf-8", "replace")
464
+ timestamp = generated_at or time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
465
+ has_failure = (not results) or any(r.outcome.value not in ("pass", "witness") for r in results)
466
+ overall = "FAIL" if has_failure else "PASS"
467
+ overall_cls = "badge-fail" if has_failure else "badge-pass"
468
+ total_s = sum(r.duration_s for r in results)
469
+ filter_html = f"<span>Filter: <code>{_esc(only)}</code></span>" if only else ""
470
+ rows_html = "\n".join(_table_row(idx, r) for idx, r in enumerate(results))
471
+ trace_cards = [_trace_card(idx, r) for idx, r in enumerate(results) if r.trace is not None and bool(r.trace.steps)]
472
+ traces_html = "\n".join(trace_cards) if trace_cards else '<p class="empty-note">There are no counter-example or witness traces for this run.</p>'
473
+ return "\n".join([
474
+ "<!DOCTYPE html>",
475
+ '<html lang="en">',
476
+ "<head>",
477
+ ' <meta charset="utf-8">',
478
+ ' <meta name="viewport" content="width=device-width, initial-scale=1">',
479
+ f" <title>TLC Report — {_esc(matrix_name)}</title>",
480
+ f" <style>{_STYLE}</style>",
481
+ "</head>",
482
+ "<body>",
483
+ ' <main class="page">',
484
+ ' <section class="card">',
485
+ ' <div class="header-top">',
486
+ f" <h1>TLC Matrix Report: {_esc(matrix_name)}</h1>",
487
+ f' <span class="badge {overall_cls}">{overall}</span>',
488
+ " </div>",
489
+ f" <p>{_esc(summary)}</p>",
490
+ ' <div class="meta">',
491
+ f" <span>Total duration: <strong>{total_s:.2f}s</strong></span>",
492
+ f" <span>Generated (UTC): <code>{_esc(timestamp)}</code></span>",
493
+ f" {filter_html}",
494
+ " </div>",
495
+ " </section>",
496
+ ' <section class="card">',
497
+ " <h2>Matrix Runs</h2>",
498
+ " <table><thead><tr><th>Type</th><th>Spec</th><th>Label</th><th>Constants</th><th>Checks</th><th>Outcome</th><th>States / Detail</th><th>Duration</th><th>Trace / Output</th></tr></thead>",
499
+ f" <tbody>{rows_html}</tbody></table>",
500
+ " </section>",
501
+ ' <section class="card">',
502
+ " <h2>Interactive Trace Explorer</h2>",
503
+ f" {traces_html}",
504
+ " </section>",
505
+ " </main>",
506
+ f" <script>{_SCRIPT}</script>",
507
+ "</body>",
508
+ "</html>",
509
+ ])
510
+
511
+
512
+ def write_html(path: Path, matrix_name: str, results: list, summary: str, *, only: str = "") -> Path:
513
+ """Render the HTML report and write it atomically to path."""
514
+ target = Path(path)
515
+ runner.atomic_write(target, render_html(matrix_name, results, summary, only=only))
516
+ return target