gdp-wired 0.43.0 → 0.45.0

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 (79) hide show
  1. package/README.md +8 -3
  2. package/dist/core/c/reader.js +22 -7
  3. package/dist/core/check.js +3 -2
  4. package/dist/core/cli.d.ts +7 -0
  5. package/dist/core/cli.js +184 -12
  6. package/dist/core/counts.d.ts +1 -1
  7. package/dist/core/counts.js +30 -12
  8. package/dist/core/data.d.ts +6 -1
  9. package/dist/core/data.js +894 -152
  10. package/dist/core/dsl.d.ts +2 -0
  11. package/dist/core/dsl.js +88 -10
  12. package/dist/core/effect-prims.d.ts +60 -0
  13. package/dist/core/effect-prims.js +625 -0
  14. package/dist/core/effect.d.ts +17 -1
  15. package/dist/core/effect.js +108 -4
  16. package/dist/core/ex/harness.exs +2 -0
  17. package/dist/core/ex/reader.exs +17 -1
  18. package/dist/core/exists.d.ts +15 -1
  19. package/dist/core/exists.js +263 -41
  20. package/dist/core/extract-c.d.ts +2 -0
  21. package/dist/core/extract-c.js +22 -13
  22. package/dist/core/extract-check.d.ts +7 -0
  23. package/dist/core/extract-check.js +57 -4
  24. package/dist/core/extract-ex.js +5 -5
  25. package/dist/core/extract-go-check.js +22 -17
  26. package/dist/core/extract-go.d.ts +3 -0
  27. package/dist/core/extract-go.js +24 -9
  28. package/dist/core/extract-jvm.js +68 -16
  29. package/dist/core/extract-print.js +3 -0
  30. package/dist/core/extract-py.js +5 -5
  31. package/dist/core/extract-rb.js +5 -5
  32. package/dist/core/extract-read.d.ts +8 -0
  33. package/dist/core/extract-read.js +55 -0
  34. package/dist/core/extract-rs.js +28 -25
  35. package/dist/core/extract-shapes.js +20 -0
  36. package/dist/core/extract-sol.js +23 -12
  37. package/dist/core/extract-step.d.ts +59 -3
  38. package/dist/core/extract-step.js +334 -64
  39. package/dist/core/extract-swift.js +22 -15
  40. package/dist/core/extract.d.ts +1 -0
  41. package/dist/core/extract.js +27 -2
  42. package/dist/core/fresh.d.ts +2 -2
  43. package/dist/core/fresh.js +7 -3
  44. package/dist/core/go/reader.go +7 -1
  45. package/dist/core/infer.js +113 -40
  46. package/dist/core/jvm/Harness.java +8 -1
  47. package/dist/core/jvm/JavaReader.java +10 -2
  48. package/dist/core/jvm/Jvm.java +18 -2
  49. package/dist/core/jvm/KtReader.java +60 -5
  50. package/dist/core/machine.d.ts +2 -0
  51. package/dist/core/machine.js +32 -6
  52. package/dist/core/py/harness.py +128 -24
  53. package/dist/core/py/reader.py +50 -5
  54. package/dist/core/rb/reader.rb +52 -5
  55. package/dist/core/rs/src/main.rs +10 -0
  56. package/dist/core/sol/Replay.sol +52 -0
  57. package/dist/core/sol/harness.py +511 -0
  58. package/dist/core/solver.js +5 -4
  59. package/dist/core/system.d.ts +62 -1
  60. package/dist/core/system.js +274 -6
  61. package/dist/core/transfer.js +17 -0
  62. package/dist/core/watch.js +1 -1
  63. package/dist/interchange/check.d.ts +18 -1
  64. package/dist/interchange/check.js +19 -12
  65. package/dist/interchange/cli.d.ts +2 -0
  66. package/dist/interchange/cli.js +45 -0
  67. package/dist/interchange/format.d.ts +5 -1
  68. package/dist/interchange/format.js +25 -9
  69. package/dist/kernel/cdcl.js +65 -14
  70. package/dist/kernel/epr.js +35 -5
  71. package/dist/kernel/kernel.d.ts +2 -0
  72. package/dist/kernel/kernel.js +67 -40
  73. package/dist/kernel/prove.d.ts +22 -0
  74. package/dist/kernel/prove.js +156 -7
  75. package/dist/kernel/reader.js +3 -2
  76. package/dist/lean-kernel/emit.d.ts +9 -3
  77. package/dist/lean-kernel/emit.js +170 -29
  78. package/dist/lean-kernel/library.js +1 -1
  79. package/package.json +12 -3
package/README.md CHANGED
@@ -177,7 +177,10 @@ All of these are proven automatically, and each proof is also a Lean theorem:
177
177
  a run of two fibers; `Effect.retry` and `Effect.repeat` inside a method are part of its step. A `Schedule` is a rule of
178
178
  its decisions (attempt, retries, delay, elapsed, done; exponential a `recur` function, jitter an input within its
179
179
  range), every combinator a fragment of one machine, checked by stepping Effect's own schedule
