lemmascript 0.6.4 → 0.6.5

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,377 @@
1
+ /**
2
+ * `lsc runs` — read the run log and report what verification caught.
3
+ *
4
+ * A catch is a failure that a later run fixed. Each run gives each Dafny
5
+ * member a verdict; a streak of failures ending in a pass is one catch, a
6
+ * streak ending with the member gone is dropped, and a streak still failing
7
+ * at the end of the log is open. Members are then merged per TypeScript
8
+ * function (lsc's generated helpers left out), and each catch is classified
9
+ * by what changed between its first failing run and its passing run. A
10
+ * source fix also gets the diff of its two `.ts` snapshots and a hint at
11
+ * whether the code, the spec or only the proof changed. `runsReport` gathers
12
+ * all of this as data (what `--json` prints) and `formatText` summarises it;
13
+ * `runRuns` is the command `lsc.ts` calls.
14
+ */
15
+ import { execFileSync } from "child_process";
16
+ import { existsSync } from "fs";
17
+ import path from "path";
18
+ import { DAFNY_HELPER_NAMES, ENSURES_LEMMA_SUFFIX } from "./dafny-emit.js";
19
+ import { loadConfigOptions } from "./config.js";
20
+ import { readRecords, resolveLogDir } from "./run-log.js";
21
+ /**
22
+ * Whether each `//@` keyword the extractor parses states what a function
23
+ * promises (spec) or only helps the proof along. Typed by the extractor's own
24
+ * keyword list, so adding or removing a keyword there fails the typecheck
25
+ * here until it is classified. Other `//@` lines (`assert`, `havoc`, …) count as proof.
26
+ */
27
+ const ANNOTATION_ROLES = {
28
+ requires: "spec",
29
+ ensures: "spec",
30
+ contract: "spec",
31
+ invariant: "proof",
32
+ decreases: "proof",
33
+ done_with: "proof",
34
+ type: "proof",
35
+ };
36
+ /**
37
+ * The shape of the hashes the run log writes. Hashes come from runs.jsonl,
38
+ * which anyone can edit, so only this shape may become a path or a git argument.
39
+ */
40
+ const SNAPSHOT_HASH = /^[0-9a-f]{12}$/;
41
+ /**
42
+ * A member missing from a partial run (filtered, or one Dafny never reached)
43
+ * was not checked; missing from a complete run, it is gone.
44
+ */
45
+ function verdict(run, member) {
46
+ if (run.failed.includes(member))
47
+ return "fail";
48
+ if (run.passed.includes(member))
49
+ return "pass";
50
+ return run.partial ? "unchecked" : "gone";
51
+ }
52
+ /** Every member's failure streaks, file by file, in log order. */
53
+ export function memberResults(records) {
54
+ const byFile = new Map();
55
+ for (const r of records) {
56
+ const runs = byFile.get(r.file);
57
+ if (runs === undefined)
58
+ byFile.set(r.file, [r]);
59
+ else
60
+ runs.push(r);
61
+ }
62
+ const results = [];
63
+ for (const [file, runs] of byFile) {
64
+ const members = new Set(runs.flatMap(r => [...r.failed, ...r.passed]));
65
+ for (const member of members) {
66
+ let failedRun = null;
67
+ for (const run of runs) {
68
+ const v = verdict(run, member);
69
+ if (v === "fail") {
70
+ if (failedRun === null)
71
+ failedRun = run;
72
+ continue;
73
+ }
74
+ if (failedRun === null || v === "unchecked")
75
+ continue;
76
+ results.push(v === "pass"
77
+ ? { file, member, status: "caught", failedRun, fixedRun: run }
78
+ : { file, member, status: "dropped", failedRun, droppedRun: run });
79
+ failedRun = null;
80
+ }
81
+ if (failedRun !== null)
82
+ results.push({ file, member, status: "open", failedRun });
83
+ }
84
+ }
85
+ return results;
86
+ }
87
+ /**
88
+ * The TypeScript function a Dafny member verifies: `foo_ensures` belongs to
89
+ * `foo`, and any other member is its own function. Null for lsc's generated
90
+ * helpers, which are not the user's code.
91
+ */
92
+ export function functionOf(member) {
93
+ if (DAFNY_HELPER_NAMES.has(member))
94
+ return null;
95
+ return member.endsWith(ENSURES_LEMMA_SUFFIX) ? member.slice(0, -ENSURES_LEMMA_SUFFIX.length) : member;
96
+ }
97
+ /** Order ISO timestamps oldest first. */
98
+ function byTime(a, b) {
99
+ return a < b ? -1 : a > b ? 1 : 0;
100
+ }
101
+ /** When a member's failure ended (the fixing or dropping run's time), or null while it is still open. */
102
+ function endOf(r) {
103
+ return (r.fixedRun ?? r.droppedRun)?.ts ?? null;
104
+ }
105
+ /** Whether `a`'s failure ended after `b`'s: open is latest, and a fix beats a drop in the same run. */
106
+ function endsLater(a, b) {
107
+ const ea = endOf(a);
108
+ const eb = endOf(b);
109
+ if (eb === null)
110
+ return false;
111
+ if (ea === null)
112
+ return true;
113
+ if (ea !== eb)
114
+ return ea > eb;
115
+ return a.status === "caught" && b.status !== "caught";
116
+ }
117
+ /** One function's overlapping member failures as one result, ending the way `last` (the latest to end) did. */
118
+ function mergeSpan(fn, span, last) {
119
+ return {
120
+ file: last.file, function: fn, members: [...new Set(span.map(r => r.member))].sort(),
121
+ status: last.status, failedRun: span[0].failedRun, fixedRun: last.fixedRun, droppedRun: last.droppedRun,
122
+ };
123
+ }
124
+ /**
125
+ * Merge member results into one per TypeScript function. A function is failing
126
+ * while any of its members is, so member failures that overlap (or where one
127
+ * starts in the run that ends another) are one result: it starts at the earliest
128
+ * failure and ends the way the last of them ended (still open, fixed or dropped).
129
+ * Generated helpers are left out.
130
+ */
131
+ export function groupByFunction(results) {
132
+ const byFunction = new Map();
133
+ for (const r of results) {
134
+ const fn = functionOf(r.member);
135
+ if (fn === null)
136
+ continue;
137
+ const key = `${r.file}\0${fn}`;
138
+ const group = byFunction.get(key);
139
+ if (group === undefined)
140
+ byFunction.set(key, { fn, results: [r] });
141
+ else
142
+ group.results.push(r);
143
+ }
144
+ const merged = [];
145
+ for (const { fn, results: group } of byFunction.values()) {
146
+ group.sort((a, b) => byTime(a.failedRun.ts, b.failedRun.ts));
147
+ let span = [];
148
+ let last = null;
149
+ for (const r of group) {
150
+ // A failure starting after the span's last one ended means the function passed in between.
151
+ const end = last === null ? null : endOf(last);
152
+ if (last !== null && end !== null && r.failedRun.ts > end) {
153
+ merged.push(mergeSpan(fn, span, last));
154
+ span = [];
155
+ last = null;
156
+ }
157
+ span.push(r);
158
+ if (last === null || endsLater(r, last))
159
+ last = r;
160
+ }
161
+ if (last !== null)
162
+ merged.push(mergeSpan(fn, span, last));
163
+ }
164
+ return merged;
165
+ }
166
+ /** Compare the first failing run with the passing run: source first, then proof. */
167
+ export function classify(failed, fixed) {
168
+ if (failed.tsHash !== fixed.tsHash)
169
+ return "source-fix";
170
+ if (failed.dfyHash !== fixed.dfyHash)
171
+ return "proof";
172
+ return "flaky";
173
+ }
174
+ /** What one changed line of a `.ts` diff touches, or null for blanks and comments. */
175
+ function lineChange(text) {
176
+ const line = text.trim();
177
+ if (line.startsWith("//@"))
178
+ return ANNOTATION_ROLES[line.slice(3).trim().split(/\s/)[0]] === "spec" ? "spec" : "proof";
179
+ if (line === "" || line.startsWith("//") || line.startsWith("/*") || line.startsWith("*"))
180
+ return null;
181
+ return "code";
182
+ }
183
+ /** Hint at what a source fix changed, from the `+`/`-` lines of its unified diff. */
184
+ export function changeHint(diff) {
185
+ const changed = new Set();
186
+ // Only file headers are metadata. Inside a hunk, even a line beginning
187
+ // with "---" is a deletion (for example, `--count;`).
188
+ let inHunk = false;
189
+ for (const line of diff.split("\n")) {
190
+ if (line.startsWith("diff --git "))
191
+ inHunk = false;
192
+ else if (line.startsWith("@@ "))
193
+ inHunk = true;
194
+ else if (inHunk && (line.startsWith("+") || line.startsWith("-"))) {
195
+ const change = lineChange(line.slice(1));
196
+ if (change !== null)
197
+ changed.add(change);
198
+ }
199
+ }
200
+ if (changed.has("code"))
201
+ return changed.has("spec") ? "mixed" : "code";
202
+ return changed.has("spec") ? "spec" : "proof";
203
+ }
204
+ /** A UTC timestamp's date (`2026-10-06`) and time (`14:13`) in `timeZone`, or the local zone when undefined. */
205
+ function localTime(ts, timeZone) {
206
+ const format = new Intl.DateTimeFormat("en-US", {
207
+ timeZone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23",
208
+ });
209
+ const part = Object.fromEntries(format.formatToParts(new Date(ts)).map(p => [p.type, p.value]));
210
+ return { date: `${part.year}-${part.month}-${part.day}`, time: `${part.hour}:${part.minute}` };
211
+ }
212
+ /** `1 run`, `3 runs`. */
213
+ function count(n, noun) {
214
+ return `${n} ${noun}${n === 1 ? "" : "s"}`;
215
+ }
216
+ /** Rows as aligned columns, two spaces apart; a row's last cell is never padded. */
217
+ function columns(rows) {
218
+ const widths = [];
219
+ for (const row of rows) {
220
+ for (let i = 0; i < row.length; i++)
221
+ widths[i] = Math.max(widths[i] ?? 0, row[i].length);
222
+ }
223
+ return rows.map(row => row.map((cell, i) => i < row.length - 1 ? cell.padEnd(widths[i]) : cell).join(" "));
224
+ }
225
+ /**
226
+ * The human summary of a report: the log's span and counts, then one line per
227
+ * catch, open and dropped failure. Times are shown in `timeZone` (the local
228
+ * zone by default), with dates only when the log spans more than one day;
229
+ * open and dropped failures always show the date they first failed.
230
+ */
231
+ export function formatText(report, timeZone) {
232
+ if (report.runs === 0 || report.from === null || report.to === null)
233
+ return `No runs recorded yet in ${report.log}.`;
234
+ const from = localTime(report.from, timeZone);
235
+ const to = localTime(report.to, timeZone);
236
+ const oneDay = from.date === to.date;
237
+ const dated = (ts) => { const t = localTime(ts, timeZone); return `${t.date} ${t.time}`; };
238
+ const when = (ts) => oneDay ? localTime(ts, timeZone).time : dated(ts);
239
+ const c = report.counts;
240
+ const lines = [
241
+ `${count(report.runs, "run")}, ${count(report.files, "file")}, ${from.date} ${from.time} → ${oneDay ? to.time : `${to.date} ${to.time}`}`,
242
+ "",
243
+ `catches: ${c.catches} (source-fix ${c.sourceFix}, proof ${c.proof}, flaky ${c.flaky})`,
244
+ `open: ${c.open} dropped: ${c.dropped}`,
245
+ ];
246
+ const rows = [
247
+ ...report.catches.map(k => [
248
+ k.kind, k.file, k.function, `failed ${when(k.failedAt)}, fixed ${when(k.fixedAt)}`,
249
+ ...(k.evidence?.hint ? [`hint: ${k.evidence.hint}`] : []),
250
+ ]),
251
+ ...report.open.map(o => ["open", o.file, o.function, `failed ${dated(o.failedAt)}`]),
252
+ ...report.dropped.map(d => ["dropped", d.file, d.function, `failed ${dated(d.failedAt)}`]),
253
+ ];
254
+ if (rows.length > 0)
255
+ lines.push("", ...columns(rows));
256
+ return lines.join("\n");
257
+ }
258
+ /**
259
+ * The unified diff between two `.ts` snapshots in `<logDir>/.lemmascript/blobs/`,
260
+ * or null when either is missing, a hash isn't a snapshot hash, or git can't
261
+ * compare them.
262
+ */
263
+ export function snapshotDiff(logDir, fromHash, toHash) {
264
+ if (fromHash === null || toHash === null || !SNAPSHOT_HASH.test(fromHash) || !SNAPSHOT_HASH.test(toHash))
265
+ return null;
266
+ const blobs = path.join(logDir, ".lemmascript", "blobs");
267
+ const from = `${fromHash}.ts`;
268
+ const to = `${toHash}.ts`;
269
+ if (!existsSync(path.join(blobs, from)) || !existsSync(path.join(blobs, to)))
270
+ return null;
271
+ try {
272
+ // Run inside blobs/ so the diff headers name the snapshots, not the machine's paths.
273
+ return execFileSync("git", ["diff", "--no-index", "--no-color", "--no-ext-diff", "--no-textconv", "--text", "--", from, to], { cwd: blobs, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] });
274
+ }
275
+ catch (e) {
276
+ // `git diff --no-index` exits 1 when the files differ; anything else (another
277
+ // exit code, or no status because git was killed or never ran) is a failed comparison.
278
+ const stdout = typeof e?.stdout === "string" ? e.stdout : "";
279
+ return e?.status === 1 && stdout.startsWith("diff --git ") ? stdout : null;
280
+ }
281
+ }
282
+ /** A caught function result as a catch, with diff evidence when the source changed. */
283
+ function toCatch(logDir, r) {
284
+ const fixedRun = r.fixedRun;
285
+ const kind = classify(r.failedRun, fixedRun);
286
+ const result = {
287
+ id: `${r.failedRun.id}:${r.function}`, file: r.file, function: r.function, members: r.members, kind,
288
+ failedAt: r.failedRun.ts, failedRun: r.failedRun.id, fixedAt: fixedRun.ts, fixedRun: fixedRun.id,
289
+ };
290
+ if (kind === "source-fix") {
291
+ const diff = snapshotDiff(logDir, r.failedRun.tsHash, fixedRun.tsHash);
292
+ result.evidence = { hint: diff === null ? null : changeHint(diff), diff };
293
+ }
294
+ return result;
295
+ }
296
+ /** An open or dropped function result, named by run ids. */
297
+ function toUnfixed(r) {
298
+ return {
299
+ file: r.file, function: r.function, members: r.members, failedAt: r.failedRun.ts, failedRun: r.failedRun.id,
300
+ ...(r.droppedRun ? { droppedRun: r.droppedRun.id } : {}),
301
+ };
302
+ }
303
+ /**
304
+ * Read `<logDir>/.lemmascript/runs.jsonl` and report its catches (ordered by
305
+ * fix time) and its open and dropped failures (ordered by failure time).
306
+ */
307
+ export function runsReport(logDir) {
308
+ const records = readRecords(logDir);
309
+ const results = groupByFunction(memberResults(records));
310
+ const catches = results.filter(r => r.status === "caught").map(r => toCatch(logDir, r))
311
+ .sort((a, b) => byTime(a.fixedAt, b.fixedAt));
312
+ const unfixed = (status) => results.filter(r => r.status === status).map(toUnfixed)
313
+ .sort((a, b) => byTime(a.failedAt, b.failedAt));
314
+ const open = unfixed("open");
315
+ const dropped = unfixed("dropped");
316
+ const times = records.map(r => r.ts).sort(byTime);
317
+ return {
318
+ v: 1,
319
+ log: path.join(path.resolve(logDir), ".lemmascript", "runs.jsonl"),
320
+ runs: records.length,
321
+ files: new Set(records.map(r => r.file)).size,
322
+ from: times[0] ?? null,
323
+ to: times[times.length - 1] ?? null,
324
+ counts: {
325
+ catches: catches.length,
326
+ sourceFix: catches.filter(c => c.kind === "source-fix").length,
327
+ proof: catches.filter(c => c.kind === "proof").length,
328
+ flaky: catches.filter(c => c.kind === "flaky").length,
329
+ open: open.length,
330
+ dropped: dropped.length,
331
+ },
332
+ catches, open, dropped,
333
+ };
334
+ }
335
+ /** Whether `git` can be run, which snapshot diffs need. */
336
+ function gitAvailable() {
337
+ try {
338
+ execFileSync("git", ["--version"], { stdio: "ignore" });
339
+ return true;
340
+ }
341
+ catch {
342
+ return false;
343
+ }
344
+ }
345
+ /**
346
+ * `lsc runs [--json] [--config=<path>]`: report the log that `lsc check` and
347
+ * `lsc regen` record to from the current directory. Recording settings don't
348
+ * apply; a log that exists is always read.
349
+ */
350
+ export function runRuns(args) {
351
+ let json = false;
352
+ let configPath;
353
+ for (const arg of args) {
354
+ if (arg === "--json")
355
+ json = true;
356
+ else if (arg.startsWith("--config=")) {
357
+ configPath = arg.slice("--config=".length);
358
+ if (!configPath)
359
+ throw new Error("Invalid --config: expected a path after '='");
360
+ }
361
+ else if (arg.startsWith("-"))
362
+ throw new Error(`Unknown flag: ${arg} (lsc runs takes only --json and --config=<path>)`);
363
+ else
364
+ throw new Error(`lsc runs takes no file (got: ${arg})`);
365
+ }
366
+ // Config and log discovery start at a source file's directory, so use a
367
+ // synthetic path under cwd, as `lsc config` does.
368
+ const probe = path.join(process.cwd(), ".lemmascript-runs-probe.ts");
369
+ const { configFile } = loadConfigOptions(probe, configPath);
370
+ const report = runsReport(resolveLogDir(probe, configFile));
371
+ // Missing evidence looks the same whatever the cause, so say when it is git;
372
+ // stderr keeps `--json` output clean.
373
+ if (report.catches.some(c => c.evidence?.diff === null) && !gitAvailable()) {
374
+ console.error("warning: git is not available, so source fixes have no diff or hint");
375
+ }
376
+ console.log(json ? JSON.stringify(report, null, 2) : formatText(report));
377
+ }
@@ -2710,8 +2710,7 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
2710
2710
  comment: " Generated by lsc from " + (mod.file.split("/").pop() ?? "") + "\n Do not edit — re-run `lsc gen` to regenerate.",
2711
2711
  imports: defBaseImports,
2712
2712
  options: [
2713
- { key: "loom.semantics.termination", value: '"total"' },
2714
- { key: "loom.semantics.choice", value: '"demonic"' },
2713
+ { key: "velvet.semantics.termination", value: '"total"' },
2715
2714
  ],
2716
2715
  decls: [...constDecls, ...defByMethods, ...methods, ...classDecls],
2717
2716
  };