gdp-wired 0.42.0 → 0.43.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.
package/README.md CHANGED
@@ -171,7 +171,13 @@ 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`). `conforms(rule, service)` runs a rule written by hand
175
181
  beside a running service (Effect's own Semaphore, a store), and `fromSchema(schema)` is a Schema's kind
176
182
  (`examples/effect.ts`; what is read and refused, with what Effect projects write, in `research/effect/README.md`).
177
183
  - **What nobody stated, looked for when the prover alone stops**: where `proveRule` or `proveSteps` doesn't prove the laws
@@ -35,7 +35,8 @@ type LawOut = {
35
35
  name: string;
36
36
  expr: string;
37
37
  where?: string;
38
- kind?: 'law' | 'step' | 'two runs';
38
+ kind?: 'law' | 'step' | 'two runs' | 'leads to';
39
+ from?: 'any';
39
40
  verdict: 'proven' | 'broken' | 'unknown' | 'not read';
40
41
  run?: string[];
41
42
  replayed?: string;
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];
@@ -302,19 +336,53 @@ function scoped(file) {
302
336
  const text = fs.readFileSync(file, 'utf8'), lines = text.split('\n');
303
337
  return lawsIn(text, path.basename(file)).map(l => {
304
338
  let cls, fn;
339
+ // (the nearest enclosing class statement: its keyword at the start of a line, after modifiers, never a word in a
340
+ // docstring's or a comment's prose; in Python, at an indentation that encloses the law's)
341
+ const indent = (x) => /^\s*/.exec(x)[0].length, lawIndent = indent(lines[l.line - 1]), py = file.endsWith('.py');
305
342
  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();
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(/(#|\/\/).*$/, ''));
344
+ if (m && (!py || indent(lines[i]) < lawIndent))
345
+ cls = (m[1] ?? m[2]).split(/[.:<]/).filter(Boolean).pop();
346
+ }
347
+ // (in TypeScript, a law right above a declaration of a value, a schedule's say, is that value's)
348
+ let top = false;
349
+ if (/\.[cm]?[jt]sx?$/.test(file)) {
350
+ let i = l.line;
351
+ while (i < lines.length && /^\s*(\/\/|\/?\*|$)/.test(lines[i]))
352
+ i++;
353
+ const d = /^(\s*)(?:export\s+)?(?:const|let|var)\s+(\w+)\s*[=:]/.exec(lines[i] ?? '');
354
+ if (d) {
355
+ fn = d[2];
356
+ top = d[1] === '';
357
+ }
309
358
  }
359
+ let fnLine = -1;
310
360
  for (let i = l.line - 1; i < lines.length && !fn; i++) {
311
361
  const code = i === l.line - 1 ? lines[i].replace(/(#|\/\/|--).*$/, '') : lines[i];
312
362
  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]))
363
+ if (m && !/^(if|for|while|switch|return|catch|new)$/.test(m[1] ?? m[2])) {
314
364
  fn = m[1] ?? m[2];
365
+ fnLine = i;
366
+ }
367
+ }
368
+ // (a Python function at the module's top level is in no class, whatever precedes it: the def the law sits on, not a
369
+ // later one of the same name)
370
+ // (likewise in every language where a definition at the line's start is outside any class: Ruby's, Elixir's, a
371
+ // TypeScript, Kotlin, Swift or Rust free function; a Go func is its receiver's type's, or none)
372
+ const at0 = fn && fnLine >= 0 ? lines[fnLine] : '';
373
+ // (a law indented inside a class's body, the class's last line, is the class's: a free function after the class
374
+ // isn't what it sits on)
375
+ 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)) {
376
+ if (/^\S/.test(lines[l.line - 1]))
377
+ cls = undefined;
378
+ else if (cls)
379
+ fn = undefined;
380
+ }
381
+ if (fn && fnLine >= 0 && file.endsWith('.go')) {
382
+ const rv = /^func\s+\(\s*\w*\s*\*?\s*(\w+)/.exec(at0);
383
+ cls = rv ? rv[1] : /^func\s/.test(at0) ? undefined : cls;
315
384
  }
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)))
385
+ if (top)
318
386
  cls = undefined;
319
387
  return { ...l, ...(cls ? { cls } : {}), ...(fn ? { fn } : {}) };
320
388
  });
@@ -326,6 +394,7 @@ export async function checkTarget(t, o) {
326
394
  // (the clock's unit, for durations in a law: the language's clock, or clock = "s" | "ms" in gdp.toml or --clock)
327
395
  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
396
  const others = Object.fromEntries(rules.filter(r => r.x.ok).map(r => [r.entry ?? r.x.model?.name ?? '', r.x]));
397
+ const cfg = configFor(t.lang === 'go' || t.lang === 'rust' || fs.statSync(t.at).isDirectory() ? t.at : path.dirname(t.at));
329
398
  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
399
  for (const { entry, x } of rules) {
331
400
  const name = entry ?? (x.model?.name || undefined);
@@ -335,14 +404,18 @@ export async function checkTarget(t, o) {
335
404
  // (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
405
  // outside every class and function)
337
406
  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)));
407
+ // (a law in a class is that class's alone, an entry named or not)
408
+ // (a law on a function outside any class is that function's, where the file has a rule of its name, never a method
409
+ // of another rule that shares the name)
410
+ const fnRules = new Set(rules.map(r => r.entry ?? r.x.model?.name).filter(Boolean));
411
+ 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
412
  if (!x.ok || !x.rule) {
340
413
  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
414
  continue;
342
415
  }
343
416
  const ev = x.evidence;
344
417
  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` : ''}`;
418
+ 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
419
  // (the rule's methods: the choice of method where it has several, else the one each name says)
347
420
  const evSort = x.model?.inputs.find(v => v.name === x.model?.event)?.sort;
348
421
  const methods = new Set([...(x.names ?? []).filter(n => n.method).map(n => n.method), ...(evSort?.k === 'choice' ? evSort.values : [])]);
@@ -350,13 +423,44 @@ export async function checkTarget(t, o) {
350
423
  const proven = [];
351
424
  // (a law is known by its name: a name stated twice in one rule is refused, both times)
352
425
  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 })));
426
+ // (from = "any": every law proven from every state the laws allow, not only those a run from the start reaches, for
427
+ // code that steps the rule from states it is handed (a restart's, a stored one): the laws about states proven
428
+ // together as one inductive set, then each law of a step from every state they allow; none rests on what the
429
+ // search found)
430
+ const from = (o.from ?? (name ? cfg.rules[name]?.from : undefined) ?? cfg.all.from) === 'any' ? 'any' : undefined;
431
+ const kindOf = (l) => { if (isTwoRuns(l.expr))
432
+ return 'two'; if (isLeadsTo(l.expr))
433
+ return 'leads'; try {
434
+ return buildLaw(x, l, { clock: ctx.clock }).kind;
435
+ }
436
+ catch {
437
+ return 'bad';
438
+ } };
439
+ const rank = (l) => ({ law: 0, leads: 2 }[kindOf(l)] ?? 1);
440
+ const order = [...stated.keys()].sort((a, b) => rank(stated[a]) - rank(stated[b]));
441
+ // (from any state, the laws about states as one inductive set: the largest the stated ones make, each law the
442
+ // 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;
444
+ const outsOf = [];
445
+ for (const i of order) {
446
+ const l = stated[i];
447
+ 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)) } : {}) });
449
+ }
450
+ r.laws = outsOf;
354
451
  if (o.propose && x.model) {
355
452
  const p = propose(x, t.lang, o, proven, new Set(stated.map(l => l.expr.replace(/\s+/g, ''))));
356
453
  r.proposed = p.shown;
357
454
  r.brokenProposed = p.broken;
358
455
  }
359
456
  }
457
+ // (every law stated is accounted for: one that no rule took is reported not read, with why, never dropped)
458
+ const told = new Set(outs.flatMap(r => r.laws.map(l => l.where)));
459
+ const lost = laws.filter(l => !told.has(l.where));
460
+ if (lost.length)
461
+ 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,
462
+ refusals: [{ where: t.at, what: 'laws no rule read' }], notes: [], names: [], proposed: [],
463
+ 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
464
  // (a citation of no law stated in the target: refused, as a law not read is)
361
465
  const named = new Set(laws.map(l => l.name));
362
466
  for (const c of cites.filter(c => !named.has(c.law)))
@@ -366,15 +470,74 @@ export async function checkTarget(t, o) {
366
470
  // The unit of each language's clock (Date.now() and a Clock's millis count milliseconds; time.time(), DateTime.diff in
367
471
  // seconds and Instant's as_secs count seconds); the others say it in gdp.toml (clock = "s" or "ms").
368
472
  const CLOCK = { python: 's', elixir: 's', rust: 's', ts: 'ms', java: 'ms', kotlin: 'ms' };
473
+ // The largest set of these laws that is inductive from every state they allow together: each law whose step the
474
+ // kernel breaks taken out, the rest tried again.
475
+ function houdini(x, ls, ms, clock) {
476
+ let set = ls.flatMap(l => { try {
477
+ const b = buildLaw(x, l, { clock });
478
+ return b.kind === 'law' ? [{ l, law: b.law }] : [];
479
+ }
480
+ catch {
481
+ return [];
482
+ } });
483
+ for (let i = 0; i <= ls.length && set.length; i++) {
484
+ let v;
485
+ try {
486
+ v = proveRule(x.rule, [...(x.invariants ?? []), ...set.map(s => s.law)], { search: { ms }, from: 'any' });
487
+ }
488
+ catch {
489
+ return new Set();
490
+ }
491
+ if (v.proven && v.checked && !v.assumes)
492
+ return new Set(set.map(s => s.l.name));
493
+ const bad = set.find(s => v.goal === s.l.name || v.goal?.startsWith(`${s.l.name} @`));
494
+ if (!bad)
495
+ return new Set();
496
+ set = set.filter(s => s !== bad);
497
+ }
498
+ return new Set();
499
+ }
369
500
  // A law proven: an invariant with the rule's own invariants beside it, a step law with them and the invariants proven
370
501
  // 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
502
  // invariants holding of each run (core/relational.ts). Its citations go beside it, and with --cert <dir> the proof, as
372
503
  // an interchange document whose meta holds them.
373
- function prove(x, l, ms, proven, ctx) {
504
+ // The rule a law is proven on: the extraction's, declaring the divisors the law reads that the code doesn't (x // k,
505
+ // x % k: floor division and remainder by a constant, known by their facts), its machine made again with them.
506
+ function ruleFor(x, expr) {
507
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
508
+ const r = x.rule;
509
+ if (!r)
510
+ return x;
511
+ const ks = [...expr.matchAll(/(?:\/\/|%)\s*(\d+)/g)].map(m => Number(m[1])).filter(k => k >= 1);
512
+ return ks.length ? { ...x, rule: r.withDivisors(...ks) } : x;
513
+ }
514
+ function prove(x0, l, ms, proven, ctx) {
515
+ const x = ruleFor(x0, l.expr);
374
516
  const t0 = Date.now(), cites = ctx?.cites.filter(c => c.law === l.name).map(c => c.text) ?? [];
375
517
  const base = { name: l.name, expr: l.expr, ...(l.where ? { where: l.where } : {}), ...(cites.length ? { cites } : {}) };
376
- const inv = x.invariants ?? [], search = { search: { ms } };
518
+ const inv = x.invariants ?? [], search = { search: { ms }, ...(ctx?.from ? { from: ctx.from } : {}) };
519
+ // (whenever <from>, later <to>: proven with the rule's invariants and the laws proven so far, each helpful request fair)
520
+ if (isLeadsTo(l.expr)) {
521
+ let lt;
522
+ try {
523
+ lt = buildLeadsTo(x, l, { clock: ctx?.clock });
524
+ }
525
+ catch (e) {
526
+ if (e instanceof LawError)
527
+ return { ...base, verdict: 'not read', why: e.message, ms: 0 };
528
+ throw e;
529
+ }
530
+ let v;
531
+ try {
532
+ v = proveLeadsTo(x.rule, [...inv, ...proven], lt, { ms });
533
+ }
534
+ catch (e) {
535
+ return { ...base, kind: 'leads to', verdict: 'unknown', why: e.message, ms: Date.now() - t0 };
536
+ }
537
+ 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 };
538
+ }
377
539
  let b, two;
540
+ // (a law that can't be built is not read, with why: never the whole check aborted)
378
541
  try {
379
542
  if (isTwoRuns(l.expr))
380
543
  two = buildTwoRuns(x, l, ctx?.others);
@@ -382,19 +545,54 @@ function prove(x, l, ms, proven, ctx) {
382
545
  b = buildLaw(x, l, { clock: ctx?.clock });
383
546
  }
384
547
  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;
548
+ return { ...base, verdict: 'not read', why: e.message, ms: 0 };
388
549
  }
389
550
  const kind = two ? 'two runs' : b.kind;
390
551
  let v;
552
+ // (from any state, a law about states outside the inductive set: false from the start (a run), or true there and
553
+ // needing a law beside it to hold from every state the laws allow)
554
+ if (ctx?.from && ctx.inductive && b?.kind === 'law' && !ctx.inductive.has(l.name)) {
555
+ let r;
556
+ try {
557
+ r = proveRule(x.rule, [...inv, b.law], { search: { ms } });
558
+ }
559
+ catch (e) {
560
+ return { ...base, kind: 'law', verdict: 'unknown', why: e.message, ms: Date.now() - t0 };
561
+ }
562
+ if (r.run)
563
+ return { ...base, kind: 'law', verdict: 'broken', run: runOf(x, r.run), ms: Date.now() - t0 };
564
+ 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 };
565
+ }
566
+ // (from any state: a law about states proven with the others stated beside it, as one inductive set)
567
+ const beside = () => (ctx?.together ?? []).filter(m => m.name !== l.name).flatMap(m => { try {
568
+ const y = buildLaw(x, m, { clock: ctx?.clock });
569
+ return y.kind === 'law' ? [y.law] : [];
570
+ }
571
+ catch {
572
+ return [];
573
+ } });
391
574
  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);
575
+ 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
576
  }
394
577
  catch (e) {
395
578
  return { ...base, kind, verdict: 'unknown', why: e.message, ms: Date.now() - t0 };
396
579
  }
397
- let verdict = v.proven && v.checked ? 'proven' : v.run ? 'broken' : 'unknown', replayed;
580
+ // (from any state: a step that breaks the law from a state the laws allow refutes it, reachable or not; the run that
581
+ // reaches one from the start, where the search from the start finds it, is shown with it)
582
+ if (ctx?.from && !v.proven && !v.run && v.stuck === 'sat' && v.witness && b) {
583
+ try {
584
+ const r = b.kind === 'law' ? proveRule(x.rule, [...inv, b.law], { search: { ms } }) : proveSteps(x.rule, [...inv, ...proven], [b.law], { search: { ms } });
585
+ if (r.run)
586
+ v = { ...v, run: r.run };
587
+ }
588
+ catch { /* the state stands alone */ }
589
+ if (!v.run)
590
+ v = { ...v, why: `broken from a state the laws allow (from = "any"), no run from the start found reaching it` };
591
+ }
592
+ const brokenAt = !!(ctx?.from && !v.proven && !v.run && v.stuck === 'sat' && v.witness);
593
+ let verdict = v.proven && v.checked && !(ctx?.from && v.assumes) ? 'proven' : v.run || brokenAt ? 'broken' : 'unknown', replayed;
594
+ if (ctx?.from && v.proven && v.assumes)
595
+ 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
596
  // (a run the front end replays on the code: broken only where the code runs it so)
399
597
  if (verdict === 'broken' && x.replay && v.run && !two) {
400
598
  const r = x.replay(v.run, b.law);
@@ -422,7 +620,7 @@ function prove(x, l, ms, proven, ctx) {
422
620
  fs.writeFileSync(cert, JSON.stringify(doc));
423
621
  }
424
622
  }
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('; ') } : {}),
623
+ 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
624
  ...(v.run && !two ? { assumes: assumedOf(x, v.run) } : {}), ...(found?.length ? { found } : {}), ...(cert ? { cert } : {}), ms: Date.now() - t0 };
427
625
  }
428
626
  // 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 +771,7 @@ function printRule(r, o) {
573
771
  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
772
  }
575
773
  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})`)}`}`);
774
+ 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
775
  if (!proposed && l.verdict !== 'proven')
578
776
  out(` ${l.expr}`);
579
777
  for (const c of l.cites ?? [])
@@ -612,13 +810,14 @@ function printRule(r, o) {
612
810
  out();
613
811
  }
614
812
  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>]
813
+ 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
814
 
617
815
  Reads the rule in each file (Python, Ruby, Elixir, Java, Kotlin, Go, Rust, Swift, C, C++, TypeScript, Effect, XState), checks it
618
816
  against the code by running both, proves the laws stated in the code (\`# gdp: law <name>: <expr>\`, \`// gdp: law ...\`,
619
817
  @GdpLaw("<name>: <expr>")) and proposes others. Laws about two runs: \`<secret> never reaches <fields>\`, \`isolated by <argument>\`,
620
818
  \`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
819
+ --cert <dir> writes each proven law's certificate (its meta the citations); --from any (or from = "any" in gdp.toml, for every
820
+ 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
821
  one couldn't be checked.`;
623
822
  // Every target's rules and their laws, and the exit code (1: a stated law broken; 2: one not checked).
624
823
  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[];