@sublang/spex 5.0.0 → 7.0.0-beta.2

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 (114) hide show
  1. package/README.md +453 -41
  2. package/dist/cli.js +12 -1
  3. package/dist/commands/add.d.ts +1 -1
  4. package/dist/commands/add.js +3 -3
  5. package/dist/commands/auth-target.d.ts +1 -0
  6. package/dist/commands/auth-target.js +4 -2
  7. package/dist/commands/environment.d.ts +15 -21
  8. package/dist/commands/environment.js +43 -57
  9. package/dist/commands/export.js +2 -2
  10. package/dist/commands/home.d.ts +2 -2
  11. package/dist/commands/home.js +3 -3
  12. package/dist/commands/list.js +1 -1
  13. package/dist/commands/login.js +12 -7
  14. package/dist/commands/logout.js +2 -3
  15. package/dist/commands/publish.js +16 -16
  16. package/dist/commands/remove.js +1 -1
  17. package/dist/commands/run.d.ts +1 -1
  18. package/dist/commands/run.js +22 -3
  19. package/dist/commands/search.js +1 -1
  20. package/dist/commands/settle.d.ts +1 -1
  21. package/dist/commands/settle.js +3 -3
  22. package/dist/commands/whoami.js +2 -6
  23. package/dist/guards/approval.d.ts +56 -0
  24. package/dist/guards/approval.js +158 -0
  25. package/dist/guards/checks.d.ts +207 -0
  26. package/dist/guards/checks.js +681 -0
  27. package/dist/guards/commands.d.ts +15 -0
  28. package/dist/guards/commands.js +313 -0
  29. package/dist/guards/copy.d.ts +67 -0
  30. package/dist/guards/copy.js +306 -0
  31. package/dist/guards/declaration.d.ts +45 -0
  32. package/dist/guards/declaration.js +224 -0
  33. package/dist/guards/files.d.ts +137 -0
  34. package/dist/guards/files.js +544 -0
  35. package/dist/guards/harness.d.ts +58 -0
  36. package/dist/guards/harness.js +420 -0
  37. package/dist/guards/items.d.ts +61 -0
  38. package/dist/guards/items.js +161 -0
  39. package/dist/guards/patch.d.ts +55 -0
  40. package/dist/guards/patch.js +258 -0
  41. package/dist/guards/processes.d.ts +49 -0
  42. package/dist/guards/processes.js +233 -0
  43. package/dist/guards/proofs.d.ts +88 -0
  44. package/dist/guards/proofs.js +503 -0
  45. package/dist/guards/records.d.ts +176 -0
  46. package/dist/guards/records.js +513 -0
  47. package/dist/guards/report.d.ts +26 -0
  48. package/dist/guards/report.js +492 -0
  49. package/dist/guards/runner.d.ts +42 -0
  50. package/dist/guards/runner.js +167 -0
  51. package/dist/guards/tla.d.ts +51 -0
  52. package/dist/guards/tla.js +352 -0
  53. package/dist/guards/tlapm.d.ts +81 -0
  54. package/dist/guards/tlapm.js +172 -0
  55. package/dist/guards/tlc.d.ts +191 -0
  56. package/dist/guards/tlc.js +457 -0
  57. package/dist/guards/translation.d.ts +66 -0
  58. package/dist/guards/translation.js +202 -0
  59. package/dist/guards/types.d.ts +185 -0
  60. package/dist/guards/types.js +437 -0
  61. package/dist/guards/verify.d.ts +290 -0
  62. package/dist/guards/verify.js +1191 -0
  63. package/dist/guards/xml.d.ts +18 -0
  64. package/dist/guards/xml.js +105 -0
  65. package/dist/lib/environment/archive.d.ts +16 -3
  66. package/dist/lib/environment/archive.js +39 -8
  67. package/dist/lib/environment/builtins.d.ts +10 -12
  68. package/dist/lib/environment/builtins.js +18 -20
  69. package/dist/lib/environment/exports.d.ts +14 -13
  70. package/dist/lib/environment/exports.js +31 -16
  71. package/dist/lib/environment/format.d.ts +2 -2
  72. package/dist/lib/environment/format.js +3 -3
  73. package/dist/lib/environment/git-source.js +6 -3
  74. package/dist/lib/environment/install.d.ts +14 -16
  75. package/dist/lib/environment/install.js +66 -61
  76. package/dist/lib/environment/lock.d.ts +4 -3
  77. package/dist/lib/environment/lock.js +6 -5
  78. package/dist/lib/environment/marker.js +1 -2
  79. package/dist/lib/environment/own-paths.d.ts +7 -10
  80. package/dist/lib/environment/own-paths.js +10 -13
  81. package/dist/lib/environment/placed-record.d.ts +3 -2
  82. package/dist/lib/environment/placed-record.js +5 -4
  83. package/dist/lib/environment/registries.d.ts +7 -9
  84. package/dist/lib/environment/registries.js +9 -36
  85. package/dist/lib/environment/registry.d.ts +6 -7
  86. package/dist/lib/environment/registry.js +12 -12
  87. package/dist/lib/environment/requests.d.ts +6 -5
  88. package/dist/lib/environment/requests.js +6 -8
  89. package/dist/lib/environment/resolve.d.ts +4 -4
  90. package/dist/lib/environment/resolve.js +3 -4
  91. package/dist/lib/environment/store.d.ts +34 -8
  92. package/dist/lib/environment/store.js +138 -43
  93. package/dist/lib/files.d.ts +72 -12
  94. package/dist/lib/files.js +200 -65
  95. package/dist/lib/git-host.d.ts +52 -258
  96. package/dist/lib/git-host.js +52 -265
  97. package/dist/lib/home-file.d.ts +13 -10
  98. package/dist/lib/home-file.js +28 -18
  99. package/dist/lib/instance.d.ts +1 -1
  100. package/dist/lib/instance.js +1 -1
  101. package/dist/lint.d.ts +22 -0
  102. package/dist/lint.js +36 -0
  103. package/dist/testing/standin-registry.js +1 -1
  104. package/package.json +7 -3
  105. package/scaffold/.file-history.json +14 -7
  106. package/scaffold/i18n/zh/source-pins.json +41 -0
  107. package/scaffold/i18n/zh/specs/decisions/000-spec-structure-format.md +0 -1
  108. package/scaffold/i18n/zh/specs/intents/000-spdx-headers.md +0 -1
  109. package/scaffold/i18n/zh/specs/map.md +0 -1
  110. package/scaffold/i18n/zh/specs/meta.md +18 -35
  111. package/scaffold/i18n/zh/specs/packages/git.md +0 -1
  112. package/scaffold/i18n/zh/specs/packages/licensing.md +0 -1
  113. package/scaffold/specs/meta.md +18 -3
  114. package/scripts/test-exit-guard.mjs +28 -0
