gdp-wired 0.42.0 → 0.44.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 (66) hide show
  1. package/README.md +14 -3
  2. package/dist/core/cli.d.ts +8 -1
  3. package/dist/core/cli.js +271 -30
  4. package/dist/core/counts.d.ts +8 -1
  5. package/dist/core/counts.js +171 -302
  6. package/dist/core/data.js +2 -2
  7. package/dist/core/dsl.js +26 -30
  8. package/dist/core/effect-prims.d.ts +60 -0
  9. package/dist/core/effect-prims.js +625 -0
  10. package/dist/core/effect-schedule.d.ts +103 -0
  11. package/dist/core/effect-schedule.js +817 -0
  12. package/dist/core/effect.d.ts +36 -1
  13. package/dist/core/effect.js +656 -29
  14. package/dist/core/ex/harness.exs +2 -0
  15. package/dist/core/exists.d.ts +5 -0
  16. package/dist/core/exists.js +98 -34
  17. package/dist/core/extract-c.d.ts +2 -0
  18. package/dist/core/extract-c.js +5 -3
  19. package/dist/core/extract-check.d.ts +2 -0
  20. package/dist/core/extract-check.js +45 -4
  21. package/dist/core/extract-ex.js +2 -2
  22. package/dist/core/extract-go-check.js +4 -6
  23. package/dist/core/extract-go.d.ts +3 -0
  24. package/dist/core/extract-go.js +4 -4
  25. package/dist/core/extract-jvm.js +6 -3
  26. package/dist/core/extract-print.js +9 -2
  27. package/dist/core/extract-py.js +2 -2
  28. package/dist/core/extract-rb.js +2 -2
  29. package/dist/core/extract-read.js +2 -1
  30. package/dist/core/extract-rs.js +12 -7
  31. package/dist/core/extract-sol.js +4 -4
  32. package/dist/core/extract-step.d.ts +18 -0
  33. package/dist/core/extract-step.js +135 -31
  34. package/dist/core/extract-swift.js +3 -3
  35. package/dist/core/extract.d.ts +8 -0
  36. package/dist/core/extract.js +13 -1
  37. package/dist/core/infer.d.ts +1 -0
  38. package/dist/core/infer.js +10 -7
  39. package/dist/core/jvm/Harness.java +8 -1
  40. package/dist/core/jvm/Jvm.java +1 -1
  41. package/dist/core/jvm/KtReader.java +3 -0
  42. package/dist/core/laws.d.ts +4 -0
  43. package/dist/core/laws.js +176 -9
  44. package/dist/core/machine.d.ts +3 -0
  45. package/dist/core/machine.js +17 -3
  46. package/dist/core/py/harness.py +64 -19
  47. package/dist/core/py/reader.py +51 -1
  48. package/dist/core/sol/Replay.sol +52 -0
  49. package/dist/core/sol/harness.py +508 -0
  50. package/dist/core/system.d.ts +44 -0
  51. package/dist/core/system.js +435 -0
  52. package/dist/interchange/check.d.ts +18 -1
  53. package/dist/interchange/check.js +9 -2
  54. package/dist/interchange/cli.d.ts +2 -0
  55. package/dist/interchange/cli.js +45 -0
  56. package/dist/interchange/format.d.ts +1 -1
  57. package/dist/interchange/format.js +15 -7
  58. package/dist/kernel/cdcl.js +32 -12
  59. package/dist/kernel/kernel.js +3 -2
  60. package/dist/kernel/prove.d.ts +1 -0
  61. package/dist/kernel/prove.js +69 -8
  62. package/dist/kernel/reader.js +3 -2
  63. package/dist/lean-kernel/emit.js +3 -3
  64. package/dist/lean-kernel/lean-terms.d.ts +1 -0
  65. package/dist/lean-kernel/lean-terms.js +8 -4
  66. package/package.json +12 -3