180
- (`examples/effect-retry.ts`, `examples/effect-stm.ts`). `conforms(rule, service)` runs a rule written by hand
180
+ (`examples/effect-retry.ts`, `examples/effect-stm.ts`). A `Queue` (bounded, dropping, sliding, unbounded) or a
181
+ `Semaphore` the service makes is modelled once, its own laws proven (bounded, nothing lost, FIFO, the permits) and
182
+ run beside Effect's own on random operations and fibers, so a law states only the service's own
183
+ (`examples/effect-queue.ts`: a worker pool, a release without its acquire refuted by a run). `conforms(rule, service)` runs a rule written by hand
181
184
  beside a running service (Effect's own Semaphore, a store), and `fromSchema(schema)` is a Schema's kind
182
185
  (`examples/effect.ts`; what is read and refused, with what Effect projects write, in `research/effect/README.md`).
183
186
  - **What nobody stated, looked for when the prover alone stops**: where `proveRule` or `proveSteps` doesn't prove the laws
@@ -561,7 +564,7 @@ Proving and checking: a law over 64 steps proves in about 5 s, and Lean checks i
561
564
  | `kernel/` | The trusted kernel and the untrusted prover, with soundness fuzz (`kernel.test.ts`, `history.test.ts`) |
562
565
  | `lean-kernel/` | The kernel's Lean twin, its soundness proofs, and the exported trees |
563
566
  | `examples/` | The builders at work: `domains/` (187 rules across 21 domains, each with laws and broken variants), `harness.ts` (the triple check), `readme.ts`, `guide.ts` (the guide's code), `groups.ts` (two groups decided at every pair), `budget.ts`, `gdp.ts` (gdp-ts's example, its checks proven), `exists.ts` (laws with "there exists"), `datatypes.ts` (records and variants), `lemmas.ts` (recurrences and their lemmas), `invoices.ts` (lists a request carries), `folds.ts` (folds over trees), `trees.ts` (trees and lists of lists in the state), `composition.ts`, `sets.ts`, `quantifiers.ts`, `functions.ts`, `arith.ts` (division and remainder by a constant, integers in rules and datatypes), `lists.ts`, `sizes.ts`, `liveness.ts`, `steps.ts` (laws over up to 64 steps), and `jev-fabric/` (a Bend project's 59 proven laws, ported) |
564
- | `docs/` | The comparison with Bend and Lean, and the full scope |
567
+ | `docs/` | [ARCHITECTURE.md](docs/ARCHITECTURE.md) (the trust boundaries and what guards each), [FRONTENDS.md](docs/FRONTENDS.md) (how a language's reader plugs in), [interchange.md](docs/interchange.md) (certificates as JSON, for checkers in other languages), the comparison with Bend and Lean |
565
568
  | `compare/` | The same three rules in gdp-wired, Bend and plain Lean, checked and measured |
566
569
  | `research/` | Everything around the library ([`research/README.md`](research/README.md)): the GPU searches (`search/`, `hw/`, `modal-gpu/`), invariant and rank synthesis (`synth/`), relational laws and guard synthesis (`next/`), bit-vector laws (`sat/`), the enumeration and benchmarks (`enum/`, `gpu/`, `perf/`), the first Lean checker (`lean/`) and the first prototype, the audit path (`audit/`) |
567
570
  | `supercomputer/` | Everything above as jobs on boat (a warm pool), Modal and RunPod: `suite.json` is the regression suite (`modal/` links here until every lane has merged the rename) |
@@ -578,7 +581,9 @@ The npm package is the library: the builders (`gdp-wired`), the runtimes (`gdp-w
578
581
  `typescript` installed), Effect services (`gdp-wired/effect`, with `typescript` and `effect`), lemmas nobody stated (`gdp-wired/discover`), invariant
579
582
  inference (`gdp-wired/infer`), the
580
583
  Lean export (`gdp-wired/lean`), the kernel (`gdp-wired/kernel`), the prover (`gdp-wired/prove`), the derivation checker
581
- and solver (`gdp-wired/check`, `gdp-wired/solver`). Everything else here (examples, comparisons, the Lean twin, the GPU
584
+ and solver (`gdp-wired/check`, `gdp-wired/solver`), and the interchange reader and checker (`gdp-wired/interchange`, with
585
+ the `gdp-wired-check` bin: `npx -p gdp-wired gdp-wired-check cert.json` checks a certificate `gdp-wired check --cert`
586
+ wrote with the kernel alone, no search). Everything else here (examples, comparisons, the Lean twin, the GPU
582
587
  searches) runs from a clone and needs [Bun](https://bun.sh); Lean 4.34.0 for `lean/` and `lean-kernel/`; a WebGPU
583
588
  runtime (Chrome, or Dawn's node bindings) for the GPU parts. Releases: bump `version` in `package.json` and push to
584
589
  main; `.github/workflows/publish.yml` publishes it with npm provenance.
@@ -1,4 +1,4 @@
1
- import { Refusal } from "../extract-read.js";
1
+ import { Refusal, readerRun, statedRefusal } from "../extract-read.js";
2
2
  // (consecutive JSON values in one string, each with where it ends)
3
3
  class JSONDecoder {
4
4
  decode(s, i) {
@@ -31,10 +31,13 @@ export function clangDump(file, flags, clang = 'clang', cpp = false, filter) {
31
31
  const cp = node('node:child_process'), lang = cpp ? ['-x', 'c++'] : ['-x', 'c'];
32
32
  const run = (args) => {
33
33
  try {
34
- return cp.execFileSync(clang, args, { encoding: 'utf8', maxBuffer: 1 << 30, stdio: ['ignore', 'pipe', 'pipe'] });
34
+ return cp.execFileSync(clang, args, { encoding: 'utf8', maxBuffer: 1 << 30, stdio: ['ignore', 'pipe', 'pipe'], ...readerRun() });
35
35
  }
36
36
  catch (e) {
37
37
  const x = e;
38
+ const stated = statedRefusal(e);
39
+ if (stated)
40
+ throw new Refusal(file, stated);
38
41
  throw new Refusal(file, x.code === 'ENOENT' ? `no ${clang} to run: clang is needed to extract ${cpp ? 'C++' : 'C'}` : `clang doesn't compile it (${String(x.stderr ?? x.message).split('\n').filter(l => /error/.test(l)).slice(0, 3).join(' | ')})`);
39
42
  }
40
43
  };
@@ -198,11 +201,17 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
198
201
  cxx.push(n);
199
202
  }
200
203
  };
204
+ // A literal's value exactly, through parentheses.
205
+ const exact = (n) => n.kind === 'IntegerLiteral' ? BigInt(String(n.value)) : n.kind === 'ParenExpr' ? exact(n.inner[0]) : undefined;
201
206
  // A constant's value, where the node is one (literals, enum constants, a const global's, folded).