@@ -0,0 +1,1191 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
+ /*
4
+ * Guards package (guards-12, guards-17 to guards-25, guards-28,
5
+ * guards-36, guards-38, guards-39, guards-42, guards-50 to guards-57),
6
+ * DR-243, DR-244 and DR-252: what `spex verify` does for one guard. It
7
+ * loads the guard and compares its inputs with the approval record.
8
+ * Without the code, TLC reads each translation alone, evaluates the
9
+ * cases under each, compares the translations and model-checks the
10
+ * first one in name order, at the declared values. Where it found
11
+ * nothing wrong, the proofs are checked, for any values (`proofs.ts`).
12
+ * On a copy of the code, the binding's module causes each permitted
13
+ * case and every step of the model once, and the project's tests run
14
+ * with the probes on, writing their records. TLC walks every sequence
15
+ * of records, the module's and the tests', through the model and says
16
+ * of each record whether it was matched, forbidden, not the model's or
17
+ * not legal. The same is done on a copy with each kept fault. This
18
+ * file settles the result and whether the guard passes. It calls no
19
+ * language model and draws nothing at random. It prints nothing:
20
+ * `report.ts` does. It writes nothing in the project.
21
+ */
22
+ import { execFileSync } from "node:child_process";
23
+ import { copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, writeFileSync } from "node:fs";
24
+ import { join } from "node:path";
25
+ import { fileURLToPath } from "node:url";
26
+ import { changedInput, compareApproval, readApproval } from "./approval.js";
27
+ import { checkCases, checkForm, checkModel, compareTranslations, judgeRecords, prepareKeep, quoted, runFolder, seconds, } from "./checks.js";
28
+ import { makeCopy, makeHome, relativeToCopy, removeCopy, removeFolder } from "./copy.js";
29
+ import { declarationModule } from "./declaration.js";
30
+ import { checkProofs } from "./proofs.js";
31
+ import { NoTranslation, loadGuard, } from "./files.js";
32
+ import { applyPatch } from "./patch.js";
33
+ import { lastWords, runProcess } from "./processes.js";
34
+ import { caseOpenings, copyValues, moduleCaseName, moduleSequence, moduleStepName, newBook, reach, readRecords, runsOf, stepFailure, } from "./records.js";
35
+ import { canon, key, showTla } from "./tla.js";
36
+ import { GuardError, byText, sameFields, showFields, } from "./types.js";
37
+ /** The result of a guard that passes. */
38
+ export const PASSING = "Model proved, code tested";
39
+ /** The declaration in TLA+, as a file. */
40
+ const DECLARATION_FILE = "Declaration.tla";
41
+ /** The most records a finding prints before the one it is about. */
42
+ const MOST_SHOWN = 20;
43
+ /** What begins the cause of a guard that an error Spex did not expect
44
+ * left not checked (guards-18). */
45
+ export const UNEXPECTED = "an error Spex did not expect: ";
46
+ /** Whether a guard's report is one that passes. */
47
+ export function passes(report) {
48
+ return !("cannot" in report) && report.reasons.length === 0;
49
+ }
50
+ // ---------------------------------------------------------------
51
+ // One copy and its processes (guards-12, guards-53)
52
+ // ---------------------------------------------------------------
53
+ /** Run one program in a copy: its working folder the copy, its temp
54
+ * folder the copy's own, stopped at the time limit with all it
55
+ * started (guards-12). `more` adds to its environment. The copy's
56
+ * fresh folder, which its temp folder names, marks every process the
57
+ * program starts, so that on Linux one that left its group is found. */
58
+ function runIn(copy, program, args, limit, more = {}) {
59
+ return runProcess(program, args, {
60
+ cwd: copy.folder,
61
+ env: { ...withoutRecords(process.env), TMPDIR: copy.scratch, TMP: copy.scratch, TEMP: copy.scratch, ...more },
62
+ seconds: limit,
63
+ // What the code prints takes no part in a result; its errors are
64
+ // kept only to say why a process ended early.
65
+ errors: join(copy.home, "errors.txt"),
66
+ mark: copy.home,
67
+ });
68
+ }
69
+ /** `: <cause>` for a process that ended early, or nothing where it
70
+ * gave none. */
71
+ function becauseOf(said) {
72
+ const cause = lastWords(said);
73
+ return cause === "" ? "" : `: ${cause}`;
74
+ }
75
+ /** What a binding lacks that a test on the code needs, found before
76
+ * any copy is made (guards-36), or null. */
77
+ function lacking(binding) {
78
+ if (binding.kind === "neither")
79
+ return "no binding.mjs and no tests";
80
+ if (binding.files.length === 0)
81
+ return "the declaration names no files";
82
+ return null;
83
+ }
84
+ /** Leave each file of records as the tests wrote it, byte for byte,
85
+ * in `<keep>/<folder>`. */
86
+ function keepLines(from, keep, folder) {
87
+ const to = join(keep, folder);
88
+ mkdirSync(to, { recursive: true });
89
+ for (const file of readdirSync(from).sort(byText)) {
90
+ const path = join(from, file);
91
+ if (/^.+\.jsonl$/.test(file) && lstatSync(path).isFile())
92
+ copyFileSync(path, join(to, file));
93
+ }
94
+ }
95
+ /** The system's own word for what kept a file or folder from being
96
+ * read, as `ENOENT: no such file or directory, scandir '…'`. */
97
+ function systemCause(error) {
98
+ return error instanceof Error ? error.message : String(error);
99
+ }
100
+ /**
101
+ * Make one copy, apply the fault's patch where there is one, run the
102
+ * binding's commands, the copy's process on `sequences` where the
103
+ * binding has a module, and the test command where it has one, read
104
+ * the lines the tests wrote, and remove the copy. A binding that lacks
105
+ * its module and its tests, or its files, gets no copy.
106
+ *
107
+ * Every copy of a run holds the same files, so that no result joins
108
+ * what two versions of the code did (guards-12): the binding's folder
109
+ * and the probes as the guard's inputs were read, and, where `held` is
110
+ * the state of the copy of the project's code, the files that copy
111
+ * held. A copy that holds others is not made.
112
+ */
113
+ async function runCopy(shop, sequences, fault, held) {
114
+ const { guard } = shop;
115
+ const { binding, limits } = guard;
116
+ const lacks = lacking(binding);
117
+ if (lacks !== null)
118
+ return { digest: null, run: { kind: "binding", cause: lacks } };
119
+ let copy;
120
+ try {
121
+ copy = makeCopy(guard.root, [...binding.files, binding.folder]);
122
+ }
123
+ catch (error) {
124
+ const cause = error instanceof Error ? error.message : String(error);
125
+ return { digest: null, run: { kind: "binding", cause: `the copy could not be made: ${cause}` } };
126
+ }
127
+ // The binding's folder as the copy holds it and as the inputs list
128
+ // it: a file the inputs do not name is a change too, so that no
129
+ // helper added since the inputs were read enters a copy.
130
+ const within = `${binding.folder}/`;
131
+ const copied = copy.files.filter((path) => path.startsWith(within));
132
+ const listed = [...new Set([...binding.folderFiles, ...copied])].sort(byText);
133
+ const outside = binding.probes.filter((path) => !path.startsWith(within));
134
+ const input = changedInput(guard.inputs, copy.folder, [...listed, ...outside]);
135
+ const moved = input !== null ? `: ${input}` : held !== null && copy.state !== held ? "" : null;
136
+ if (moved !== null) {
137
+ removeCopy(copy);
138
+ const cause = `the copy could not be made: the project's files changed while the guard was checked${moved}`;
139
+ return { digest: null, run: { kind: "binding", cause } };
140
+ }
141
+ // The revision is read with the copy of the project's code, so that
142
+ // it names what was copied: the declared paths, and each place a
143
+ // link among them led to, whose files Git lists elsewhere (guards-26).
144
+ const revised = fault === null ? { revision: revision(guard.root, [...binding.files, binding.folder, ...copy.linked]) } : {};
145
+ const done = (run) => ({ digest: copy.digest, state: copy.state, run, ...revised });
146
+ // No cause names the copy's fresh folder: a path into the copy is
147
+ // told relative to it, so two runs tell the same cause (guards-36).
148
+ const told = (cause) => relativeToCopy(cause, copy.home);
149
+ try {
150
+ if (fault !== null) {
151
+ const patched = applyPatch(copy.folder, fault.patch);
152
+ if (!patched.applies)
153
+ return done({ kind: "patch", cause: patched.cause });
154
+ if (!patched.changed)
155
+ return done({ kind: "nothing" });
156
+ }
157
+ for (const [index, command] of binding.commands.entries()) {
158
+ const shown = `command ${index + 1} (${command.join(" ")})`;
159
+ const program = command[0] === "node" ? process.execPath : command[0];
160
+ const ran = await runIn(copy, program, command.slice(1), limits.seconds);
161
+ if (ran.failed !== null)
162
+ return done({ kind: "binding", cause: told(`${shown} could not start: ${ran.failed}`) });
163
+ if (ran.timedOut)
164
+ return done({ kind: "timeout" });
165
+ if (ran.code !== 0) {
166
+ const status = ran.code === null ? "ended early" : `ended with status ${ran.code}`;
167
+ return done({ kind: "binding", cause: told(`${shown} ${status}${becauseOf(ran.errors)}`) });
168
+ }
169
+ }
170
+ // The module's sequences, where the binding has a module.
171
+ const observed = new Map();
172
+ const short = [];
173
+ if (binding.module) {
174
+ const job = {
175
+ root: realpathSync.native(guard.root),
176
+ copy: copy.folder,
177
+ result: join(copy.home, "result.jsonl"),
178
+ module: `${binding.folder}/binding.mjs`,
179
+ values: binding.vocabulary.sets,
180
+ events: binding.events,
181
+ sequences,
182
+ };
183
+ const jobFile = join(copy.home, "job.json");
184
+ writeFileSync(jobFile, JSON.stringify(job));
185
+ const runner = fileURLToPath(new URL("./runner.js", import.meta.url));
186
+ const ran = await runIn(copy, process.execPath, [runner, jobFile], limits.seconds);
187
+ // The sequences the process caused to their end before it ended
188
+ // stand (guards-23). A line cut short by its end is not read.
189
+ let finished = false;
190
+ const text = existsSync(job.result) ? readFileSync(job.result, "utf8") : "";
191
+ for (const written of text.split("\n")) {
192
+ let line;
193
+ try {
194
+ line = JSON.parse(written);
195
+ }
196
+ catch {
197
+ continue;
198
+ }
199
+ if (line.kind === "observed")
200
+ observed.set(line.at, line.effects);
201
+ else if (line.kind === "outside")
202
+ short.push({ kind: "outside", file: line.file });
203
+ else if (line.kind === "ended")
204
+ short.push({ kind: "binding", cause: told(line.cause) });
205
+ else if (line.kind === "finished")
206
+ finished = true;
207
+ }
208
+ if (!finished && short.length === 0) {
209
+ if (ran.timedOut)
210
+ short.push({ kind: "timeout", seconds: limits.seconds });
211
+ else {
212
+ const status = ran.code === null ? "" : ` (status ${ran.code})`;
213
+ short.push({
214
+ kind: "binding",
215
+ cause: told(`the process ended before every sequence was caused${status}${becauseOf(ran.failed ?? ran.errors)}`),
216
+ });
217
+ }
218
+ }
219
+ }
220
+ // The project's tests with the probes on, where the binding names
221
+ // them and the module, if any, caused every sequence (guards-53).
222
+ let book = newBook(binding);
223
+ let tests = null;
224
+ let read = null;
225
+ let unread = null;
226
+ if (binding.tests !== null && short.length === 0) {
227
+ const words = binding.tests;
228
+ const program = words[0] === "node" ? process.execPath : words[0];
229
+ const began = Date.now();
230
+ const ran = await runIn(copy, program, words.slice(1), limits.seconds, { SPEX_RECORDS: copy.records });
231
+ tests = {
232
+ words,
233
+ failed: ran.failed === null ? null : told(ran.failed),
234
+ code: ran.code,
235
+ timedOut: ran.timedOut,
236
+ because: told(becauseOf(ran.errors)),
237
+ left: ran.left,
238
+ seconds: (Date.now() - began) / 1000,
239
+ };
240
+ if (ran.failed === null) {
241
+ // What the tests left may be past reading: a folder they
242
+ // removed, a file they closed to its reader. That is the
243
+ // binding's failure and no error of the run (guards-36): none
244
+ // of the lines is read, so no half-read file counts.
245
+ try {
246
+ read = await readRecords(copy.records, book);
247
+ }
248
+ catch (error) {
249
+ // Only what the system refused: any other error is Spex's own.
250
+ if (typeof error?.code !== "string" || error instanceof GuardError)
251
+ throw error;
252
+ unread = told(systemCause(error));
253
+ book = newBook(binding);
254
+ read = { sequences: [], refused: [], strays: [] };
255
+ }
256
+ if (unread === null && shop.keep !== null)
257
+ keepLines(copy.records, shop.keep, fault === null ? "lines" : `lines-${fault.name}`);
258
+ }
259
+ }
260
+ return done({ kind: "done", observed, short, tests, read, unread, book });
261
+ }
262
+ finally {
263
+ removeCopy(copy);
264
+ }
265
+ }
266
+ // ---------------------------------------------------------------
267
+ // What the records show against the model
268
+ // ---------------------------------------------------------------
269
+ /** The rows of the table in the order they are tried: shortest
270
+ * sequences first, ties in TLC's order. */
271
+ function inOrder(table) {
272
+ return table.rows
273
+ .map((row, at) => ({ row, at, path: table.paths.get(row.from) }))
274
+ .sort((a, b) => a.path.length - b.path.length || a.at - b.at);
275
+ }
276
+ function placesOf(book) {
277
+ const places = new Map();
278
+ for (const { values } of Object.values(copyValues(book)))
279
+ values.forEach((value, at) => places.set(value, at));
280
+ return places;
281
+ }
282
+ /** A value of a declared type with a set's members in order. */
283
+ function arranged(type, value, places) {
284
+ if (type.kind === "optional")
285
+ return value === null ? null : arranged(type.of, value, places);
286
+ if (type.kind !== "set" || !Array.isArray(value))
287
+ return value;
288
+ const rank = (member) => typeof member === "string" ? (places.get(member) ?? Number.MAX_SAFE_INTEGER) : typeof member === "number" ? member : Number(member);
289
+ return value.map((member) => arranged(type.of, member, places)).sort((a, b) => rank(a) - rank(b));
290
+ }
291
+ /** Named values in the declared order, each arranged. */
292
+ function arrangedFields(declared, fields, places) {
293
+ const out = {};
294
+ for (const [name, type] of Object.entries(declared))
295
+ if (Object.hasOwn(fields, name))
296
+ out[name] = arranged(type, fields[name], places);
297
+ return out;
298
+ }
299
+ /** A TLA+ value TLC printed as a value of a record, or undefined. */
300
+ function valueOfTla(value) {
301
+ if (typeof value !== "object")
302
+ return value;
303
+ if ("m" in value)
304
+ return value.m === "Missing" ? null : undefined;
305
+ if ("s" in value) {
306
+ const members = value.s.map(valueOfTla);
307
+ return members.some((member) => member === undefined) ? undefined : members;
308
+ }
309
+ return undefined;
310
+ }
311
+ /** What a translation says of one sequence, in a report's words. */
312
+ function saidOf(answer) {
313
+ if (answer.said === "matched")
314
+ return "every record matched";
315
+ const what = answer.said === "forbidden" ? "forbidden by the rule" : answer.said === "differs" ? "not the model's" : "not legal";
316
+ return `record ${answer.matched + 1} ${what}`;
317
+ }
318
+ async function assess(shop, name, judging, others, permitted, table, run) {
319
+ const { binding } = shop.guard;
320
+ const { book, observed, read, tests } = run;
321
+ const kind = binding.kind;
322
+ const rows = inOrder(table);
323
+ // The same sequence caused again gives the same effects.
324
+ const first = new Map();
325
+ let notRepeated = null;
326
+ const repeats = (calls, effects) => {
327
+ let prefix = "";
328
+ for (const [at, effect] of effects.entries()) {
329
+ prefix += `\n${JSON.stringify(calls[at])}`;
330
+ const known = first.get(prefix);
331
+ if (known === undefined)
332
+ first.set(prefix, effect);
333
+ else if (!sameFields(known, effect) && notRepeated === null) {
334
+ notRepeated = {
335
+ kind: "not repeated",
336
+ steps: calls.slice(0, at).map((call, index) => ({ call, effect: showFields(effects[index]) })),
337
+ last: calls[at],
338
+ gave: showFields(known),
339
+ other: showFields(effect),
340
+ };
341
+ }
342
+ }
343
+ };
344
+ // The sequences: each the module caused to its end, its permitted
345
+ // cases first and then each step of the model, then the tests'.
346
+ const sequences = [];
347
+ const sources = [];
348
+ permitted.forEach((entry, index) => {
349
+ const effects = observed.get(index);
350
+ if (effects === undefined)
351
+ return;
352
+ const calls = entry.steps.map((step) => ({ event: step.event, params: step.params }));
353
+ repeats(calls, effects);
354
+ sequences.push(moduleSequence(book, moduleCaseName(entry.label), calls, effects));
355
+ sources.push({ kind: "case", entry });
356
+ });
357
+ rows.forEach(({ row, path }, index) => {
358
+ const effects = observed.get(permitted.length + index);
359
+ if (effects === undefined)
360
+ return;
361
+ const calls = [...path.map((step) => step.call), row.call];
362
+ repeats(calls, effects);
363
+ sequences.push(moduleSequence(book, moduleStepName(index + 1), calls, effects));
364
+ sources.push({ kind: "step" });
365
+ });
366
+ for (const sequence of read?.sequences ?? []) {
367
+ sequences.push(sequence);
368
+ sources.push({ kind: "tests" });
369
+ }
370
+ // TLC judges every sequence, the module's then the tests'.
371
+ const check = await judgeRecords(shop, name, judging, sequences, book);
372
+ if (check.kind === "cannot")
373
+ return { cannot: check.cannot };
374
+ const { judged, halted } = check;
375
+ // TLC compared the translations at the declared values alone. Where
376
+ // their agreement is not proved for any values, `others` holds every
377
+ // translation after the first, and where the copy's records hold a
378
+ // value outside the declared ones, each of them judges the same
379
+ // sequences in runs of its own. A finding stands only in a sequence
380
+ // every translation judges alike, so that no result and no caught
381
+ // fault rests on which translation is first in name order (guards-61).
382
+ const unsure = new Set();
383
+ const differing = [];
384
+ const stoppedOthers = [];
385
+ // For a sequence a stopped run left unjudged, that run's cause.
386
+ const unjudgedBy = new Map();
387
+ // What each translation that judged a sequence said of it, in name
388
+ // order, and the sequences of which they say otherwise.
389
+ const answered = new Map();
390
+ const differs = new Set();
391
+ let firstDiffering;
392
+ // Whether another translation applies the rule at another number of
393
+ // a sequence's records: the count of those is then the first's alone.
394
+ let appliedOtherwise = false;
395
+ // The sequences all judge alike but for the model's effect where
396
+ // the first does not match: that effect is then the first's alone.
397
+ const modelOfFirst = new Set();
398
+ if (others.length > 0 && book.homes.size > 0) {
399
+ const upTo = judged.indexOf(null);
400
+ const again = upTo < 0 ? sequences : sequences.slice(0, upTo);
401
+ const said = again.map((_, k) => [`${judging.name}: ${saidOf(judged[k])}`]);
402
+ again.forEach((_, k) => answered.set(k, [{ translation: judging.name, judged: judged[k] }]));
403
+ for (const other of again.length === 0 ? [] : others) {
404
+ const second = await judgeRecords(shop, `${name}@${other.name}`, other, again, book);
405
+ if (second.kind === "cannot")
406
+ return { cannot: second.cannot };
407
+ const halt = second.halted;
408
+ const stoppedHere = halt === null
409
+ ? null
410
+ : halt.kind === "timeout"
411
+ ? { kind: "stopped", cause: `${halt.cause} under translation ${other.name}` }
412
+ : { kind: "said", text: `${halt.cause} under translation ${other.name}` };
413
+ if (stoppedHere !== null)
414
+ stoppedOthers.push(stoppedHere);
415
+ again.forEach((_, k) => {
416
+ const first = judged[k];
417
+ const answer = second.judged[k];
418
+ if (answer === null) {
419
+ unsure.add(k);
420
+ if (stoppedHere !== null && !unjudgedBy.has(k))
421
+ unjudgedBy.set(k, stoppedHere);
422
+ return;
423
+ }
424
+ said[k].push(`${other.name}: ${saidOf(answer)}`);
425
+ answered.get(k)?.push({ translation: other.name, judged: answer });
426
+ if (answer.applied !== first.applied)
427
+ appliedOtherwise = true;
428
+ if (answer.matched !== first.matched || answer.said !== first.said)
429
+ differs.add(k);
430
+ else if (key(answer.model ?? "") !== key(first.model ?? ""))
431
+ modelOfFirst.add(k);
432
+ });
433
+ }
434
+ for (const k of [...differs].sort((a, b) => a - b)) {
435
+ firstDiffering ??= k;
436
+ unsure.add(k);
437
+ differing.push(`${sequences[k].name}: ${said[k].join("; ")}`);
438
+ }
439
+ }
440
+ const places = placesOf(book);
441
+ const { events } = binding;
442
+ const callShown = (call) => ({ event: call.event, params: arrangedFields(events[call.event].params, call.params, places) });
443
+ const effectShown = (call, effect) => showFields(arrangedFields(events[call.event].effect, effect, places));
444
+ const modelShown = (call, model) => {
445
+ const declared = events[call.event].effect;
446
+ // An event with no effect field has the one effect `<<>>`: any
447
+ // other value of the model is shown as TLC printed it.
448
+ if (Object.keys(declared).length === 0)
449
+ return model === null || key(model) === key({ t: [] }) ? "" : showTla(canon(model));
450
+ const record = model !== null && typeof model === "object" && "r" in model ? model.r : null;
451
+ const whole = () => (model === null ? "" : showTla(canon(model)));
452
+ // A record of other fields than the declared ones is shown whole:
453
+ // a field left out could be all that parts it from the code's.
454
+ if (record === null || Object.keys(record).length !== Object.keys(declared).length)
455
+ return whole();
456
+ const fields = {};
457
+ for (const field of Object.keys(declared)) {
458
+ const value = Object.hasOwn(record, field) ? valueOfTla(record[field]) : undefined;
459
+ if (value === undefined)
460
+ return whole();
461
+ fields[field] = value;
462
+ }
463
+ return effectShown(call, fields);
464
+ };
465
+ // The permitted cases: the module's own sequences where it has a
466
+ // module, else every sequence of the tests that opens with one. A
467
+ // record that differs in a field its step states is a failed case.
468
+ // One sequence of the tests may open several cases, so it may hold a
469
+ // failed step of each: every one is kept, whichever case is listed first.
470
+ const failedAt = new Map();
471
+ const failed = [];
472
+ const causes = [];
473
+ let casesCaused = 0;
474
+ let casesAsStated = 0;
475
+ const failure = (entry, k, sequence) => {
476
+ const found = stepFailure(entry.steps, sequences[k].handed, book);
477
+ if (found === null)
478
+ return false;
479
+ failedAt.set(k, (failedAt.get(k) ?? new Set()).add(found.step));
480
+ const declared = events[entry.steps[found.step - 1].event].effect;
481
+ for (const one of found.differences) {
482
+ failed.push({
483
+ case: entry.label,
484
+ step: found.step,
485
+ field: one.field,
486
+ stated: arranged(declared[one.field], one.stated, places),
487
+ observed: arranged(declared[one.field], one.observed, places),
488
+ sequence,
489
+ });
490
+ }
491
+ return true;
492
+ };
493
+ const notSeen = [];
494
+ if (binding.module) {
495
+ sources.forEach((source, k) => {
496
+ if (source.kind !== "case")
497
+ return;
498
+ casesCaused += 1;
499
+ if (!failure(source.entry, k, null))
500
+ casesAsStated += 1;
501
+ });
502
+ }
503
+ else {
504
+ for (const entry of permitted) {
505
+ const openings = caseOpenings(entry.steps, sequences, book);
506
+ if (openings.length === 0) {
507
+ notSeen.push(entry.label);
508
+ continue;
509
+ }
510
+ casesCaused += 1;
511
+ let any = false;
512
+ for (const opening of openings)
513
+ if (failure(entry, opening.sequence, sequences[opening.sequence].name))
514
+ any = true;
515
+ if (!any)
516
+ casesAsStated += 1;
517
+ }
518
+ }
519
+ // What TLC said of each sequence, read into the counts and the
520
+ // findings (guards-55, guards-57).
521
+ const counts = {
522
+ records: 0,
523
+ sequences: sequences.length,
524
+ matched: 0,
525
+ forbidden: 0,
526
+ differs: 0,
527
+ notJudged: 0,
528
+ applied: 0,
529
+ reached: 0,
530
+ steps: table.rows.length,
531
+ beyond: 0,
532
+ by: null,
533
+ };
534
+ const code = {
535
+ kind,
536
+ steps: rows.length,
537
+ tested: 0,
538
+ same: 0,
539
+ forbidden: 0,
540
+ differs: 0,
541
+ notReached: 0,
542
+ notJudged: 0,
543
+ cases: permitted.length,
544
+ casesCaused,
545
+ casesAsStated,
546
+ tests: tests === null ? null : { sequences: read?.sequences.length ?? 0, whole: read?.sequences.filter((one) => one.why === null).length ?? 0 },
547
+ counts,
548
+ violation: null,
549
+ difference: null,
550
+ failed,
551
+ };
552
+ // The first sequence whose forbidden record does not stand.
553
+ let unsettledAt;
554
+ const findingOf = (k, answer) => {
555
+ const sequence = sequences[k];
556
+ const source = sources[k];
557
+ const before = sequence.handed.slice(0, answer.matched);
558
+ const earlier = Math.max(0, before.length - MOST_SHOWN);
559
+ const record = book.records[sequence.handed[answer.matched]];
560
+ return {
561
+ sequence: source.kind === "tests" ? sequence.name : null,
562
+ case: source.kind === "case" ? source.entry.label : null,
563
+ at: answer.matched + 1,
564
+ earlier,
565
+ steps: before.slice(earlier).map((number) => {
566
+ const one = book.records[number];
567
+ return { call: callShown(one.call), effect: effectShown(one.call, one.effect) };
568
+ }),
569
+ last: callShown(record.call),
570
+ model: answer.said === "not legal" ? null : modelShown(record.call, answer.model),
571
+ gave: effectShown(record.call, record.effect),
572
+ by: modelOfFirst.has(k) ? judging.name : null,
573
+ };
574
+ };
575
+ // A sequence the translations judge differently, to the record at
576
+ // which they part: the first that some translation does not match.
577
+ const disputeOf = (k) => {
578
+ const sequence = sequences[k];
579
+ const each = answered.get(k) ?? [];
580
+ const at = Math.min(...each.map((one) => one.judged.matched));
581
+ const before = sequence.handed.slice(0, at);
582
+ const earlier = Math.max(0, before.length - MOST_SHOWN);
583
+ const record = book.records[sequence.handed[at]];
584
+ return {
585
+ earlier,
586
+ steps: before.slice(earlier).map((number) => {
587
+ const one = book.records[number];
588
+ return { call: callShown(one.call), effect: effectShown(one.call, one.effect) };
589
+ }),
590
+ last: callShown(record.call),
591
+ gave: effectShown(record.call, record.effect),
592
+ answers: each.map(({ translation, judged: one }) => ({
593
+ translation,
594
+ said: one.matched > at ? "matched" : one.said,
595
+ model: one.matched > at || one.said === "not legal" ? null : modelShown(record.call, one.model),
596
+ })),
597
+ };
598
+ };
599
+ sequences.forEach((sequence, k) => {
600
+ counts.records += sequence.records;
601
+ const step = sources[k].kind === "step";
602
+ if (step)
603
+ code.tested += 1;
604
+ const answer = judged[k];
605
+ if (answer === null) {
606
+ counts.notJudged += sequence.records;
607
+ if (step)
608
+ code.notJudged += 1;
609
+ return;
610
+ }
611
+ const stopped = answer.said === "matched" ? 0 : 1;
612
+ counts.matched += answer.matched;
613
+ counts.applied += answer.applied;
614
+ counts.notJudged += sequence.records - answer.matched - stopped;
615
+ if (step) {
616
+ const n = sequence.handed.length;
617
+ if (answer.matched === n)
618
+ code.same += 1;
619
+ else if (answer.matched < n - 1)
620
+ code.notReached += 1;
621
+ else if (answer.said === "forbidden")
622
+ code.forbidden += 1;
623
+ else
624
+ code.differs += 1;
625
+ }
626
+ if (answer.said === "forbidden") {
627
+ counts.forbidden += 1;
628
+ if (unsure.has(k))
629
+ unsettledAt ??= k;
630
+ else
631
+ code.violation ??= findingOf(k, answer);
632
+ }
633
+ else if (answer.said !== "matched") {
634
+ counts.differs += 1;
635
+ // A record that differs in a field its case's step states is a
636
+ // failed case, and no difference from the model.
637
+ if (answer.said === "differs" && failedAt.get(k)?.has(answer.matched + 1))
638
+ return;
639
+ if (!unsure.has(k))
640
+ code.difference ??= findingOf(k, answer);
641
+ }
642
+ });
643
+ const reached = reach(table, sequences, judged, book);
644
+ counts.reached = reached.reached.size;
645
+ counts.beyond = reached.beyond;
646
+ // What the test command and its lines leave short, in the order of
647
+ // the run's steps (guards-53, guards-51, guards-52, guards-56).
648
+ if (tests !== null) {
649
+ if (tests.failed !== null) {
650
+ causes.push({ kind: "binding", cause: `the test command (${tests.words.join(" ")}) could not start: ${tests.failed}` });
651
+ }
652
+ else if (tests.timedOut) {
653
+ causes.push({ kind: "said", text: `a timeout: the tests were not done after ${seconds(shop.guard.limits.seconds)}` });
654
+ }
655
+ else if (tests.code === null) {
656
+ causes.push({ kind: "said", text: `the tests were ended before they finished${tests.because}` });
657
+ }
658
+ else if (tests.code !== 0) {
659
+ causes.push({ kind: "said", text: `the tests ended with status ${tests.code}${tests.because}` });
660
+ }
661
+ if (tests.left)
662
+ causes.push({ kind: "said", text: "the tests left processes running when they ended" });
663
+ }
664
+ if (read !== null) {
665
+ const [one, ...more] = read.refused;
666
+ if (one !== undefined) {
667
+ const others = more.length === 0 ? "" : `, and ${more.length} more ${more.length === 1 ? "line" : "lines"}`;
668
+ causes.push({ kind: "binding", cause: `a probe wrote what is no line of the binding: ${one.file}:${one.line}: ${one.cause}${others}` });
669
+ }
670
+ for (const stray of read.strays)
671
+ causes.push({ kind: "binding", cause: `${printedName(stray)} in the folder of records is no file of records` });
672
+ if (run.unread !== null) {
673
+ causes.push({ kind: "binding", cause: `the folder of records could not be read: ${run.unread}` });
674
+ }
675
+ else if (read.sequences.length === 0 && !tests?.timedOut) {
676
+ causes.push({
677
+ kind: "binding",
678
+ cause: "the tests wrote no sequence of records: a probe appends its lines to a file <name>.jsonl in the folder SPEX_RECORDS names",
679
+ });
680
+ }
681
+ const broken = read.sequences.filter((sequence) => sequence.why !== null);
682
+ if (broken.length > 0) {
683
+ const more = broken.length > 1 ? `, and ${broken.length - 1} more` : "";
684
+ causes.push({ kind: "said", text: `a sequence of records is not whole: ${broken[0].name}: ${broken[0].why}${more}` });
685
+ }
686
+ }
687
+ for (const label of notSeen)
688
+ causes.push({ kind: "said", text: `a permitted case was not seen on the code: "${label}"` });
689
+ if (halted !== null) {
690
+ causes.push(halted.kind === "timeout" ? { kind: "stopped", cause: halted.cause } : { kind: "said", text: halted.cause });
691
+ }
692
+ else if (counts.applied === 0 && counts.matched + counts.forbidden + counts.differs > 0) {
693
+ causes.push({ kind: "said", text: "the rule applied at no record" });
694
+ }
695
+ // What the other translations left unsettled (guards-61): a run
696
+ // stopped at the time limit before one out of memory, as listed.
697
+ causes.push(...stoppedOthers.filter((one) => one.kind === "stopped"), ...stoppedOthers.filter((one) => one.kind !== "stopped"));
698
+ const differently = differing.length === 0
699
+ ? null
700
+ : `the translations judge a sequence of records differently: ${differing[0]}${differing.length > 1 ? `, and ${differing.length - 1} more` : ""}`;
701
+ const dispute = firstDiffering === undefined ? null : disputeOf(firstDiffering);
702
+ if (differently !== null && dispute !== null)
703
+ causes.push({ kind: "judged differently", text: differently, shown: dispute });
704
+ counts.by = unsure.size > 0 || appliedOtherwise ? judging.name : null;
705
+ // Why no forbidden record stands, for a kept fault: the sequences
706
+ // judged differently, else the run that left the first translation's
707
+ // forbidden record unjudged.
708
+ const left = unsettledAt === undefined ? undefined : unjudgedBy.get(unsettledAt);
709
+ const unsettled = differently ?? (left === undefined ? null : left.kind === "stopped" ? left.cause : left.kind === "said" ? left.text : null);
710
+ return { code, notRepeated, causes, halted, unsettled, dispute, sequences };
711
+ }
712
+ /** What `--keep` leaves of one copy's sequences: one line for each,
713
+ * with its run and its number there, each line refused, then the test
714
+ * command as run (guards-41). */
715
+ function keepSequences(keep, name, assessed, run) {
716
+ const { sequences } = assessed;
717
+ const runs = runsOf(sequences);
718
+ const lines = sequences.map((sequence, k) => {
719
+ const at = runs.findIndex((one) => k >= one.from && k < one.to);
720
+ const where = at < 0 ? "no run" : `${runFolder(name, at + 1)} ${k - runs[at].from + 1}`;
721
+ const whole = sequence.why === null ? "whole" : `not whole: ${sequence.why}`;
722
+ return `${where}: ${sequence.name}: ${whole}; ${sequence.records} ${sequence.records === 1 ? "record" : "records"}, ${sequence.handed.length} handed to TLC`;
723
+ });
724
+ for (const one of run.read?.refused ?? [])
725
+ lines.push(`refused: ${one.file}:${one.line}: ${one.cause}`);
726
+ const { tests } = run;
727
+ if (tests !== null) {
728
+ const ended = tests.failed !== null
729
+ ? `could not start: ${tests.failed}`
730
+ : tests.timedOut
731
+ ? "stopped at the time limit"
732
+ : tests.code === null
733
+ ? "ended by a signal"
734
+ : `status ${tests.code}`;
735
+ lines.push(`test command: ${tests.words.map(quoted).join(" ")}: ${ended}, ${tests.seconds.toFixed(1)} seconds`);
736
+ }
737
+ writeFileSync(join(keep, `${name === "records" ? "sequences" : `sequences${name.slice("records".length)}`}.txt`), `${lines.join("\n")}\n`);
738
+ }
739
+ // ---------------------------------------------------------------
740
+ // One guard
741
+ // ---------------------------------------------------------------
742
+ function spexVersion() {
743
+ try {
744
+ const manifest = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
745
+ return typeof manifest.version === "string" ? manifest.version : "unknown";
746
+ }
747
+ catch {
748
+ return "unknown";
749
+ }
750
+ }
751
+ /** The short Git commit of the root, `with changes` where Git reports
752
+ * a change in the copied files, or that there is none. */
753
+ function revision(root, paths) {
754
+ // --no-optional-locks keeps Git from writing anything into .git, and
755
+ // a path is the name of a file, never a pattern: `[id].ts` is not
756
+ // `i.ts`.
757
+ const git = (args) => execFileSync("git", ["--no-optional-locks", "--literal-pathspecs", "-C", root, ...args], {
758
+ encoding: "utf8",
759
+ stdio: ["ignore", "pipe", "ignore"],
760
+ });
761
+ try {
762
+ const commit = git(["rev-parse", "--short", "HEAD"]).trim();
763
+ if (commit === "")
764
+ return "no Git revision";
765
+ const changes = git(["status", "--porcelain", "--", ...paths]).trim();
766
+ return `revision ${commit}${changes === "" ? "" : " with changes"}`;
767
+ }
768
+ catch {
769
+ return "no Git revision";
770
+ }
771
+ }
772
+ /**
773
+ * What a result rests on (guards-23), as DR-244 lists it: that the
774
+ * translations say what the items say, that the declaration says what
775
+ * the rule is about, that a proof rests on nothing beyond the
776
+ * declaration's assumptions, that the proof system and its solvers
777
+ * are sound, that values outside the declared ones are given to TLC
778
+ * in the declared order, that the module and the probes report every
779
+ * event truly and in order, and that the tests reach the behavior that
780
+ * matters. Each is said with how it is held; the last two by what the
781
+ * binding has, and the one on the order only where a record can hold
782
+ * such a value of a set with an order: the binding has probes, and
783
+ * `ordered` says its declaration gives a set an order.
784
+ */
785
+ export function assumptions(proof, kind = "module", ordered = false) {
786
+ // Each line names an assumption and the means by which it is held,
787
+ // not what this run found: that is in the lines above it.
788
+ const reports = kind === "probes"
789
+ ? "the probes report every event truly and in order: checked in part, by each kept fault and by each sequence being whole"
790
+ : kind === "both"
791
+ ? "the module and the probes report every event truly and in order: checked in part, by each kept fault and by each sequence being whole"
792
+ : "the module reports every event truly and in order: checked in part, by each kept fault";
793
+ const reach = kind === "probes"
794
+ ? "the tests reach the behavior that matters: not checked; the result says how much of the model the records reached"
795
+ : "the tests reach the behavior that matters: not checked; the module tries each step of the model once";
796
+ return [
797
+ "the translations say what the items say: checked by the cases, by their agreement and by a person's approval",
798
+ "the declaration says what the rule is about, its sets as it states them: checked only by a person's approval",
799
+ "a proof rests on nothing beyond the declaration's assumptions: checked by Spex's own reading of the proof files",
800
+ "TLC and the proof system read a file alike: not checked; a translation and a proof file hold only printable ASCII",
801
+ `the proof system${proof === null ? "" : ` ${proof.version}`} and its solvers are sound: not checked`,
802
+ ...(ordered && (kind === "probes" || kind === "both")
803
+ ? ["values outside the declared ones are given to TLC in the declared order: by Spex's own sort, of which TLC checks only that no value stands twice"]
804
+ : []),
805
+ reports,
806
+ reach,
807
+ ];
808
+ }
809
+ /** Why a kept fault was not caught on a copy whose module's process
810
+ * did not cause every sequence. */
811
+ function shortReason(cause, limits) {
812
+ switch (cause.kind) {
813
+ case "binding":
814
+ return `the binding failed: ${cause.cause}`;
815
+ case "timeout":
816
+ return `a timeout: not done after ${seconds(limits.seconds)}`;
817
+ case "outside":
818
+ return `a project file was loaded from outside the copy: ${cause.file}`;
819
+ case "stopped":
820
+ return cause.cause;
821
+ default:
822
+ return "the tests did not end";
823
+ }
824
+ }
825
+ /**
826
+ * Check one guard (guards-17).
827
+ */
828
+ export async function checkGuard(root, name, run) {
829
+ const cannot = (cause) => ({ name, cannot: [{ cause, note: null, steps: [] }] });
830
+ const said = (error) => (error instanceof Error ? error.message : String(error));
831
+ // 1. Load. A guard with no translation yet has its declaration all
832
+ // the same: `--keep` leaves it in TLA+, for those who draft one.
833
+ let guard;
834
+ try {
835
+ guard = loadGuard(root, name, run.index());
836
+ }
837
+ catch (error) {
838
+ if (error instanceof NoTranslation && run.keep !== null) {
839
+ try {
840
+ const kept = prepareKeep(run.keep, name);
841
+ writeFileSync(join(kept, DECLARATION_FILE), declarationModule(error.binding, error.binding.name));
842
+ }
843
+ catch (failure) {
844
+ if (!(failure instanceof GuardError))
845
+ throw failure;
846
+ return cannot(failure.message);
847
+ }
848
+ }
849
+ return cannot(error instanceof GuardError ? error.message : `${UNEXPECTED}${said(error)}`);
850
+ }
851
+ // 2. The inputs against the approval record.
852
+ let approval;
853
+ try {
854
+ approval = { ...compareApproval(guard.inputs, readApproval(root, name)), unreadable: null };
855
+ }
856
+ catch (error) {
857
+ if (!(error instanceof GuardError))
858
+ throw error;
859
+ approval = { approved: false, recorded: true, changed: [], added: [], gone: [], unreadable: error.message };
860
+ }
861
+ // TLC, and where it runs.
862
+ let tools;
863
+ try {
864
+ tools = await run.tools();
865
+ }
866
+ catch (error) {
867
+ if (!(error instanceof GuardError))
868
+ throw error;
869
+ return cannot(error.message);
870
+ }
871
+ const home = makeHome();
872
+ try {
873
+ const shop = {
874
+ tools,
875
+ guard,
876
+ home,
877
+ keep: run.keep === null ? null : prepareKeep(run.keep, name),
878
+ version: { tlc: null },
879
+ };
880
+ return await check(guard, approval, shop);
881
+ }
882
+ catch (error) {
883
+ if (!(error instanceof GuardError))
884
+ throw error;
885
+ return cannot(error.message);
886
+ }
887
+ finally {
888
+ removeFolder(home);
889
+ }
890
+ }
891
+ /**
892
+ * Wait for runs started together, every one to its end, and hand
893
+ * back what each found. Where runs fail, the failure told is that of
894
+ * the first in the order given, whichever ended first: the same
895
+ * inputs give the same report, and no run outlives its guard.
896
+ */
897
+ async function together(runs) {
898
+ const ended = await Promise.allSettled(runs);
899
+ for (const one of ended)
900
+ if (one.status === "rejected")
901
+ throw one.reason;
902
+ return ended.map((one) => one.value);
903
+ }
904
+ /** Why a kept fault whose copy was judged was not caught: the first
905
+ * that holds in the order of the run's steps (guards-24). */
906
+ function faultReason(guard, made, assessed) {
907
+ const { limits, binding } = guard;
908
+ // No record's effect is forbidden under every translation: the
909
+ // first translation found one, or another did (guards-61).
910
+ if (assessed.unsettled !== null)
911
+ return assessed.unsettled;
912
+ if (made.short.length > 0)
913
+ return shortReason(made.short[0], limits);
914
+ const { tests } = made;
915
+ if (tests?.failed != null)
916
+ return `the binding failed: the test command (${tests.words.join(" ")}) could not start: ${tests.failed}`;
917
+ if (tests?.timedOut)
918
+ return `a timeout: the tests were not done after ${seconds(limits.seconds)}`;
919
+ const failing = assessed.causes.find((cause) => cause.kind === "binding");
920
+ if (failing?.kind === "binding")
921
+ return `the binding failed: ${failing.cause}`;
922
+ if (assessed.halted !== null)
923
+ return assessed.halted.cause;
924
+ const found = assessed.code;
925
+ if (binding.kind === "module") {
926
+ const other = found.differs + found.notReached;
927
+ return (`the code gave no effect the rule forbids in ${found.tested} ${found.tested === 1 ? "step" : "steps"} tested` +
928
+ (other === 0 ? "" : `; ${other} did not give the model's effect`));
929
+ }
930
+ const { counts } = found;
931
+ const judged = counts.matched + counts.forbidden + counts.differs;
932
+ const status = tests === null || tests.code === 0
933
+ ? ""
934
+ : tests.code === null
935
+ ? "; the tests were ended before they finished"
936
+ : `; the tests ended with status ${tests.code}`;
937
+ const left = tests?.left ? "; the tests left processes running when they ended" : "";
938
+ return (`the code gave no effect the rule forbids in ${judged} ${judged === 1 ? "record" : "records"} judged` +
939
+ (counts.differs === 0 ? "" : `; ${counts.differs} not matched`) +
940
+ status +
941
+ left);
942
+ }
943
+ async function check(guard, approval, shop) {
944
+ const { name, root, translations, limits } = guard;
945
+ // The first translation in name order: its model is checked and
946
+ // judges the code.
947
+ const judging = translations[0];
948
+ // 0. Each translation alone, every fault of every one.
949
+ const forms = await together(translations.map((translation) => checkForm(shop, translation)));
950
+ if (forms.some((faults) => faults.length > 0)) {
951
+ return { name, cannot: forms.flat().map((cause) => ({ cause, note: null, steps: [] })) };
952
+ }
953
+ // 1 to 3. Without the code: the model, the translations against
954
+ // each other, the cases. The runs start together.
955
+ const [model, compared, cases] = await together([checkModel(shop, judging), translations.length > 1 ? compareTranslations(shop) : null, checkCases(shop)]);
956
+ const unreadable = [];
957
+ // A translation TLC could not go on in is told once: as the model
958
+ // run met it, else the comparison, else the cases.
959
+ const told = new Set();
960
+ for (const found of [model, compared, cases]) {
961
+ if (found?.kind !== "cannot")
962
+ continue;
963
+ for (const one of found.cannot) {
964
+ const file = /^(.*?\.tla)(:\d+:\d+)?: /.exec(one.cause)?.[1] ?? one.cause;
965
+ if (!told.has(file))
966
+ unreadable.push(one);
967
+ told.add(file);
968
+ }
969
+ }
970
+ if (unreadable.length > 0)
971
+ return { name, cannot: unreadable };
972
+ if (cases.kind === "cannot" || compared?.kind === "cannot" || model.kind === "cannot") {
973
+ throw new GuardError("TLC could not check the guard");
974
+ }
975
+ const causes = [];
976
+ const failures = cases.kind === "done" ? cases.failures : [];
977
+ const casesFailed = cases.kind === "stopped" || failures.length > 0;
978
+ if (cases.kind === "stopped")
979
+ causes.push({ kind: "stopped", cause: cases.cause });
980
+ else if (failures.length > 0)
981
+ causes.push({ kind: "cases" });
982
+ if (compared?.kind === "differ")
983
+ causes.push({ kind: "differ" });
984
+ if (compared?.kind === "not compared")
985
+ causes.push({ kind: "not compared", cause: compared.cause });
986
+ if (model.kind === "not checked")
987
+ causes.push({ kind: "stopped", cause: `${model.cause} while it checked the model` });
988
+ if (model.kind === "checked" && model.applied === 0)
989
+ causes.push({ kind: "never applied" });
990
+ // Why the code is not tested, where it is not: no translation
991
+ // judges it then.
992
+ const notTested = casesFailed
993
+ ? "the check of cases without the code failed"
994
+ : compared?.kind === "differ"
995
+ ? "the translations differ"
996
+ : compared?.kind === "not compared"
997
+ ? "the translations were not compared"
998
+ : model.kind === "conflict"
999
+ ? "the model conflicts with the rule"
1000
+ : model.kind === "not checked"
1001
+ ? "the model was not checked"
1002
+ : model.applied === 0
1003
+ ? "the rule applies at no step of the model"
1004
+ : null;
1005
+ // The proofs, for any values, where TLC found nothing wrong at the
1006
+ // declared values: where it did, a statement is false or its check
1007
+ // did not settle, and the result rests on that already. Proofs that
1008
+ // are not accepted leave the code tested all the same.
1009
+ const proofs = notTested === null ? await checkProofs(shop) : { kind: "not checked", cause: notTested };
1010
+ // Where the proofs are accepted the translations agree for any
1011
+ // values; where they are not, every other translation judges the
1012
+ // records too (guards-61).
1013
+ const others = proofs.kind === "accepted" ? [] : translations.slice(1);
1014
+ // The revision as the copy of the project's code read it; null
1015
+ // where no copy was made, and it is then read at the end.
1016
+ let revised = null;
1017
+ // 4 and 5. The permitted cases and every step of the model, and the
1018
+ // project's tests, on a copy; TLC judges their records.
1019
+ let digest = null;
1020
+ let code = null;
1021
+ const faults = [];
1022
+ if (notTested !== null || model.kind !== "checked") {
1023
+ for (const fault of guard.faults) {
1024
+ faults.push({ name: fault.name, tried: false, caught: null, reason: notTested });
1025
+ }
1026
+ }
1027
+ else {
1028
+ const { table } = model;
1029
+ const permitted = guard.cases.filter((entry) => entry.kind === "permitted");
1030
+ const sequences = [
1031
+ ...permitted.map((entry) => entry.steps.map((step) => ({ event: step.event, params: step.params }))),
1032
+ ...inOrder(table).map(({ row, path }) => [...path.map((step) => step.call), row.call]),
1033
+ ];
1034
+ const copied = await runCopy(shop, sequences, null, null);
1035
+ digest = copied.digest;
1036
+ revised = copied.revision ?? null;
1037
+ if (copied.run.kind === "binding")
1038
+ causes.push({ kind: "binding", cause: copied.run.cause });
1039
+ else if (copied.run.kind === "timeout")
1040
+ causes.push({ kind: "timeout", seconds: limits.seconds });
1041
+ else if (copied.run.kind === "done") {
1042
+ const assessed = await assess(shop, "records", judging, others, permitted, table, copied.run);
1043
+ if ("cannot" in assessed)
1044
+ return { name, cannot: assessed.cannot };
1045
+ if (shop.keep !== null)
1046
+ keepSequences(shop.keep, "records", assessed, copied.run);
1047
+ code = assessed.code;
1048
+ if (assessed.notRepeated !== null)
1049
+ causes.push(assessed.notRepeated);
1050
+ causes.push(...copied.run.short, ...assessed.causes);
1051
+ }
1052
+ // 6. The same on a copy with each kept fault. A fault is caught
1053
+ // only where TLC found a record the rule forbids. Without a copy of
1054
+ // the project's code there is no digest to hold a fault's copy to,
1055
+ // so no fault is tried (guards-24).
1056
+ const without = digest === null && copied.run.kind === "binding" ? copied.run.cause : null;
1057
+ for (const fault of without === null ? [] : guard.faults) {
1058
+ faults.push({ name: fault.name, tried: false, caught: null, reason: `the binding failed: ${without}` });
1059
+ }
1060
+ for (const fault of without === null ? guard.faults : []) {
1061
+ const patched = await runCopy(shop, sequences, fault, copied.state ?? null);
1062
+ const notCaught = (reason) => {
1063
+ faults.push({ name: fault.name, tried: true, caught: null, reason });
1064
+ };
1065
+ const made = patched.run;
1066
+ if (patched.digest === null && made.kind === "binding") {
1067
+ faults.push({ name: fault.name, tried: false, caught: null, reason: `the binding failed: ${made.cause}` });
1068
+ }
1069
+ else if (made.kind === "patch")
1070
+ notCaught(`the patch does not apply: ${made.cause}`);
1071
+ else if (made.kind === "nothing")
1072
+ notCaught("the patch changes nothing");
1073
+ else if (made.kind === "binding")
1074
+ notCaught(`the binding failed: ${made.cause}`);
1075
+ else if (made.kind === "timeout")
1076
+ notCaught(`a timeout: not done after ${seconds(limits.seconds)}`);
1077
+ else {
1078
+ const folder = `records-${fault.name}`;
1079
+ const assessed = await assess(shop, folder, judging, others, permitted, table, made);
1080
+ if ("cannot" in assessed)
1081
+ return { name, cannot: assessed.cannot };
1082
+ if (shop.keep !== null)
1083
+ keepSequences(shop.keep, folder, assessed, made);
1084
+ const found = assessed.code.violation;
1085
+ if (found !== null)
1086
+ faults.push({ name: fault.name, tried: true, caught: found, reason: null });
1087
+ else {
1088
+ const reason = faultReason(guard, made, assessed);
1089
+ faults.push({ name: fault.name, tried: true, caught: null, reason, dispute: reason === assessed.unsettled ? assessed.dispute : null });
1090
+ }
1091
+ }
1092
+ }
1093
+ }
1094
+ // Proofs not accepted leave the checks short, after what the code
1095
+ // left short.
1096
+ if (proofs.kind === "not accepted")
1097
+ causes.push({ kind: "proofs", reason: proofs.reason });
1098
+ // The one result, the highest row found (guards-23). A record not
1099
+ // judged for any cause leaves the result Inconclusive.
1100
+ const withModule = code !== null && code.kind !== "probes";
1101
+ const complete = code !== null && (!withModule || (code.tested === code.steps && code.casesAsStated === code.cases));
1102
+ const result = model.kind === "conflict"
1103
+ ? "Conflict in the items"
1104
+ : code?.violation != null
1105
+ ? "Violated on the code"
1106
+ : code?.difference != null
1107
+ ? "Code differs from the model"
1108
+ : code !== null && code.failed.length > 0
1109
+ ? "Case failed"
1110
+ : causes.length > 0 || !complete || code?.notReached !== 0 || code?.notJudged !== 0 || code?.counts.notJudged !== 0
1111
+ ? "Inconclusive"
1112
+ : PASSING;
1113
+ // Whether it passes (guards-25).
1114
+ const system = shop.tools.proof;
1115
+ const proof = system.kind === "found"
1116
+ ? { version: system.version, solvers: system.solvers, variable: system.variable, pinned: system.pinned }
1117
+ : null;
1118
+ const reasons = [];
1119
+ if (!approval.approved)
1120
+ reasons.push("not approved");
1121
+ if (casesFailed)
1122
+ reasons.push("the check of cases without the code failed");
1123
+ if (translations.length < 2)
1124
+ reasons.push("only one translation");
1125
+ if (compared?.kind === "differ")
1126
+ reasons.push("the translations differ");
1127
+ if (compared?.kind === "not compared")
1128
+ reasons.push("the translations were not compared");
1129
+ if (result !== PASSING)
1130
+ reasons.push(`the result is ${result}`);
1131
+ if (faults.length === 0)
1132
+ reasons.push("no kept fault");
1133
+ for (const fault of faults) {
1134
+ if (fault.caught === null)
1135
+ reasons.push(`kept fault ${fault.name} not ${fault.tried ? "caught" : "tried"}`);
1136
+ }
1137
+ return {
1138
+ name,
1139
+ behavior: guard.items.behavior.id,
1140
+ statement: guard.items.behavior.statement,
1141
+ approval,
1142
+ cases: {
1143
+ count: guard.cases.length,
1144
+ permitted: guard.cases.filter((entry) => entry.kind === "permitted").length,
1145
+ forbidden: guard.cases.filter((entry) => entry.kind === "forbidden").length,
1146
+ translations: translations.map((translation) => translation.name),
1147
+ failures,
1148
+ },
1149
+ compared,
1150
+ judging: judging.name,
1151
+ model: model.kind === "checked"
1152
+ ? {
1153
+ kind: "checked",
1154
+ states: model.table.paths.size,
1155
+ steps: model.table.rows.length,
1156
+ applied: model.applied,
1157
+ collision: model.collision,
1158
+ }
1159
+ : model,
1160
+ proofs,
1161
+ code,
1162
+ notTested,
1163
+ result,
1164
+ causes,
1165
+ assumes: assumptions(proof, guard.binding.kind, Object.keys(guard.binding.vocabulary.orders).length > 0),
1166
+ versions: {
1167
+ spex: spexVersion(),
1168
+ node: process.versions.node,
1169
+ tlc: shop.version.tlc,
1170
+ pinned: shop.tools.pinned,
1171
+ java: shop.tools.javaVersion,
1172
+ proof,
1173
+ },
1174
+ revision: revised ?? revision(root, [...guard.binding.files, guard.binding.folder]),
1175
+ digest,
1176
+ limits,
1177
+ faults,
1178
+ reasons,
1179
+ };
1180
+ }
1181
+ /** The environment without an outer SPEX_RECORDS: only the test command is given one, by Spex. */
1182
+ function withoutRecords(env) {
1183
+ const rest = { ...env };
1184
+ delete rest.SPEX_RECORDS;
1185
+ return rest;
1186
+ }
1187
+ /** An entry's name as it stands where it is plain, else as JSON writes it, so no name a test chose adds a line to the report. */
1188
+ function printedName(name) {
1189
+ return /^[\x20-\x7e]+$/.test(name) ? name : JSON.stringify(name);
1190
+ }
1191
+ //# sourceMappingURL=verify.js.map