package/README.md CHANGED
@@ -171,7 +171,16 @@ All of these are proven automatically, and each proof is also a Lean theorem:
171
171
  whose make effect creates Refs (Ref, SynchronizedRef, SubscriptionRef, 4.x's TxRef) and returns an object of methods
172
172
  (`Effect.fn` bodies, arrows returning an effect), with typed failures as its refusals and `Clock.currentTimeMillis` as
173
173
  an input; the rule is checked by running the service on Effect's runtime (the `effect` the file's project has,
174
- `Effect.runSyncExit`, the clock fixed at each request's time), every Ref, result and failure compared. `conforms(rule, service)` runs a rule written by hand
174
+ `Effect.runSyncExit`, the clock fixed at each request's time), every Ref, result and failure compared. Transactions
175
+ (3.x STM's TRef, 4.x `Effect.tx` over TxRefs) are atomic steps, waits (`STM.check`, `Effect.txRetry`) their guards,
176
+ and a method of several transactions is every fiber's steps (core/system.ts's `lift`), so a lost update comes back as
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
+ its decisions (attempt, retries, delay, elapsed, done; exponential a `recur` function, jitter an input within its
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`). 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
175
184
  beside a running service (Effect's own Semaphore, a store), and `fromSchema(schema)` is a Schema's kind
176
185
  (`examples/effect.ts`; what is read and refused, with what Effect projects write, in `research/effect/README.md`).
177
186
  - **What nobody stated, looked for when the prover alone stops**: where `proveRule` or `proveSteps` doesn't prove the laws
@@ -555,7 +564,7 @@ Proving and checking: a law over 64 steps proves in about 5 s, and Lean checks i
555
564
  | `kernel/` | The trusted kernel and the untrusted prover, with soundness fuzz (`kernel.test.ts`, `history.test.ts`) |
556
565
  | `lean-kernel/` | The kernel's Lean twin, its soundness proofs, and the exported trees |
557
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) |
558
- | `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 |
559
568
  | `compare/` | The same three rules in gdp-wired, Bend and plain Lean, checked and measured |
560
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/`) |
561
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) |
@@ -572,7 +581,9 @@ The npm package is the library: the builders (`gdp-wired`), the runtimes (`gdp-w
572
581
  `typescript` installed), Effect services (`gdp-wired/effect`, with `typescript` and `effect`), lemmas nobody stated (`gdp-wired/discover`), invariant
573
582
  inference (`gdp-wired/infer`), the
574
583
  Lean export (`gdp-wired/lean`), the kernel (`gdp-wired/kernel`), the prover (`gdp-wired/prove`), the derivation checker
575
- 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
576
587
  searches) runs from a clone and needs [Bun](https://bun.sh); Lean 4.34.0 for `lean/` and `lean-kernel/`; a WebGPU
577
588
  runtime (Chrome, or Dawn's node bindings) for the GPU parts. Releases: bump `version` in `package.json` and push to
578
589
  main; `.github/workflows/publish.yml` publishes it with npm provenance.
@@ -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;
@@ -35,7 +36,8 @@ type LawOut = {
35
36
  name: string;
36
37
  expr: string;
37
38
  where?: string;
38
- kind?: 'law' | 'step' | 'two runs';
39
+ kind?: 'law' | 'step' | 'two runs' | 'leads to';
40
+ from?: 'any';
39
41
  verdict: 'proven' | 'broken' | 'unknown' | 'not read';
40
42
  run?: string[];
41
43
  replayed?: string;
@@ -63,6 +65,11 @@ export type RuleOut = {
63
65
  brokenProposed?: number;
64
66
  source?: string;
65
67
  };
68
+ type Scoped = LawText & {
69
+ cls?: string;
70
+ fn?: string;
71
+ };
72
+ export declare function scoped(file: string): Scoped[];
66
73
  export declare function checkTarget(t: Target, o: Opts): Promise<RuleOut[]>;
67
74
  export declare function runOf(x: Extraction, run: NonNullable<Verdict['run']>): string[];
68
75
  export declare const proposedLaws: (x: Extraction, lang: Lang, ms?: number) => {
package/dist/core/cli.js CHANGED
@@ -7,8 +7,8 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
7
7
  }
8
8
  return path;
9
9
  };
10
- import { proveRule, proveSteps } from "./dsl.js";
11
- import { LawError, buildLaw, buildTwoRuns, citesIn, isTwoRuns, lawsIn, namesWithClock } from "./laws.js";
10
+ import { proveLeadsTo, proveRule, proveSteps } from "./dsl.js";
11
+ import { LawError, buildLaw, buildLeadsTo, buildTwoRuns, citesIn, isLeadsTo, isTwoRuns, lawsIn, namesWithClock } from "./laws.js";
12
12
  import { certify, proveTwoRuns } from "./relational.js";
13
13
  const proc = globalThis.process;
14
14
  const fs = proc.getBuiltinModule('node:fs'), path = proc.getBuiltinModule('node:path');
@@ -254,19 +254,49 @@ const merge = (a, b) => {
254
254
  };
255
255
  // The entries to read: the one given, else the one inferred; where several classes or structs qualify, each of them; a
256
256
  // file of functions, each function a law is stated on.
257
+ // Every class or function a law is stated on is read too (a class that writes no state, a decision, among them): no law
258
+ // stated in the code is left without a rule to be proven on, or refused with why.
257
259
  async function rulesOf(t, o, laws) {
258
- const { json: _j, ms: _m, propose: _p, clock: _c, cert: _t, ...flags } = o;
260
+ const got = await rulesOf0(t, o, laws);
261
+ if (o.entry)
262
+ return got;
263
+ const have = new Set(got.flatMap(r => [r.entry, r.x.model?.name].filter((n) => !!n)));
264
+ const more = [...new Set(laws.map(l => l.cls ?? l.fn).filter((n) => !!n && !have.has(n)))];
265
+ if (!more.length)
266
+ return got;
267
+ const { json: _j, ms: _m, propose: _p, clock: _c, cert: _t, from: _fr, ...flags } = o;
259
268
  void _j;
260
269
  void _m;
261
270
  void _p;
262
271
  void _c;
263
272
  void _t;
273
+ void _fr;
274
+ 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
+ void _k;
277
+ void _f;
278
+ const keep = [...new Set(laws.flatMap(l => l.expr.match(/[A-Za-z_]\w*/g) ?? []))];
279
+ const extra = await Promise.all(more.map(async (entry) => ({ entry, x: await extractOne(t, { ...merge(merge({ ...shared, keep }, cfg.rules[entry] || {}), flags), entry }) })));
280
+ // (the first rule, read with no entry named, kept only where it read something or nothing else was)
281
+ return [...got.filter(r => r.x.ok || r.entry || !extra.length), ...extra];
282
+ }
283
+ async function rulesOf0(t, o, laws) {
284
+ const { json: _j, ms: _m, propose: _p, clock: _c, cert: _t, from: _fr, ...flags } = o;
285
+ void _j;
286
+ void _m;
287
+ void _p;
288
+ void _c;
289
+ void _t;
290
+ void _fr;
264
291
  // (the options: gdp.toml's for every rule, then the rule's own, then the flags; a rule found with no entry named is
265
292
  // read again where gdp.toml has options of its own for it)
266
293
  const cfg = configFor(t.lang === 'go' || t.lang === 'rust' || fs.statSync(t.at).isDirectory() ? t.at : path.dirname(t.at));
267
- const { clock: _k, ...shared } = cfg.all;
294
+ const { clock: _k, from: _f, ...shared } = cfg.all;
295
+ void _f;
268
296
  void _k;
269
- const optsFor = (entry) => merge(merge(shared, (entry && cfg.rules[entry]) || {}), flags);
297
+ // (the names the laws read, so an argument a law reads stays in the rule though the code ignores it)
298
+ const keep = [...new Set(laws.flatMap(l => l.expr.match(/[A-Za-z_]\w*/g) ?? []))];
299
+ const optsFor = (entry) => merge(merge({ ...shared, keep }, (entry && cfg.rules[entry]) || {}), flags);
270
300
  const one = async (entry) => {
271
301
  const x = await extractOne(t, { ...optsFor(entry), ...(entry ? { entry } : {}) }), found = x.model?.name;
272
302
  return !entry && found && cfg.rules[found] ? { entry: found, x: await extractOne(t, { ...optsFor(found), entry: found }) } : { entry, x };
@@ -286,9 +316,13 @@ async function rulesOf(t, o, laws) {
286
316
  if (first.x.ok)
287
317
  return [first];
288
318
  // (refused with no entry named: the rules gdp.toml names that the code has, each with its options)
289
- const named = Object.keys(cfg.rules).filter(k => t.files.some(f => new RegExp(`\\b${k.replace(/[^\w]/g, '\\$&')}\\b`).test(fs.readFileSync(f, 'utf8'))));
319
+ // (a rule gdp.toml names, where the file defines a class, struct or function of that name: never a word of its prose)
320
+ const named = Object.keys(cfg.rules).filter(k => t.files.some(f => new RegExp(`\\b(?:class|struct|def|defp|defmodule|module|fn|fun|func|function|interface|contract|object|impl|type|record|enum)\\s+(?:\\([^)]*\\)\\s*)?${k.replace(/[^\w]/g, '\\$&')}\\b`).test(fs.readFileSync(f, 'utf8'))));
321
+ // (and each class the refusal names: gdp.toml's rules beside the file's others, not instead of them)
322
+ const many = /several (?:classes|structs) (?:write their state|written by the file's functions) \(([^)]*)\)/.exec(first.x.refusals[0]?.what ?? '')?.[1].split(', ') ?? [];
323
+ const fns0 = [...new Set(laws.filter(l => !l.cls && l.fn).map(l => l.fn))];
290
324
  if (named.length)
291
- return Promise.all(named.map(k => one(k)));
325
+ return Promise.all([...new Set([...many, ...named, ...fns0])].map(k => one(k)));
292
326
  // (a contract's file names its contracts: refused with none named, the refusal is the rule's)
293
327
  if (t.lang === 'solidity')
294
328
  return [first];
@@ -298,23 +332,92 @@ async function rulesOf(t, o, laws) {
298
332
  const fns = [...new Set(laws.filter(l => !l.cls && l.fn).map(l => l.fn))];
299
333
  return several.length || fns.length ? Promise.all([...several, ...fns].map(c => one(c))) : [first];
300
334
  }
301
- function scoped(file) {
335
+ // (a class statement's name: its keyword at the start of a line, after modifiers; never a word in a comment)
336
+ const classAt = (line) => {
337
+ 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(/(#|\/\/).*$/, ''));
338
+ return m ? (m[1] ?? m[2]).split(/[.:<]/).filter(Boolean).pop() : undefined;
339
+ };
340
+ // (a type written like a call declares a value, never a function: `mapping(address => uint256) public balances;`, its
341
+ // parentheses closed, then a name (after modifiers) and `;` or `=`; a function's qualifiers (const, override, ...) are no
342
+ // name. A law on such a value is on no function, nor is one followed by another class's statement before any.)
343
+ const declares = (code, open) => {
344
+ let d = 0, i = open;
345
+ for (; i < code.length; i++) {
346
+ if (code[i] === '(')
347
+ d++;
348
+ else if (code[i] === ')' && --d === 0)
349
+ break;
350
+ }
351
+ const m = /^\s*(?:[A-Za-z_$][\w$]*\s+)*([A-Za-z_$][\w$]*)\s*(?:;|=(?![=>]))/.exec(code.slice(i + 1));
352
+ return !!m && !/^(const|override|final|noexcept|volatile|default|delete)$/.test(m[1]);
353
+ };
354
+ export function scoped(file) {
302
355
  const text = fs.readFileSync(file, 'utf8'), lines = text.split('\n');
303
356
  return lawsIn(text, path.basename(file)).map(l => {
304
357
  let cls, fn;
358
+ // (the nearest enclosing class statement: its keyword at the start of a line, after modifiers, never a word in a
359
+ // docstring's or a comment's prose; in Python, at an indentation that encloses the law's)
360
+ const indent = (x) => /^\s*/.exec(x)[0].length, lawIndent = indent(lines[l.line - 1]), py = file.endsWith('.py');
305
361
  for (let i = l.line - 1; i >= 0 && !cls; i--) {
306
- const m = /\b(?:class|struct|actor|defmodule|module|object|impl|record|interface|contract)\s+([\w.:]+)|\btype\s+(\w+)\s+struct\b/.exec(lines[i].replace(/(#|\/\/).*$/, ''));
307
- if (m)
308
- cls = (m[1] ?? m[2]).split(/[.:]/).pop();
362
+ const m = classAt(lines[i]);
363
+ if (m && (!py || indent(lines[i]) < lawIndent))
364
+ cls = m;
365
+ }
366
+ // (a law right above a class statement, past comments, blank lines and annotations, is that class's: a contract's,
367
+ // a struct's, a class's, never its first member's; one indented inside a class above a class after it isn't)
368
+ let above;
369
+ for (let i = l.line; i < lines.length; i++) {
370
+ if (/^\s*(\/\/|\/?\*|#|@|--|$)/.test(lines[i]))
371
+ continue;
372
+ above = indent(lines[i]) >= lawIndent ? classAt(lines[i]) : undefined;
373
+ break;
309
374
  }
310
- for (let i = l.line - 1; i < lines.length && !fn; i++) {
375
+ if (above)
376
+ return { ...l, cls: above };
377
+ // (in TypeScript, a law right above a declaration of a value, a schedule's say, is that value's)
378
+ let top = false;
379
+ if (/\.[cm]?[jt]sx?$/.test(file)) {
380
+ let i = l.line;
381
+ while (i < lines.length && /^\s*(\/\/|\/?\*|$)/.test(lines[i]))
382
+ i++;
383
+ const d = /^(\s*)(?:export\s+)?(?:const|let|var)\s+(\w+)\s*[=:]/.exec(lines[i] ?? '');
384
+ if (d) {
385
+ fn = d[2];
386
+ top = d[1] === '';
387
+ }
388
+ }
389
+ let fnLine = -1;
390
+ let onValue = false;
391
+ for (let i = l.line - 1; i < lines.length && !fn && !onValue; i++) {
311
392
  const code = i === l.line - 1 ? lines[i].replace(/(#|\/\/|--).*$/, '') : lines[i];
393
+ if (i >= l.line && classAt(code))
394
+ break;
312
395
  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);
313
- if (m && !/^(if|for|while|switch|return|catch|new)$/.test(m[1] ?? m[2]))
396
+ if (m && !m[1] && declares(code, m.index + m[0].length - 1))
397
+ onValue = true;
398
+ else if (m && !/^(if|for|while|switch|return|catch|new)$/.test(m[1] ?? m[2])) {
314
399
  fn = m[1] ?? m[2];
400
+ fnLine = i;
401
+ }
315
402
  }
316
- // (a Python function at the module's top level is in no class, whatever precedes it)
317
- if (fn && file.endsWith('.py') && lines.slice(l.line - 1).some(x => new RegExp(`^(?:async\\s+)?def\\s+${fn}\\b`).test(x)))
403
+ // (a Python function at the module's top level is in no class, whatever precedes it: the def the law sits on, not a
404
+ // later one of the same name)
405
+ // (likewise in every language where a definition at the line's start is outside any class: Ruby's, Elixir's, a
406
+ // TypeScript, Kotlin, Swift or Rust free function; a Go func is its receiver's type's, or none)
407
+ const at0 = fn && fnLine >= 0 ? lines[fnLine] : '';
408
+ // (a law indented inside a class's body, the class's last line, is the class's: a free function after the class
409
+ // isn't what it sits on)
410
+ if (fn && fnLine >= 0 && /\.(py|rb|ex|exs|ts|mts|tsx|js|mjs|kt|swift|rs)$/.test(file) && /^\S/.test(at0) && !/^\s*(?:class|struct|impl|module|defmodule|object|interface)\b/.test(at0)) {
411
+ if (/^\S/.test(lines[l.line - 1]))
412
+ cls = undefined;
413
+ else if (cls)
414
+ fn = undefined;
415
+ }
416
+ if (fn && fnLine >= 0 && file.endsWith('.go')) {
417
+ const rv = /^func\s+\(\s*\w*\s*\*?\s*(\w+)/.exec(at0);
418
+ cls = rv ? rv[1] : /^func\s/.test(at0) ? undefined : cls;
419
+ }
420
+ if (top)
318
421
  cls = undefined;
319
422
  return { ...l, ...(cls ? { cls } : {}), ...(fn ? { fn } : {}) };
320
423
  });
@@ -326,8 +429,10 @@ export async function checkTarget(t, o) {
326
429
  // (the clock's unit, for durations in a law: the language's clock, or clock = "s" | "ms" in gdp.toml or --clock)
327
430
  const unit = o.clock ?? configFor(t.lang === 'go' || t.lang === 'rust' || fs.statSync(t.at).isDirectory() ? t.at : path.dirname(t.at)).all.clock ?? CLOCK[t.lang];
328
431
  const others = Object.fromEntries(rules.filter(r => r.x.ok).map(r => [r.entry ?? r.x.model?.name ?? '', r.x]));
432
+ const cfg = configFor(t.lang === 'go' || t.lang === 'rust' || fs.statSync(t.at).isDirectory() ? t.at : path.dirname(t.at));
329
433
  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 };
330
- for (const { entry, x } of rules) {
434
+ for (const { entry, x: x0 } of rules) {
435
+ let x = x0;
331
436
  const name = entry ?? (x.model?.name || undefined);
332
437
  // (a target that is the working directory, a crate's or a package's: `.`)
333
438
  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 } : {}) };
@@ -335,14 +440,24 @@ export async function checkTarget(t, o) {
335
440
  // (the laws of this rule: all where it is the file's one, else those in its class or on it or its methods, and those
336
441
  // outside every class and function)
337
442
  const ms0 = new Set((x.names ?? []).map(n => n.method));
338
- const mine = rules.length === 1 ? laws : laws.filter(l => (!l.cls && !l.fn) || (l.cls ? l.cls === name : l.fn === name || ms0.has(l.fn)));
443
+ // (a law in a class is that class's alone, an entry named or not)
444
+ // (a law on a function outside any class is that function's, where the file has a rule of its name, never a method
445
+ // of another rule that shares the name)
446
+ const fnRules = new Set(rules.map(r => r.entry ?? r.x.model?.name).filter(Boolean));
447
+ const mine = rules.length === 1 ? laws.filter(l => !name || (l.cls ? l.cls === name : !l.fn || l.fn === name || ms0.has(l.fn))) : laws.filter(l => (!l.cls && !l.fn) || (l.cls ? l.cls === name : l.fn === name || (ms0.has(l.fn) && !fnRules.has(l.fn))));
339
448
  if (!x.ok || !x.rule) {
340
449
  r.laws = mine.map(l => ({ name: l.name, expr: l.expr, where: l.where, verdict: 'not read', why: 'the rule was refused', ms: 0 }));
341
450
  continue;
342
451
  }
452
+ // (an Effect service's primitives: the lemmas of their use proven first, each proven one beside every law)
453
+ if (x.lemmas?.length) {
454
+ const { withLemmas } = await import("./effect.js"), w = withLemmas(x, { ms: Math.max(o.ms, 30_000) });
455
+ x = w.x;
456
+ r.notes = [...r.notes, ...w.proven.map(n => `lemma proven, beside every law: ${n}`), ...w.unproven.map(n => `lemma not proven (left out): ${n}`)];
457
+ }
343
458
  const ev = x.evidence;
344
459
  if (ev)
345
- 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` : ''}`;
460
+ 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)` : ''}`;
346
461
  // (the rule's methods: the choice of method where it has several, else the one each name says)
347
462
  const evSort = x.model?.inputs.find(v => v.name === x.model?.event)?.sort;
348
463
  const methods = new Set([...(x.names ?? []).filter(n => n.method).map(n => n.method), ...(evSort?.k === 'choice' ? evSort.values : [])]);
@@ -350,13 +465,44 @@ export async function checkTarget(t, o) {
350
465
  const proven = [];
351
466
  // (a law is known by its name: a name stated twice in one rule is refused, both times)
352
467
  const twice = (l) => stated.filter(m => m.name === l.name).map(m => m.where);
353
- r.laws = stated.map(l => (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 } : prove(x, l, o.ms, proven, { ...ctx, entry: name })));
468
+ // (from = "any": every law proven from every state the laws allow, not only those a run from the start reaches, for
469
+ // code that steps the rule from states it is handed (a restart's, a stored one): the laws about states proven
470
+ // together as one inductive set, then each law of a step from every state they allow; none rests on what the
471
+ // search found)
472
+ const from = (o.from ?? (name ? cfg.rules[name]?.from : undefined) ?? cfg.all.from) === 'any' ? 'any' : undefined;
473
+ const kindOf = (l) => { if (isTwoRuns(l.expr))
474
+ return 'two'; if (isLeadsTo(l.expr))
475
+ return 'leads'; try {
476
+ return buildLaw(x, l, { clock: ctx.clock }).kind;
477
+ }
478
+ catch {
479
+ return 'bad';
480
+ } };
481
+ const rank = (l) => ({ law: 0, leads: 2 }[kindOf(l)] ?? 1);
482
+ const order = [...stated.keys()].sort((a, b) => rank(stated[a]) - rank(stated[b]));
483
+ // (from any state, the laws about states as one inductive set: the largest the stated ones make, each law the
484
+ // kernel's step breaks taken out in turn (Houdini), the others proven together; one taken out is judged alone)
485
+ const inductive = from && x.rule ? houdini(x, stated.filter(m => twice(m).length === 1 && kindOf(m) === 'law'), o.ms, ctx.clock) : undefined;
486
+ const outsOf = [];
487
+ for (const i of order) {
488
+ const l = stated[i];
489
+ 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 }
490
+ : 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)) } : {}) });
491
+ }
492
+ r.laws = outsOf;
354
493
  if (o.propose && x.model) {
355
494
  const p = propose(x, t.lang, o, proven, new Set(stated.map(l => l.expr.replace(/\s+/g, ''))));
356
495
  r.proposed = p.shown;
357
496
  r.brokenProposed = p.broken;
358
497
  }
359
498
  }
499
+ // (every law stated is accounted for: one that no rule took is reported not read, with why, never dropped)
500
+ const told = new Set(outs.flatMap(r => r.laws.map(l => l.where)));
501
+ const lost = laws.filter(l => !told.has(l.where));
502
+ if (lost.length)
503
+ outs.push({ file: path.relative(proc.cwd(), t.at) || '.', lang: LANG_NAME[t.lang], entry: [...new Set(lost.map(l => l.cls ?? l.fn ?? '(the file)'))].join(', '), ok: false,
504
+ refusals: [{ where: t.at, what: 'laws no rule read' }], notes: [], names: [], proposed: [],
505
+ laws: lost.map(l => ({ name: l.name, expr: l.expr, where: l.where, verdict: 'not read', why: `no rule read for it (${l.cls ? `class ${l.cls}` : l.fn ? `function ${l.fn}` : 'the file'}): name its entry (--entry, or [rules.<entry>] in gdp.toml)`, ms: 0 })) });
360
506
  // (a citation of no law stated in the target: refused, as a law not read is)
361
507
  const named = new Set(laws.map(l => l.name));
362
508
  for (const c of cites.filter(c => !named.has(c.law)))
@@ -366,15 +512,74 @@ export async function checkTarget(t, o) {
366
512
  // The unit of each language's clock (Date.now() and a Clock's millis count milliseconds; time.time(), DateTime.diff in
367
513
  // seconds and Instant's as_secs count seconds); the others say it in gdp.toml (clock = "s" or "ms").
368
514
  const CLOCK = { python: 's', elixir: 's', rust: 's', ts: 'ms', java: 'ms', kotlin: 'ms' };
515
+ // The largest set of these laws that is inductive from every state they allow together: each law whose step the
516
+ // kernel breaks taken out, the rest tried again.
517
+ function houdini(x, ls, ms, clock) {
518
+ let set = ls.flatMap(l => { try {
519
+ const b = buildLaw(x, l, { clock });
520
+ return b.kind === 'law' ? [{ l, law: b.law }] : [];
521
+ }
522
+ catch {
523
+ return [];
524
+ } });
525
+ for (let i = 0; i <= ls.length && set.length; i++) {
526
+ let v;
527
+ try {
528
+ v = proveRule(x.rule, [...(x.invariants ?? []), ...set.map(s => s.law)], { search: { ms }, from: 'any' });
529
+ }
530
+ catch {
531
+ return new Set();
532
+ }
533
+ if (v.proven && v.checked && !v.assumes)
534
+ return new Set(set.map(s => s.l.name));
535
+ const bad = set.find(s => v.goal === s.l.name || v.goal?.startsWith(`${s.l.name} @`));
536
+ if (!bad)
537
+ return new Set();
538
+ set = set.filter(s => s !== bad);
539
+ }
540
+ return new Set();
541
+ }
369
542
  // A law proven: an invariant with the rule's own invariants beside it, a step law with them and the invariants proven
370
543
  // so far (each holds in every reachable state, so the step laws may assume them); a law about two runs with the rule's
371
544
  // invariants holding of each run (core/relational.ts). Its citations go beside it, and with --cert <dir> the proof, as
372
545
  // an interchange document whose meta holds them.
373
- function prove(x, l, ms, proven, ctx) {
546
+ // The rule a law is proven on: the extraction's, declaring the divisors the law reads that the code doesn't (x // k,
547
+ // x % k: floor division and remainder by a constant, known by their facts), its machine made again with them.
548
+ function ruleFor(x, expr) {
549
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
550
+ const r = x.rule;
551
+ if (!r)
552
+ return x;
553
+ const ks = [...expr.matchAll(/(?:\/\/|%)\s*(\d+)/g)].map(m => Number(m[1])).filter(k => k >= 1);
554
+ return ks.length ? { ...x, rule: r.withDivisors(...ks) } : x;
555
+ }
556
+ function prove(x0, l, ms, proven, ctx) {
557
+ const x = ruleFor(x0, l.expr);
374
558
  const t0 = Date.now(), cites = ctx?.cites.filter(c => c.law === l.name).map(c => c.text) ?? [];
375
559
  const base = { name: l.name, expr: l.expr, ...(l.where ? { where: l.where } : {}), ...(cites.length ? { cites } : {}) };
376
- const inv = x.invariants ?? [], search = { search: { ms } };
560
+ const inv = x.invariants ?? [], search = { search: { ms }, ...(ctx?.from ? { from: ctx.from } : {}) };
561
+ // (whenever <from>, later <to>: proven with the rule's invariants and the laws proven so far, each helpful request fair)
562
+ if (isLeadsTo(l.expr)) {
563
+ let lt;
564
+ try {
565
+ lt = buildLeadsTo(x, l, { clock: ctx?.clock });
566
+ }
567
+ catch (e) {
568
+ if (e instanceof LawError)
569
+ return { ...base, verdict: 'not read', why: e.message, ms: 0 };
570
+ throw e;
571
+ }
572
+ let v;
573
+ try {
574
+ v = proveLeadsTo(x.rule, [...inv, ...proven], lt, { ms });
575
+ }
576
+ catch (e) {
577
+ return { ...base, kind: 'leads to', verdict: 'unknown', why: e.message, ms: Date.now() - t0 };
578
+ }
579
+ return { ...base, kind: 'leads to', verdict: v.proven && v.checked ? 'proven' : 'unknown', ...(v.proven && v.checked ? {} : { why: [v.goal, v.stuck, v.why].filter(Boolean).join('; ') || 'not proven' }), ms: Date.now() - t0 };
580
+ }
377
581
  let b, two;
582
+ // (a law that can't be built is not read, with why: never the whole check aborted)
378
583
  try {
379
584
  if (isTwoRuns(l.expr))
380
585
  two = buildTwoRuns(x, l, ctx?.others);
@@ -382,19 +587,54 @@ function prove(x, l, ms, proven, ctx) {
382
587
  b = buildLaw(x, l, { clock: ctx?.clock });
383
588
  }
384
589
  catch (e) {
385
- if (e instanceof LawError || two === undefined && isTwoRuns(l.expr))
386
- return { ...base, verdict: 'not read', why: e.message, ms: 0 };
387
- throw e;
590
+ return { ...base, verdict: 'not read', why: e.message, ms: 0 };
388
591
  }
389
592
  const kind = two ? 'two runs' : b.kind;
390
593
  let v;
594
+ // (from any state, a law about states outside the inductive set: false from the start (a run), or true there and
595
+ // needing a law beside it to hold from every state the laws allow)
596
+ if (ctx?.from && ctx.inductive && b?.kind === 'law' && !ctx.inductive.has(l.name)) {
597
+ let r;
598
+ try {
599
+ r = proveRule(x.rule, [...inv, b.law], { search: { ms } });
600
+ }
601
+ catch (e) {
602
+ return { ...base, kind: 'law', verdict: 'unknown', why: e.message, ms: Date.now() - t0 };
603
+ }
604
+ if (r.run)
605
+ return { ...base, kind: 'law', verdict: 'broken', run: runOf(x, r.run), ms: Date.now() - t0 };
606
+ return { ...base, kind: 'law', verdict: 'unknown', why: r.proven && r.checked ? `true in every state a run from the start reaches, not inductive from every state the laws allow (from = "any"): state the law it needs beside it${r.found?.laws?.length ? `: ${r.found.laws.map(f => f.text).join('; ')}` : ''}` : r.why ?? r.stuck ?? 'not proven', ...(r.found?.laws?.length ? { found: r.found.laws.map(f => f.text) } : {}), ms: Date.now() - t0 };
607
+ }
608
+ // (from any state: a law about states proven with the others stated beside it, as one inductive set)
609
+ const beside = () => (ctx?.together ?? []).filter(m => m.name !== l.name).flatMap(m => { try {
610
+ const y = buildLaw(x, m, { clock: ctx?.clock });
611
+ return y.kind === 'law' ? [y.law] : [];
612
+ }
613
+ catch {
614
+ return [];
615
+ } });
391
616
  try {
392
- v = two ? proveTwoRuns(two, { ...search, invariants: [two.sides[0] === x.rule ? inv : (ctx?.others && Object.values(ctx.others).find(o => o.rule === two.sides[0])?.invariants) ?? [], inv] }) : b.kind === 'law' ? proveRule(x.rule, [...inv, b.law], search) : proveSteps(x.rule, [...inv, ...proven], [b.law], search);
617
+ v = two ? proveTwoRuns(two, { ...search, invariants: [two.sides[0] === x.rule ? inv : (ctx?.others && Object.values(ctx.others).find(o => o.rule === two.sides[0])?.invariants) ?? [], inv] }) : b.kind === 'law' ? proveRule(x.rule, [...inv, ...(ctx?.from ? beside() : []), b.law], search) : proveSteps(x.rule, [...inv, ...proven], [b.law], search);
393
618
  }
394
619
  catch (e) {
395
620
  return { ...base, kind, verdict: 'unknown', why: e.message, ms: Date.now() - t0 };
396
621
  }
397
- let verdict = v.proven && v.checked ? 'proven' : v.run ? 'broken' : 'unknown', replayed;
622
+ // (from any state: a step that breaks the law from a state the laws allow refutes it, reachable or not; the run that
623
+ // reaches one from the start, where the search from the start finds it, is shown with it)
624
+ if (ctx?.from && !v.proven && !v.run && v.stuck === 'sat' && v.witness && b) {
625
+ try {
626
+ const r = b.kind === 'law' ? proveRule(x.rule, [...inv, b.law], { search: { ms } }) : proveSteps(x.rule, [...inv, ...proven], [b.law], { search: { ms } });
627
+ if (r.run)
628
+ v = { ...v, run: r.run };
629
+ }
630
+ catch { /* the state stands alone */ }
631
+ if (!v.run)
632
+ v = { ...v, why: `broken from a state the laws allow (from = "any"), no run from the start found reaching it` };
633
+ }
634
+ const brokenAt = !!(ctx?.from && !v.proven && !v.run && v.stuck === 'sat' && v.witness);
635
+ let verdict = v.proven && v.checked && !(ctx?.from && v.assumes) ? 'proven' : v.run || brokenAt ? 'broken' : 'unknown', replayed;
636
+ if (ctx?.from && v.proven && v.assumes)
637
+ v.why = `proven only in states a run from the start reaches (from = "any" asks for every state the laws allow): it needs ${v.assumes.laws.join('; ') || 'k-induction'}`;
398
638
  // (a run the front end replays on the code: broken only where the code runs it so)
399
639
  if (verdict === 'broken' && x.replay && v.run && !two) {
400
640
  const r = x.replay(v.run, b.law);
@@ -422,7 +662,7 @@ function prove(x, l, ms, proven, ctx) {
422
662
  fs.writeFileSync(cert, JSON.stringify(doc));
423
663
  }
424
664
  }
425
- return { ...base, kind, verdict, ...(replayed ? { replayed } : {}), ...(v.run && verdict === 'broken' ? { run: two ? pairRunOf(x, v.run, two) : runOf(x, v.run) } : {}), ...(verdict === 'unknown' ? { 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('; ') } : {}),
665
+ 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('; ') } : {}),
426
666
  ...(v.run && !two ? { assumes: assumedOf(x, v.run) } : {}), ...(found?.length ? { found } : {}), ...(cert ? { cert } : {}), ms: Date.now() - t0 };
427
667
  }
428
668
  // 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
@@ -573,7 +813,7 @@ function printRule(r, o) {
573
813
  out(` ${paint('dim', `${label(n).padEnd(w)} ${ROLE[n.role].padEnd(9)} ${n.rule}${n.none ? `${n.rule ? ', ' : ''}None: ${n.none}` : ''}${n.map ? ` (cells: ${n.map.fields.join(', ')}${n.map.tpl ? `; key ${JSON.stringify(n.map.tpl)}` : ''})` : ''}${n.role === 'const' ? String(n.value) : ''}`)}`);
574
814
  }
575
815
  const law = (l, proposed) => {
576
- out(` ${paint(VERDICT[l.verdict], l.verdict)}${' '.repeat(Math.max(0, 9 - l.verdict.length))}${l.name}${proposed ? '' : ` ${paint('dim', `(${l.where})`)}`}`);
816
+ out(` ${paint(VERDICT[l.verdict], l.verdict)}${' '.repeat(Math.max(0, 9 - l.verdict.length))}${l.name}${l.from ? ' (from any state)' : ''}${proposed ? '' : ` ${paint('dim', `(${l.where})`)}`}`);
577
817
  if (!proposed && l.verdict !== 'proven')
578
818
  out(` ${l.expr}`);
579
819
  for (const c of l.cites ?? [])
@@ -612,13 +852,14 @@ function printRule(r, o) {
612
852
  out();
613
853
  }
614
854
  const label = (n) => (n.role === 'answer' ? `${n.code.split('.').pop()}(...)` : n.role === 'input' && n.method ? `${n.method}(${n.code})` : n.role === 'result' && n.method ? `${n.method}() result` : n.code);
615
- const USAGE = `gdp-wired check <file|dir>... [--entry X] [--methods a,b] [--failures kept] [--on-error discard] [--json] [--ms 10000] [--no-propose] [--clock s|ms] [--cert <dir>]
855
+ const USAGE = `gdp-wired check <file|dir>... [--entry X] [--methods a,b] [--failures kept] [--on-error discard] [--json] [--ms 10000] [--no-propose] [--clock s|ms] [--cert <dir>] [--from any]
616
856
 
617
857
  Reads the rule in each file (Python, Ruby, Elixir, Java, Kotlin, Go, Rust, Swift, C, C++, TypeScript, Effect, XState), checks it
618
858
  against the code by running both, proves the laws stated in the code (\`# gdp: law <name>: <expr>\`, \`// gdp: law ...\`,
619
859
  @GdpLaw("<name>: <expr>")) and proposes others. Laws about two runs: \`<secret> never reaches <fields>\`, \`isolated by <argument>\`,
620
860
  \`agrees with <Class>\`; a duration over the clock: \`now - t < 30 days\`; the clause a law answers: \`gdp: cite <law name>: <clause>\`;
621
- --cert <dir> writes each proven law's certificate (its meta the citations). Exit code: 1 when a stated law is broken, 2 when
861
+ --cert <dir> writes each proven law's certificate (its meta the citations); --from any (or from = "any" in gdp.toml, for every
862
+ rule or one) proves every law from every state the laws allow, for code that steps the rule from states it is handed. Exit code: 1 when a stated law is broken, 2 when
622
863
  one couldn't be checked.`;
623
864
  // Every target's rules and their laws, and the exit code (1: a stated law broken; 2: one not checked).
624
865
  export async function check(targets, given = {}, each) {
@@ -1,5 +1,6 @@
1
1
  import { type C, type E, type Law, type Machine } from './machine.js';
2
2
  import { type CountCert, type CountInst, type Instances, type MapRead } from '../kernel/kernel.js';
3
+ import { inferLaws } from './infer.js';
3
4
  export declare const cprof: Record<string, number>;
4
5
  export declare const countsDump: {
5
6
  on?: (goal: object) => void;
@@ -20,7 +21,13 @@ export declare function certFor(goal: {
20
21
  insts: CountInst[];
21
22
  wits: string[];
22
23
  };
23
- export declare function matched(names: string[], body: C, cells: [string, E][], cap?: number): E[][];
24
+ export declare function candidates(src: Parameters<typeof inferLaws>[0], m: Machine, caller: Law[], shapes: Law[], guarded: Law[], ms: number, until: number): Law[];
25
+ export type Tried<P> = {
26
+ proof: P;
27
+ } | {
28
+ stuck: string;
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>;
24
31
  export type Counted = {
25
32
  proven: boolean;
26
33
  laws: Law[];