202
207
  const fold = (n) => {
203
208
  switch (n.kind) {
209
+ // (a literal a double can't hold exactly: NaN, past 2^53, unless a cast takes it exactly)
204
210
  case 'IntegerLiteral':
205
- case 'CharacterLiteral': return Number(n.value);
211
+ case 'CharacterLiteral': {
212
+ const v = Number(n.value);
213
+ return Number.isSafeInteger(v) ? v : NaN;
214
+ }
206
215
  case 'CXXBoolLiteralExpr': return n.value ? 1 : 0;
207
216
  case 'CallExpr': {
208
217
  const m = /numeric_limits<\s*(.+?)\s*>::(max|min|lowest)\)?\s*\(\s*\)$/.exec(text(n)), it = m ? T(parseT(m[1])) : undefined;
@@ -217,11 +226,13 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
217
226
  case 'CStyleCastExpr':
218
227
  case 'CXXStaticCastExpr':
219
228
  case 'CXXFunctionalCastExpr': {
220
- const v = fold(n.inner[0]), t = n.type ? T(tyOf(n.type)) : undefined;
229
+ const b = exact(n.inner[0]), v = b !== undefined ? Number(b) : fold(n.inner[0]), t = n.type ? T(tyOf(n.type)) : undefined;
221
230
  if (v === undefined || t?.k !== 'int')
222
231
  return n.castKind === 'IntegralToBoolean' && v !== undefined ? +(v !== 0) : undefined;
232
+ if (b === undefined && !Number.isFinite(v))
233
+ return NaN;
223
234
  // (exactly: at 64 bits 2^64 + 1 is 2^64 in a double)
224
- const m = 1n << BigInt(t.bits), w = ((BigInt(Math.trunc(v)) % m) + m) % m;
235
+ const m = 1n << BigInt(t.bits), w = (((b ?? BigInt(Math.trunc(v))) % m) + m) % m;
225
236
  return Number(t.signed && w >= m / 2n ? w - m : w);
226
237
  }
227
238
  case 'UnaryOperator': {
@@ -367,9 +378,13 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
367
378
  for (const m of cxx) {
368
379
  if (m.$rec !== entryRec)
369
380
  continue;
381
+ // (a constructor the check can't call, private or protected: refused, the object is made with it)
370
382
  if (m.kind === 'CXXConstructorDecl') {
371
- if (!/\((const )?\w+ &&?\)/.test(m.type.qualType) || params(m).length !== 1)
383
+ if (!/\((const )?\w+ &&?\)/.test(m.type.qualType) || params(m).length !== 1) {
384
+ if (m.$access !== 'public')
385
+ refuse(m, `${entry}: its constructor is ${String(m.$access)} (the check makes the object with it)`);
372
386
  ctors.push(m);
387
+ }
373
388
  continue;
374
389
  }
375
390
  if (m.kind !== 'CXXMethodDecl' || /^operator/.test(m.name))
@@ -761,7 +776,7 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
761
776
  if (c.inner.length > 2)
762
777
  return void cases.push({ p: pos(c), b: sno(c, 'a case range (a GNU extension)') });
763
778
  const v = fold(c.inner[0]);
764
- cases.push({ p: pos(c), list: [v === undefined ? no(c, 'a case that isn\'t a constant') : lit(c, v, tt)], b: [] });
779
+ cases.push({ p: pos(c), list: [v === undefined ? no(c, 'a case that isn\'t a constant') : !Number.isSafeInteger(v) ? no(c, 'a case past 2^53 (the rule\'s numbers stop there)') : lit(c, v, tt)], b: [] });
765
780
  return c.inner[1];
766
781
  }
767
782
  if (c.kind === 'DefaultStmt') {
@@ -17,7 +17,8 @@ export function checkRefutation(constraints, steps, integral = true) {
17
17
  return false;
18
18
  if (!integral && !(Number.isInteger(s.a) && Number.isInteger(s.b) && s.a >= 0 && s.b >= 0))
19
19
  return false;
20
- const out = {};
20
+ // (on no prototype: a row's variable named __proto__ is summed like any other, never dropped)
21
+ const out = Object.create(null);
21
22
  // Each product safe too: a rounded one is past 2^53, but the other row's could bring the sum back under it.
22
23
  for (const [lin, m] of [[rows[s.a], s.ma], [rows[s.b], s.mb]])
23
24
  for (const [key, c] of Object.entries(lin)) {
@@ -48,7 +49,7 @@ export function checkWitness(constraints, witness) {
48
49
  return constraints.every(c => {
49
50
  let sum = 0;
50
51
  for (const [key, a] of Object.entries(c.lin)) {
51
- const value = key === '1' ? 1 : witness[key], term = a * value;
52
+ const value = key === '1' ? 1 : Object.hasOwn(witness, key) ? witness[key] : undefined, term = a * value;
52
53
  if (!(Number.isSafeInteger(a) && Number.isSafeInteger(value) && Number.isSafeInteger(term) && Number.isSafeInteger(sum + term)))
53
54
  return false;
54
55
  sum += term;
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import type { Extraction, Name } from './extract.js';
3
3
  import { type Verdict } from './dsl.js';
4
+ import { type LawText } from './laws.js';
4
5
  export declare const colors: (env: Record<string, string | undefined>, tty: boolean, json?: boolean) => boolean;
5
6
  export type Opts = {
6
7
  entry?: string;
@@ -59,11 +60,17 @@ export type RuleOut = {
59
60
  notes: string[];
60
61
  names: Name[];
61
62
  checked?: string;
63
+ env?: string[];
62
64
  laws: LawOut[];
63
65
  proposed: LawOut[];
64
66
  brokenProposed?: number;
65
67
  source?: string;
66
68
  };
69
+ type Scoped = LawText & {
70
+ cls?: string;
71
+ fn?: string;
72
+ };
73
+ export declare function scoped(file: string): Scoped[];
67
74
  export declare function checkTarget(t: Target, o: Opts): Promise<RuleOut[]>;
68
75
  export declare function runOf(x: Extraction, run: NonNullable<Verdict['run']>): string[];
69
76
  export declare const proposedLaws: (x: Extraction, lang: Lang, ms?: number) => {
package/dist/core/cli.js CHANGED
@@ -10,6 +10,7 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
10
10
  import { proveLeadsTo, proveRule, proveSteps } from "./dsl.js";
11
11
  import { LawError, buildLaw, buildLeadsTo, buildTwoRuns, citesIn, isLeadsTo, isTwoRuns, lawsIn, namesWithClock } from "./laws.js";
12
12
  import { certify, proveTwoRuns } from "./relational.js";
13
+ import { contend, envOf, inEnv, shrinkRun } from "./system.js";
13
14
  const proc = globalThis.process;
14
15
  const fs = proc.getBuiltinModule('node:fs'), path = proc.getBuiltinModule('node:path');
15
16
  const out = (s = '') => proc.stdout.write(`${s}\n`);
@@ -264,7 +265,7 @@ async function rulesOf(t, o, laws) {
264
265
  const more = [...new Set(laws.map(l => l.cls ?? l.fn).filter((n) => !!n && !have.has(n)))];
265
266
  if (!more.length)
266
267
  return got;
267
- const { json: _j, ms: _m, propose: _p, clock: _c, cert: _t, from: _fr, ...flags } = o;
268
+ const { json: _j, ms: _m, propose: _p, clock: _c, cert: _t, from: _fr, env: _e, ...flags } = o;
268
269
  void _j;
269
270
  void _m;
270
271
  void _p;
@@ -272,7 +273,7 @@ async function rulesOf(t, o, laws) {
272
273
  void _t;
273
274
  void _fr;
274
275
  const cfg = configFor(t.lang === 'go' || t.lang === 'rust' || fs.statSync(t.at).isDirectory() ? t.at : path.dirname(t.at));
275
- const { clock: _k, from: _f, ...shared } = cfg.all;
276
+ const { clock: _k, from: _f, env: _v, ...shared } = cfg.all;
276
277
  void _k;
277
278
  void _f;
278
279
  const keep = [...new Set(laws.flatMap(l => l.expr.match(/[A-Za-z_]\w*/g) ?? []))];
@@ -281,7 +282,7 @@ async function rulesOf(t, o, laws) {
281
282
  return [...got.filter(r => r.x.ok || r.entry || !extra.length), ...extra];
282
283
  }
283
284
  async function rulesOf0(t, o, laws) {
284
- const { json: _j, ms: _m, propose: _p, clock: _c, cert: _t, from: _fr, ...flags } = o;
285
+ const { json: _j, ms: _m, propose: _p, clock: _c, cert: _t, from: _fr, env: _e, ...flags } = o;
285
286
  void _j;
286
287
  void _m;
287
288
  void _p;
@@ -291,7 +292,7 @@ async function rulesOf0(t, o, laws) {
291
292
  // (the options: gdp.toml's for every rule, then the rule's own, then the flags; a rule found with no entry named is
292
293
  // read again where gdp.toml has options of its own for it)
293
294
  const cfg = configFor(t.lang === 'go' || t.lang === 'rust' || fs.statSync(t.at).isDirectory() ? t.at : path.dirname(t.at));
294
- const { clock: _k, from: _f, ...shared } = cfg.all;
295
+ const { clock: _k, from: _f, env: _v, ...shared } = cfg.all;
295
296
  void _f;
296
297
  void _k;
297
298
  // (the names the laws read, so an argument a law reads stays in the rule though the code ignores it)
@@ -332,7 +333,26 @@ async function rulesOf0(t, o, laws) {
332
333
  const fns = [...new Set(laws.filter(l => !l.cls && l.fn).map(l => l.fn))];
333
334
  return several.length || fns.length ? Promise.all([...several, ...fns].map(c => one(c))) : [first];
334
335
  }
335
- function scoped(file) {
336
+ // (a class statement's name: its keyword at the start of a line, after modifiers; never a word in a comment)
337
+ const classAt = (line) => {
338
+ const m = /^\s*(?:(?:export|default|public|private|protected|internal|abstract|final|sealed|open|data|static|partial|pub(?:\([^)]*\))?|unsafe)\s+)*(?:class|struct|actor|defmodule|module|object|impl(?:<[^>]*>)?|record|interface|contract)\s+([\w.:]+)|^\s*type\s+(\w+)\s+struct\b/.exec(line.replace(/(#|\/\/).*$/, ''));
339
+ return m ? (m[1] ?? m[2]).split(/[.:<]/).filter(Boolean).pop() : undefined;
340
+ };
341
+ // (a type written like a call declares a value, never a function: `mapping(address => uint256) public balances;`, its
342
+ // parentheses closed, then a name (after modifiers) and `;` or `=`; a function's qualifiers (const, override, ...) are no
343
+ // name. A law on such a value is on no function, nor is one followed by another class's statement before any.)
344
+ const declares = (code, open) => {
345
+ let d = 0, i = open;
346
+ for (; i < code.length; i++) {
347
+ if (code[i] === '(')
348
+ d++;
349
+ else if (code[i] === ')' && --d === 0)
350
+ break;
351
+ }
352
+ const m = /^\s*(?:[A-Za-z_$][\w$]*\s+)*([A-Za-z_$][\w$]*)\s*(?:;|=(?![=>]))/.exec(code.slice(i + 1));
353
+ return !!m && !/^(const|override|final|noexcept|volatile|default|delete)$/.test(m[1]);
354
+ };
355
+ export function scoped(file) {
336
356
  const text = fs.readFileSync(file, 'utf8'), lines = text.split('\n');
337
357
  return lawsIn(text, path.basename(file)).map(l => {
338
358
  let cls, fn;
@@ -340,10 +360,21 @@ function scoped(file) {
340
360
  // docstring's or a comment's prose; in Python, at an indentation that encloses the law's)
341
361
  const indent = (x) => /^\s*/.exec(x)[0].length, lawIndent = indent(lines[l.line - 1]), py = file.endsWith('.py');
342
362
  for (let i = l.line - 1; i >= 0 && !cls; i--) {
343
- const m = /^\s*(?:(?:export|default|public|private|protected|internal|abstract|final|sealed|open|data|static|partial|pub(?:\([^)]*\))?|unsafe)\s+)*(?:class|struct|actor|defmodule|module|object|impl(?:<[^>]*>)?|record|interface|contract)\s+([\w.:]+)|^\s*type\s+(\w+)\s+struct\b/.exec(lines[i].replace(/(#|\/\/).*$/, ''));
363
+ const m = classAt(lines[i]);
344
364
  if (m && (!py || indent(lines[i]) < lawIndent))
345
- cls = (m[1] ?? m[2]).split(/[.:<]/).filter(Boolean).pop();
365
+ cls = m;
366
+ }
367
+ // (a law right above a class statement, past comments, blank lines and annotations, is that class's: a contract's,
368
+ // a struct's, a class's, never its first member's; one indented inside a class above a class after it isn't)
369
+ let above;
370
+ for (let i = l.line; i < lines.length; i++) {
371
+ if (/^\s*(\/\/|\/?\*|#|@|--|$)/.test(lines[i]))
372
+ continue;
373
+ above = indent(lines[i]) >= lawIndent ? classAt(lines[i]) : undefined;
374
+ break;
346
375
  }
376
+ if (above)
377
+ return { ...l, cls: above };
347
378
  // (in TypeScript, a law right above a declaration of a value, a schedule's say, is that value's)
348
379
  let top = false;
349
380
  if (/\.[cm]?[jt]sx?$/.test(file)) {
@@ -357,10 +388,15 @@ function scoped(file) {
357
388
  }
358
389
  }
359
390
  let fnLine = -1;
360
- for (let i = l.line - 1; i < lines.length && !fn; i++) {
391
+ let onValue = false;
392
+ for (let i = l.line - 1; i < lines.length && !fn && !onValue; i++) {
361
393
  const code = i === l.line - 1 ? lines[i].replace(/(#|\/\/|--).*$/, '') : lines[i];
394
+ if (i >= l.line && classAt(code))
395
+ break;
362
396
  const m = /\b(?:def|defp|fn|fun|func|function)\s+(?:\([^)]*\)\s*)?(?:self\.)?(\w+)|^\s*(?:(?:public|private|protected|static|final|synchronized|async|override|open|suspend|inline|virtual|const|[\w<>[\],?]+)\s+)*(\w+)\s*\(/.exec(code);
363
- if (m && !/^(if|for|while|switch|return|catch|new)$/.test(m[1] ?? m[2])) {
397
+ if (m && !m[1] && declares(code, m.index + m[0].length - 1))
398
+ onValue = true;
399
+ else if (m && !/^(if|for|while|switch|return|catch|new)$/.test(m[1] ?? m[2])) {
364
400
  fn = m[1] ?? m[2];
365
401
  fnLine = i;
366
402
  }
@@ -396,7 +432,8 @@ export async function checkTarget(t, o) {
396
432
  const others = Object.fromEntries(rules.filter(r => r.x.ok).map(r => [r.entry ?? r.x.model?.name ?? '', r.x]));
397
433
  const cfg = configFor(t.lang === 'go' || t.lang === 'rust' || fs.statSync(t.at).isDirectory() ? t.at : path.dirname(t.at));
398
434
  const ctx = { ms: o.ms, clock: unit === 's' ? 1 : unit === 'ms' ? 1000 : undefined, others, cites, cert: o.cert, file: path.relative(proc.cwd(), t.at) || t.at };
399
- for (const { entry, x } of rules) {
435
+ for (const { entry, x: x0 } of rules) {
436
+ let x = x0;
400
437
  const name = entry ?? (x.model?.name || undefined);
401
438
  // (a target that is the working directory, a crate's or a package's: `.`)
402
439
  const r = { file: path.relative(proc.cwd(), t.at) || '.', lang: LANG_NAME[t.lang], ...(name ? { entry: name } : {}), ok: x.ok, refusals: x.refusals, notes: x.notes, names: x.names ?? [], laws: [], proposed: [], ...(x.source ? { source: x.source } : {}) };
@@ -413,6 +450,12 @@ export async function checkTarget(t, o) {
413
450
  r.laws = mine.map(l => ({ name: l.name, expr: l.expr, where: l.where, verdict: 'not read', why: 'the rule was refused', ms: 0 }));
414
451
  continue;
415
452
  }
453
+ // (an Effect service's primitives: the lemmas of their use proven first, each proven one beside every law)
454
+ if (x.lemmas?.length) {
455
+ const { withLemmas } = await import("./effect.js"), w = withLemmas(x, { ms: Math.max(o.ms, 30_000) });
456
+ x = w.x;
457
+ r.notes = [...r.notes, ...w.proven.map(n => `lemma proven, beside every law: ${n}`), ...w.unproven.map(n => `lemma not proven (left out): ${n}`)];
458
+ }
416
459
  const ev = x.evidence;
417
460
  if (ev)
418
461
  r.checked = `checked against ${'probes' in ev ? `the code: ${ev.requests} requests from the start, ${ev.fromStates} from drawn states, ${ev.probes.steps} from the prover's witnesses` : `XState's own actor: ${ev.events} events`}${ev.coverage.arms ? `, ${ev.coverage.hit} of ${ev.coverage.arms} branch arms` : ''}${'startsOutside' in ev && ev.startsOutside ? `; ${ev.startsOutside} starts whose constructor passes 2^53 - 1 left out (outside the rule's numbers: the claim is for starts within them)` : ''}`;
@@ -421,6 +464,32 @@ export async function checkTarget(t, o) {
421
464
  const methods = new Set([...(x.names ?? []).filter(n => n.method).map(n => n.method), ...(evSort?.k === 'choice' ? evSort.values : [])]);
422
465
  const stated = mine.map(l => ({ ...l, ...(l.fn && methods.has(l.fn) ? { method: l.fn } : {}) }));
423
466
  const proven = [];
467
+ // (the environment the code runs in: --env, gdp.toml's env for the rule or every rule, or a `gdp: env` comment in
468
+ // its class: every call at once at its isolation level, keys that expire, retries; its laws lifted to it)
469
+ const words = o.env ?? (name ? cfg.rules[name]?.env : undefined) ?? envTags(t.files, name) ?? cfg.all.env;
470
+ let sys;
471
+ if (words) {
472
+ try {
473
+ const m = x.rule.machine, stores = [...new Set((x.names ?? []).filter(n => n.map?.store && n.rule).map(n => n.rule))].map(b => Object.keys(m.maps ?? {}).filter(k => k === b || k.startsWith(`${b}.`))).filter(c => c.length);
474
+ const own = Object.keys(m.state).filter(k => (x.names ?? []).some(n => (n.role === 'failed' || n.role === 'result') && ((n.rule && (k === n.rule || k.startsWith(`${n.rule}$`))) || k === n.none)));
475
+ const ev = (x.names ?? []).find(n => n.role === 'method'), evSort = x.model?.inputs.find(v => v.name === x.model?.event)?.sort;
476
+ const failedVar = (x.names ?? []).find(n => n.role === 'failed')?.rule;
477
+ // (a flow the laws state where the env doesn't: at most one call between a and b is the flow a then b, a and a a
478
+ // call of a alone, holding once it did its work)
479
+ const env = envOf(words), bw = mine.map(l => /^at\s+most\s+one\s+call\s+between\s+([\w.]+)\s+and\s+([\w.]+)$/i.exec(l.expr.trim())).find(Boolean);
480
+ if (!env.flow && bw)
481
+ env.flow = bw[1] === bw[2] ? [bw[1]] : [bw[1], bw[2]];
482
+ sys = inEnv(x.rule, env, { stores, own, ...(ev && evSort?.k === 'choice' ? { method: { name: ev.rule, values: evSort.values } } : {}), ...(failedVar ? { failed: failedVar } : {}), args: (x.names ?? []).filter(n => n.role === 'input' && n.method && n.rule).map(n => ({ method: n.method, code: n.code, rule: n.rule })),
483
+ oks: [...(x.names ?? []).filter(n => n.role === 'result' && n.method && x.model?.state.find(v => v.name === n.rule)?.sort.k === 'bool').map(n => ({ method: n.method, rule: n.rule })),
484
+ // (a method that makes an effect did its work where it made it: a charge, a handled message)
485
+ ...Object.entries(x.read?.effectsOf ?? {}).flatMap(([method, vs]) => vs.map(rule => ({ method, rule })))] });
486
+ r.env = sys.models.map(md => `${md.name}: ${md.assumes}`);
487
+ }
488
+ catch (e) {
489
+ r.laws = mine.map(l => ({ name: l.name, expr: l.expr, where: l.where, verdict: 'not read', why: `the environment: ${e.message}`, ms: 0 }));
490
+ continue;
491
+ }
492
+ }
424
493
  // (a law is known by its name: a name stated twice in one rule is refused, both times)
425
494
  const twice = (l) => stated.filter(m => m.name === l.name).map(m => m.where);
426
495
  // (from = "any": every law proven from every state the laws allow, not only those a run from the start reaches, for
@@ -440,12 +509,12 @@ export async function checkTarget(t, o) {
440
509
  const order = [...stated.keys()].sort((a, b) => rank(stated[a]) - rank(stated[b]));
441
510
  // (from any state, the laws about states as one inductive set: the largest the stated ones make, each law the
442
511
  // kernel's step breaks taken out in turn (Houdini), the others proven together; one taken out is judged alone)
443
- const inductive = from && x.rule ? houdini(x, stated.filter(m => twice(m).length === 1 && kindOf(m) === 'law'), o.ms, ctx.clock) : undefined;
512
+ const inductive = from && x.rule && !sys ? houdini(x, stated.filter(m => twice(m).length === 1 && kindOf(m) === 'law'), o.ms, ctx.clock) : undefined;
444
513
  const outsOf = [];
445
514
  for (const i of order) {
446
515
  const l = stated[i];
447
516
  outsOf[i] = twice(l).length > 1 ? { name: l.name, expr: l.expr, where: l.where, verdict: 'not read', why: `a law of this name is stated twice (${twice(l).join(', ')}): a law is known by its name`, ms: 0 }
448
- : prove(x, l, o.ms, proven, { ...ctx, entry: name, ...(from ? { from, inductive, together: stated.filter(m => twice(m).length === 1 && kindOf(m) === 'law' && inductive.has(m.name)) } : {}) });
517
+ : sys ? proveInEnv(x, l, o.ms, proven, { ...ctx, sys, entry: name }) : prove(x, l, o.ms, proven, { ...ctx, entry: name, ...(from ? { from, inductive, together: stated.filter(m => twice(m).length === 1 && kindOf(m) === 'law' && inductive.has(m.name)) } : {}) });
449
518
  }
450
519
  r.laws = outsOf;
451
520
  if (o.propose && x.model) {
@@ -623,6 +692,104 @@ function prove(x0, l, ms, proven, ctx) {
623
692
  return { ...base, kind, verdict, ...(ctx?.from && verdict === 'proven' ? { from: 'any' } : {}), ...(replayed ? { replayed } : {}), ...(v.run && verdict === 'broken' ? { run: two ? pairRunOf(x, v.run, two) : runOf(x, v.run) } : {}), ...(verdict === 'unknown' || (verdict === 'broken' && !v.run) ? { why: [v.why ?? v.stuck ?? 'not proven', ...(at.length ? [`a state the laws allow where a step breaks it, no run from the start found reaching it: ${at.join(', ')}`] : [])].join('; ') } : {}),
624
693
  ...(v.run && !two ? { assumes: assumedOf(x, v.run) } : {}), ...(found?.length ? { found } : {}), ...(cert ? { cert } : {}), ms: Date.now() - t0 };
625
694
  }
695
+ // A law of a rule in its environment (core/system.ts's inEnv): built on the rule as the code's names read it, then
696
+ // lifted to every call at once; proven of the system, a run shown as the calls' steps.
697
+ function proveInEnv(x, l, ms, proven, ctx) {
698
+ const t0 = Date.now(), sys = ctx.sys, base = { name: l.name, expr: l.expr, ...(l.where ? { where: l.where } : {}) };
699
+ if (isLeadsTo(l.expr) || isTwoRuns(l.expr))
700
+ return { ...base, verdict: 'not read', why: `a ${isLeadsTo(l.expr) ? 'leads-to' : 'two-run'} law is not lifted to the environment (state it of the rule with no env)`, ms: 0 };
701
+ // (at most one call between a and b: a flow's mutual exclusion, its leases running out where their keys expire)
702
+ const bw = /^at\s+most\s+one\s+call\s+between\s+([\w.]+)\s+and\s+([\w.]+)$/i.exec(l.expr.trim());
703
+ let b;
704
+ try {
705
+ b = bw ? { kind: 'law', law: sys.between(l.name, bw[1], bw[2]) } : buildLaw(x, l, { clock: ctx.clock });
706
+ }
707
+ catch (e) {
708
+ return { ...base, verdict: 'not read', why: e.message, ms: 0 };
709
+ }
710
+ const inv = (x.invariants ?? []).map(sys.law);
711
+ let v, law;
712
+ try {
713
+ if (b.kind === 'law') {
714
+ law = bw ? b.law : sys.law(b.law);
715
+ v = proveRule(sys.rule, [...inv, law], { search: { ms } });
716
+ }
717
+ else {
718
+ law = sys.step(b.law);
719
+ v = proveSteps(sys.rule, [...inv, ...proven], [law], { search: { ms } });
720
+ }
721
+ }
722
+ catch (e) {
723
+ return { ...base, kind: b.kind, verdict: 'unknown', why: e.message, ms: Date.now() - t0 };
724
+ }
725
+ // (not proven and no run: calls contending with one request, a run the search's own draws seldom make)
726
+ if (!(v.proven && v.checked) && !v.run) {
727
+ const run = contend(sys, law, { ms: Math.min(ms, 10_000) });
728
+ if (run)
729
+ v = { ...v, run: run };
730
+ }
731
+ const verdict = v.proven && v.checked ? 'proven' : v.run ? 'broken' : 'unknown';
732
+ if (verdict === 'proven' && b.kind === 'law')
733
+ proven.push(law);
734
+ const found = v.found?.laws?.map(f => f.text);
735
+ return { ...base, kind: b.kind, verdict, ...(v.run && verdict === 'broken' ? { run: sysRunOf(x, sys, shrinkRun(sys.rule, law, v.run)) } : {}), ...(verdict === 'unknown' ? { why: v.why ?? v.stuck ?? 'not proven' } : {}), ...(found?.length ? { found } : {}), ms: Date.now() - t0 };
736
+ }
737
+ // A run of the system as each call's steps: a call begins with its request, reads, commits; a store's key expires.
738
+ function sysRunOf(x, sys, run) {
739
+ const pcs = new Map(), done = (sys.commit ?? 0) + 1, out = [];
740
+ const params = Object.keys(run.params).length ? runOf(x, { params: run.params, trace: [] }) : [];
741
+ // (calls numbered in the order they begin; a store by the code's name)
742
+ const ids = new Map(), n = (p) => { if (!ids.has(p))
743
+ ids.set(p, ids.size + 1); return ids.get(p); };
744
+ const store = (map) => (x.names ?? []).find(m => m.rule === map)?.code ?? map;
745
+ for (const q of run.trace) {
746
+ const a = q[sys.act];
747
+ if (!(a === 0 || a === sys.part)) {
748
+ out.push(`a key of the store expires (key #${String(q['key$'])})`);
749
+ continue;
750
+ }
751
+ const call = runOf(x, { params: {}, trace: [q] }).at(-1);
752
+ if (!sys.id) {
753
+ out.push(call);
754
+ continue;
755
+ }
756
+ const p = q[sys.id], pc = pcs.get(p) ?? 0;
757
+ if (!sys.commit) {
758
+ out.push(`call ${n(p)}: ${call}`);
759
+ continue;
760
+ }
761
+ if (pc >= done)
762
+ continue;
763
+ pcs.set(p, pc === 0 ? (sys.level === 'snapshot' || sys.commit === 1 ? sys.commit : 1) : pc === sys.commit && sys.flow ? 0 : pc + 1);
764
+ out.push(pc === 0 ? `call ${n(p)} begins ${call}` : pc === sys.commit ? `call ${n(p)} commits` : `call ${n(p)} reads ${store(sys.reads[pc - 1])}`);
765
+ }
766
+ return [...params, ...out];
767
+ }
768
+ // The environment a `gdp: env <words>` comment states: one in the rule's class (or naming none, the file's).
769
+ const ENV = /(?:#|\/\/|--|%|\/\*|^\s*\*)\s*gdp:\s*env\s+(.+?)\s*(?:\*\/)?\s*$/;
770
+ function envTags(files, name) {
771
+ for (const f of files) {
772
+ const lines = fs.readFileSync(f, 'utf8').split('\n');
773
+ for (const [i, l] of lines.entries()) {
774
+ const m = ENV.exec(l);
775
+ if (!m)
776
+ continue;
777
+ // (a tag right above a class statement is that class's, else the class it is in)
778
+ let cls;
779
+ for (let j = i + 1; j < lines.length; j++) {
780
+ if (/^\s*(\/\/|\/?\*|#|@|$)/.test(lines[j]))
781
+ continue;
782
+ cls = classAt(lines[j]);
783
+ break;
784
+ }
785
+ for (let j = i; j >= 0 && !cls; j--)
786
+ cls = classAt(lines[j]);
787
+ if (!cls || !name || cls === name)
788
+ return m[1];
789
+ }
790
+ }
791
+ return undefined;
792
+ }
626
793
  // Two runs as calls of the code: each request once, the values the two runs take apart as `a | b`, and the run b leaves
627
794
  // out (isolation's: the others' calls) marked.
628
795
  function pairRunOf(x, run, two) {
@@ -762,6 +929,11 @@ function printRule(r, o) {
762
929
  else {
763
930
  if (r.checked)
764
931
  out(` ${paint('dim', r.checked)}`);
932
+ if (r.env) {
933
+ out(' in its environment (every call at once; the laws below are about these runs):');
934
+ for (const e of r.env)
935
+ out(` ${e}`);
936
+ }
765
937
  const inferred = r.notes.filter(n => /inferred|tagged|left out|answered|injected|the entry/.test(n));
766
938
  for (const n of inferred.slice(0, 12))
767
939
  out(` ${n}`);
@@ -27,7 +27,7 @@ export type Tried<P> = {
27
27
  } | {
28
28
  stuck: string;
29
29
  };
30
- export declare function cone<P>(m: Machine, set: Law[], attempt: (law: Law, ls: Law[], ms: number) => Tried<P>, until: number): Map<string, P>;
30
+ export declare function cone<P>(m: Machine, set: Law[], attempt: (law: Law, ls: Law[], ms: number) => Tried<P>, until: number, houdini?: boolean): Map<string, P>;
31
31
  export type Counted = {
32
32
  proven: boolean;
33
33
  laws: Law[];
@@ -221,8 +221,8 @@ export function candidates(src, m, caller, shapes, guarded, ms, until) {
221
221
  console.error(`counts: ${kinds.length + guarded.length + rowLaws.length + cubes.length - out.length} candidates said before or false on the small instances`);
222
222
  return out;
223
223
  }
224
- export function cone(m, set, attempt, until) {
225
- const kept = new Map(), inCone = (l) => kept.has(l.name), tried = new Map(), times = new Map(), asked = new Set();
224
+ export function cone(m, set, attempt, until, houdini = false) {
225
+ const kept = new Map(), inCone = (l) => kept.has(l.name), tried = new Map(), times = new Map(), asked = new Set(), slow = new Set();
226
226
  const stopAt = until - (until - clock()) / 3, brief = (stopAt - clock()) / Math.max(1, set.length);
227
227
  // (the maps a law reads, a count's through its body)
228
228
  const mapsOf = (l) => new Set([...reads(l.holds, () => true).values()].flatMap(([mp]) => [mp, ...(m.counts?.[mp] ? [...reads(m.counts[mp].body, () => true).values()].map(([q]) => q) : [])]));
@@ -233,7 +233,7 @@ export function cone(m, set, attempt, until) {
233
233
  grew = false;
234
234
  for (const law of set) {
235
235
  const id = `${t} ${law.name}`;
236
- if (kept.has(law.name) || tried.get(id) === kept.size || (t === 0 && tried.has(id)) || (t === 2 && (times.get(law.name) ?? 0) >= 2) || clock() > stopAt)
236
+ if (kept.has(law.name) || tried.get(id) === kept.size || (t === 0 && tried.has(id)) || (t === 2 && ((times.get(law.name) ?? 0) >= 2 || slow.has(law.name))) || clock() > stopAt)
237
237
  continue;
238
238
  tried.set(id, kept.size);
239
239
  if (t === 2)
@@ -248,6 +248,10 @@ export function cone(m, set, attempt, until) {
248
248
  continue;
249
249
  asked.add(same);
250
250
  const r = attempt(law, ls, brief);
251
+ // (a law out of time over every kept law: tried again over more, its goals only grow; where Houdini follows, its
252
+ // share is larger)
253
+ if (houdini && t === 2 && 'stuck' in r && r.stuck !== 'sat')
254
+ slow.add(law.name);
251
255
  if ('proof' in r) {
252
256
  kept.set(law.name, r.proof);
253
257
  grew = any = true;
@@ -268,9 +272,14 @@ export function cone(m, set, attempt, until) {
268
272
  }
269
273
  // On the counted clock (kernel/prove.ts's `counted`, the cost model's work at fullRate a millisecond), as the engine's
270
274
  // search is: what a budget lets it try, and so its verdict, is the same on a slow or shared machine as on a fast one; the
271
- // wall a stop only at twice the budget.
275
+ // wall a stop only at twice the budget. The small instances (exists.ts's smallOf) are read before the wall starts: their
276
+ // search is bounded by its own count of steps, on neither clock, and took 3.6 to 5.2 s of an 8 s budget's 16 s wall on
277
+ // a boat VM (exists.test.ts's two counts), so a shared VM crossed the wall before the search began and left every goal
278
+ // unknown (2 runs in 4 on main; 4 in 4 beside three busy loops).
272
279
  export function searchCounted(m0, caller, ms = 60_000) {
273
- const run = () => withWall(performance.now() + 2 * ms, () => counted(fullRate, () => searchCounted0(m0, caller, ms), true));
280
+ const g = guardLaws(m0), m = { ...m0, counts: { ...m0.counts, ...g.counts } };
281
+ ptime('small', () => smallOf(m));
282
+ const run = () => withWall(performance.now() + 2 * ms, () => counted(fullRate, () => searchCounted0(m0, g, m, caller, ms), true));
274
283
  if (!env.GDP_COUNTS_PROF)
275
284
  return run();
276
285
  cdclStats.on = true;
@@ -278,8 +287,8 @@ export function searchCounted(m0, caller, ms = 60_000) {
278
287
  console.error(`counts: prof total ${Math.round(performance.now() - t)} ms; ${Object.entries(cprof).map(([k2, x]) => `${k2} ${Math.round(x)}`).join(', ')}; cdcl runs ${cdclStats.runs} conflicts ${cdclStats.conflicts} decisions ${cdclStats.decisions} solveMs ${Math.round(cdclStats.solveMs)} rowsMs ${Math.round(cdclStats.rowsMs)} coreMs ${Math.round(cdclStats.coreMs)} unfoldMs ${Math.round(cdclStats.unfoldMs)} lpMs ${Math.round(cdclStats.lpMs)} boundMs ${Math.round(cdclStats.boundMs)} orderMs ${Math.round(cdclStats.orderMs)}`);
279
288
  return out;
280
289
  }
281
- function searchCounted0(m0, caller, ms = 60_000) {
282
- const until = clock() + ms, g = guardLaws(m0), m = { ...m0, counts: { ...m0.counts, ...g.counts } };
290
+ function searchCounted0(m0, g, m, caller, ms) {
291
+ const until = clock() + ms;
283
292
  if (!caller.every(l => clock() < until && trueSmall(m, [l])))
284
293
  return { proven: false, laws: caller, m, why: clock() < until ? 'a law fails on the small instances' : 'time' };
285
294
  const t1 = clock();
@@ -302,13 +311,16 @@ function searchCounted0(m0, caller, ms = 60_000) {
302
311
  const models = new Map(), isCount = (mp) => !!m.counts?.[mp];
303
312
  const attempt = (law, ls, pass, ms) => {
304
313
  const ts = terms(law), id = `${pass} ${law.name}`, cti = models.get(id);
314
+ // (the model broken: the attempt starts at the instances it asks for, its last attempt's and the tuples the new laws
315
+ // break it at, where the rounds of models would lead it again)
316
+ let seed;
305
317
  if (cti && !ls.some(l => !cti.ls.has(l.name) && reads(l.holds, isCount).size)) {
306
318
  const at0 = Object.fromEntries(Object.entries(cti.at).filter(([n]) => n.startsWith('?') || ls.some(l => l.name === n)));
307
- if (!ptime('mbqi', () => modelInstances(m, ls, at0, cti.gg, cti.w)))
319
+ if (!(seed = ptime('mbqi', () => modelInstances(m, ls, at0, cti.gg, cti.w))))
308
320
  return { stuck: 'sat' };
309
321
  }
310
322
  const refuted = (gg, w) => { models.set(id, { gg, w, at, ls: new Set(ls.map(l => l.name)) }); return { stuck: 'sat' }; };
311
- let at = Object.fromEntries(Object.entries(m.step.flags ?? {}).flatMap(([f, q]) => (q.op === 'all' && !q.keys?.length ? [[`?${f}`, ts]] : [])));
323
+ let at = seed ?? Object.fromEntries(Object.entries(m.step.flags ?? {}).flatMap(([f, q]) => (q.op === 'all' && !q.keys?.length ? [[`?${f}`, ts]] : [])));
312
324
  const obligations = (i) => ptime('encode', () => countedObligations(m, ls, { [law.name]: i }, ls.indexOf(law)));
313
325
  const build = () => obligations(at).map(({ goal, decls }) => { const c = pass ? certFor(goal, decls) : none; return { goal, decls, c, gg: ptime('encode', () => mcGoal(goal.hyps, decls, c)) }; });
314
326
  let built = build();
@@ -400,7 +412,7 @@ function searchCounted0(m0, caller, ms = 60_000) {
400
412
  };
401
413
  // The cone (a law about no key is assumed in every goal, so with one in the set nothing is kept); with every caller
402
414
  // kept, the kept laws are the proof; else Houdini over the whole set, the kept laws' proofs reused.
403
- const kept = set.every(l => l.forall) ? cone(m, set, (law, ls, ms2) => traced(law, ls, 1, ms2), until) : new Map();
415
+ const kept = set.every(l => l.forall) ? cone(m, set, (law, ls, ms2) => traced(law, ls, 1, ms2), until, true) : new Map();
404
416
  if (env.GDP_COUNTS_TRACE)
405
417
  console.error(`counts: kept ${kept.size} of ${set.length} in ${Math.round(clock() - t1)} ms`);
406
418
  const finish = (ls, proof) => (ptime('kernel', () => checkCountedLaws(m, ls, proof)) ? { proven: true, laws: ls, m, proof } : { proven: false, laws: ls, m, why: 'the kernel refused the set' });
@@ -408,21 +420,24 @@ function searchCounted0(m0, caller, ms = 60_000) {
408
420
  if (caller.every(l => kept.has(l.name)))
409
421
  return finish(set.filter(l => kept.has(l.name)), keptProof());
410
422
  // (each law not kept an even share of what is left a round)
423
+ let carried = new Map();
411
424
  for (let round = 0; clock() < until; round++) {
412
- const { instances, certs } = keptProof(), failed = new Set(), share = (until - clock()) / Math.max(1, set.filter(l => !kept.has(l.name)).length);
425
+ const { instances, certs } = keptProof(), failed = new Set(), proofs = new Map(), share = (until - clock()) / Math.max(1, set.filter(l => !kept.has(l.name) && !carried.has(l.name)).length);
413
426
  // (the callers last, so they meet every support kept so far)
414
427
  for (const law of [...set.filter(l => !caller.includes(l)), ...set.filter(l => caller.includes(l))]) {
415
428
  if (clock() > until)
416
429
  return { proven: false, laws: set, m, why: 'time' };
417
430
  if (kept.has(law.name))
418
431
  continue;
419
- let r = traced(law, set, 0, share);
432
+ const was = carried.get(law.name);
433
+ let r = was ? { proof: was } : traced(law, set, 0, share);
420
434
  if (!('proof' in r) && counted)
421
435
  r = traced(law, set, 1, share);
422
436
  if (!('proof' in r)) {
423
437
  failed.add(law.name);
424
438
  continue;
425
439
  }
440
+ proofs.set(law.name, r.proof);
426
441
  instances[law.name] = r.proof.instances;
427
442
  Object.assign(certs, r.proof.certs);
428
443
  }
@@ -434,6 +449,9 @@ function searchCounted0(m0, caller, ms = 60_000) {
434
449
  // (only callers fail: drop nothing more, give up)
435
450
  if (next.length === set.length)
436
451
  return { proven: false, laws: set, m, why: `not proven: ${[...failed].join(', ')}` };
452
+ // (a proof that assumes no law dropped at any key is one over the rest: its goals are the same; the kernel checks all)
453
+ const dropped = set.filter(l => !next.includes(l));
454
+ carried = new Map([...proofs].filter(([, pr]) => dropped.every(d => d.forall && !pr.instances[d.name]?.length)));
437
455
  set = next;
438
456
  }
439
457
  return { proven: false, laws: set, m, why: 'time' };
@@ -262,6 +262,7 @@ export type Measure = {
262
262
  export type Termination = {
263
263
  measure: Measure;
264
264
  text: string;
265
+ invariant?: Y;
265
266
  obligations: {
266
267
  law: DataLaw;
267
268
  proof?: CyclicVerdict;
@@ -273,10 +274,14 @@ export type Termination = {
273
274
  };
274
275
  export declare const terminationMs: {
275
276
  ms: number;
277
+ }, guardedMs: {
278
+ ms: number;
276
279
  };
277
280
  export declare const showMeasure: (f: Pick<Fn, "params">, m: Measure) => string;
278
281
  export declare function measureX(f: Pick<Fn, 'params'>, c: Measure['comps'][number], args: X[]): X;
279
- export declare function checkMeasures(fns: Fn[], ms: Measure[], budget?: number): {
282
+ export type Inv = (Y | undefined)[];
283
+ export declare const valueVar: (f: Pick<Fn, "name">) => string;
284
+ export declare function checkMeasures(fns: Fn[], ms: Measure[], budget?: number, inv?: Inv): {
280
285
  proven: true;
281
286
  obligations: Termination['obligations'][];
282
287
  } | {