gdp-wired 0.47.0 → 0.48.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 (170) hide show
  1. package/README.md +15 -4
  2. package/dist/core/carry.d.ts +15 -0
  3. package/dist/core/carry.js +651 -0
  4. package/dist/core/cli.d.ts +3 -1
  5. package/dist/core/cli.js +28 -8
  6. package/dist/core/count-cases.d.ts +24 -0
  7. package/dist/core/count-cases.js +320 -0
  8. package/dist/core/count-cert-grow.d.ts +4 -0
  9. package/dist/core/count-cert-grow.js +37 -0
  10. package/dist/core/count-cert-transport.d.ts +3 -0
  11. package/dist/core/count-cert-transport.js +58 -0
  12. package/dist/core/count-completion.d.ts +9 -0
  13. package/dist/core/count-completion.js +27 -0
  14. package/dist/core/count-cubes.d.ts +8 -0
  15. package/dist/core/count-cubes.js +69 -0
  16. package/dist/core/count-demand.d.ts +37 -0
  17. package/dist/core/count-demand.js +361 -0
  18. package/dist/core/count-facts.d.ts +52 -0
  19. package/dist/core/count-facts.js +247 -0
  20. package/dist/core/count-focus-proof.d.ts +8 -0
  21. package/dist/core/count-focus-proof.js +140 -0
  22. package/dist/core/count-focused.d.ts +22 -0
  23. package/dist/core/count-focused.js +676 -0
  24. package/dist/core/count-ranges.d.ts +5 -0
  25. package/dist/core/count-ranges.js +65 -0
  26. package/dist/core/count-recovery/action-guard.d.ts +5 -0
  27. package/dist/core/count-recovery/action-guard.js +51 -0
  28. package/dist/core/count-recovery/boolean-core.d.ts +16 -0
  29. package/dist/core/count-recovery/boolean-core.js +258 -0
  30. package/dist/core/count-recovery/carried-case.d.ts +2 -0
  31. package/dist/core/count-recovery/carried-case.js +24 -0
  32. package/dist/core/count-recovery/conditional-check-cache.d.ts +23 -0
  33. package/dist/core/count-recovery/conditional-check-cache.js +130 -0
  34. package/dist/core/count-recovery/conditional-cuts.d.ts +6 -0
  35. package/dist/core/count-recovery/conditional-cuts.js +318 -0
  36. package/dist/core/count-recovery/conditional-proof.d.ts +19 -0
  37. package/dist/core/count-recovery/conditional-proof.js +306 -0
  38. package/dist/core/count-recovery/derivability-closure.d.ts +14 -0
  39. package/dist/core/count-recovery/derivability-closure.js +533 -0
  40. package/dist/core/count-recovery/empty-count-source.d.ts +2 -0
  41. package/dist/core/count-recovery/empty-count-source.js +40 -0
  42. package/dist/core/count-recovery/field-bound-lemmas.d.ts +23 -0
  43. package/dist/core/count-recovery/field-bound-lemmas.js +640 -0
  44. package/dist/core/count-recovery/field-case.d.ts +5 -0
  45. package/dist/core/count-recovery/field-case.js +89 -0
  46. package/dist/core/count-recovery/field-demand.d.ts +46 -0
  47. package/dist/core/count-recovery/field-demand.js +47 -0
  48. package/dist/core/count-recovery/field-only.d.ts +3 -0
  49. package/dist/core/count-recovery/field-only.js +18 -0
  50. package/dist/core/count-recovery/fold-path.d.ts +6 -0
  51. package/dist/core/count-recovery/fold-path.js +35 -0
  52. package/dist/core/count-recovery/frame-lemmas.d.ts +9 -0
  53. package/dist/core/count-recovery/frame-lemmas.js +120 -0
  54. package/dist/core/count-recovery/guard-cases.d.ts +12 -0
  55. package/dist/core/count-recovery/guard-cases.js +138 -0
  56. package/dist/core/count-recovery/key-closure.d.ts +14 -0
  57. package/dist/core/count-recovery/key-closure.js +62 -0
  58. package/dist/core/count-recovery/leaf-allowance.d.ts +4 -0
  59. package/dist/core/count-recovery/leaf-allowance.js +7 -0
  60. package/dist/core/count-recovery/lift-count-proxies.d.ts +6 -0
  61. package/dist/core/count-recovery/lift-count-proxies.js +175 -0
  62. package/dist/core/count-recovery/live-dependencies.d.ts +6 -0
  63. package/dist/core/count-recovery/live-dependencies.js +76 -0
  64. package/dist/core/count-recovery/member-inclusions.d.ts +11 -0
  65. package/dist/core/count-recovery/member-inclusions.js +168 -0
  66. package/dist/core/count-recovery/member-premises.d.ts +29 -0
  67. package/dist/core/count-recovery/member-premises.js +114 -0
  68. package/dist/core/count-recovery/natural-cases.d.ts +6 -0
  69. package/dist/core/count-recovery/natural-cases.js +59 -0
  70. package/dist/core/count-recovery/ops.d.ts +6 -0
  71. package/dist/core/count-recovery/ops.js +8 -0
  72. package/dist/core/count-recovery/pre-state-source.d.ts +8 -0
  73. package/dist/core/count-recovery/pre-state-source.js +18 -0
  74. package/dist/core/count-recovery/rebase-path.d.ts +9 -0
  75. package/dist/core/count-recovery/rebase-path.js +70 -0
  76. package/dist/core/count-recovery/rename-proof.d.ts +2 -0
  77. package/dist/core/count-recovery/rename-proof.js +102 -0
  78. package/dist/core/count-recovery/row-cases.d.ts +16 -0
  79. package/dist/core/count-recovery/row-cases.js +291 -0
  80. package/dist/core/count-recovery/scalar-guards.d.ts +7 -0
  81. package/dist/core/count-recovery/scalar-guards.js +291 -0
  82. package/dist/core/count-recovery/source-memo.d.ts +12 -0
  83. package/dist/core/count-recovery/source-memo.js +67 -0
  84. package/dist/core/count-select.d.ts +16 -0
  85. package/dist/core/count-select.js +24 -0
  86. package/dist/core/count-support.d.ts +598 -0
  87. package/dist/core/count-support.js +2080 -0
  88. package/dist/core/count-unions.d.ts +2 -0
  89. package/dist/core/count-unions.js +139 -0
  90. package/dist/core/count-witness-flags.d.ts +9 -0
  91. package/dist/core/count-witness-flags.js +37 -0
  92. package/dist/core/count-write-frames.d.ts +12 -0
  93. package/dist/core/count-write-frames.js +206 -0
  94. package/dist/core/counts.d.ts +20 -2
  95. package/dist/core/counts.js +807 -156
  96. package/dist/core/dsl.d.ts +50 -6
  97. package/dist/core/dsl.js +307 -65
  98. package/dist/core/effect.js +8 -1
  99. package/dist/core/exists.d.ts +1 -1
  100. package/dist/core/exists.js +80 -15
  101. package/dist/core/extract-check.d.ts +7 -1
  102. package/dist/core/extract-check.js +130 -13
  103. package/dist/core/extract-read.d.ts +22 -8
  104. package/dist/core/extract-read.js +29 -11
  105. package/dist/core/extract-shapes.js +122 -41
  106. package/dist/core/extract-standalone.js +53 -9
  107. package/dist/core/extract.js +9 -3
  108. package/dist/core/field-laws.d.ts +2 -0
  109. package/dist/core/field-laws.js +100 -0
  110. package/dist/core/finite-frontiers.d.ts +5 -0
  111. package/dist/core/finite-frontiers.js +116 -0
  112. package/dist/core/finite-houdini.d.ts +52 -0
  113. package/dist/core/finite-houdini.js +460 -0
  114. package/dist/core/finite-model.d.ts +13 -0
  115. package/dist/core/finite-model.js +68 -0
  116. package/dist/core/finite-tiny.d.ts +72 -0
  117. package/dist/core/finite-tiny.js +1052 -0
  118. package/dist/core/infer.d.ts +1 -1
  119. package/dist/core/infer.js +32 -9
  120. package/dist/core/laws.d.ts +2 -1
  121. package/dist/core/laws.js +47 -14
  122. package/dist/core/lemma-cuts.d.ts +38 -0
  123. package/dist/core/lemma-cuts.js +365 -0
  124. package/dist/core/machine.d.ts +39 -2
  125. package/dist/core/machine.js +240 -35
  126. package/dist/core/mutate.d.ts +55 -0
  127. package/dist/core/mutate.js +210 -0
  128. package/dist/core/native-domain.d.ts +6 -0
  129. package/dist/core/native-domain.js +114 -0
  130. package/dist/core/native-law.d.ts +3 -0
  131. package/dist/core/native-law.js +174 -0
  132. package/dist/core/quorum-laws.d.ts +5 -0
  133. package/dist/core/quorum-laws.js +239 -0
  134. package/dist/core/relational.js +10 -2
  135. package/dist/core/relevance.d.ts +4 -0
  136. package/dist/core/relevance.js +79 -0
  137. package/dist/core/runtime-wall.d.ts +3 -0
  138. package/dist/core/runtime-wall.js +4 -0
  139. package/dist/core/sample-step.d.ts +16 -0
  140. package/dist/core/sample-step.js +28 -0
  141. package/dist/core/source-check.d.ts +44 -0
  142. package/dist/core/source-check.js +126 -0
  143. package/dist/core/source-diagnostic.d.ts +1 -0
  144. package/dist/core/source-diagnostic.js +34 -0
  145. package/dist/core/support-budget.d.ts +2 -0
  146. package/dist/core/support-budget.js +6 -0
  147. package/dist/core/system.js +2 -0
  148. package/dist/core/wall.d.ts +6 -0
  149. package/dist/core/wall.js +23 -0
  150. package/dist/core/watch.js +4 -0
  151. package/dist/kernel/cdcl.d.ts +4 -0
  152. package/dist/kernel/cdcl.js +20 -5
  153. package/dist/kernel/kernel.d.ts +10 -0
  154. package/dist/kernel/kernel.js +56 -3
  155. package/dist/kernel/model-sequence.d.ts +2 -2
  156. package/dist/kernel/model-sequence.js +4 -3
  157. package/dist/kernel/model-values.d.ts +2 -0
  158. package/dist/kernel/model-values.js +60 -0
  159. package/dist/kernel/prove.d.ts +10 -0
  160. package/dist/kernel/prove.js +56 -8
  161. package/dist/kernel/prover-rows.d.ts +29 -0
  162. package/dist/kernel/prover-rows.js +114 -0
  163. package/dist/lean-kernel/emit.d.ts +39 -2
  164. package/dist/lean-kernel/emit.js +136 -24
  165. package/dist/lean-kernel/lean-terms.d.ts +1 -0
  166. package/dist/lean-kernel/lean-terms.js +13 -5
  167. package/dist/lean-kernel/library.js +4 -0
  168. package/dist/lean-kernel/qalpha.d.ts +7 -0
  169. package/dist/lean-kernel/qalpha.js +40 -0
  170. package/package.json +5 -1
package/dist/core/dsl.js CHANGED
@@ -16,12 +16,14 @@
16
16
  // A step returns its updates as one object: every right-hand side reads the state before the step, as the kernel and
17
17
  // both runtimes do.
18
18
  import { candidates, cone, searchCounted } from "./counts.js";
19
+ import { inheritSource, translationVerdict } from "./source-check.js";
19
20
  import { env as knobs } from "./solver.js";
20
- import { argsKey, machineTerms, part, tuple, carriedView, compileFunction, divName, divisor, divisorsIn, evalC, evalE, interpret, isArithmetic, loadJs, modName, numbersOf, pairedArgs, seeded, withArithmetic } from "./machine.js";
21
+ import { argsKey, bindDirect, directOf, machineTerms, part, tuple, carriedView, compileFunction, divName, divisor, divisorsIn, evalC, evalE, fnCall, interpret, isArithmetic, loadJs, modName, numbersOf, pairedArgs, seeded, sourceFreeFn, withArithmetic } from "./machine.js";
21
22
  import { allowed, keysOf, requestEnv, watch, watchWork } from "./watch.js";
22
23
  import { ghostOf, proveSome, skolemOf, someHolds, substVars, substVarsE, witnessSupport } from "./exists.js";
23
24
  import { check, mapArities, checkRecur, foldObligations, ghostedMachine, loopObligations, someOfGhostsOk, substC, sumMachine } from "../kernel/kernel.js";
24
25
  import { certLoop, clock, counted, factsFor, fullRate, grow, pastWall, proveLaw, proveLaws, proveLiveness, proveSetFast, proveStepLaws, usualProof, withDeadline, withWall } from "../kernel/prove.js";
26
+ import { WallExpired, checkWall, searchWall } from "./wall.js";
25
27
  import { certCyclic, certOn, crossCyclic, cyclicOn, foldNodes, proveCyclic, quietly, recurNodes, translatedProof, uncovered } from "./cyclic.js";
26
28
  import { discover } from "./discover.js";
27
29
  import { inferLaws, inferRates } from "./infer.js";
@@ -1188,7 +1190,7 @@ export class CarriedList {
1188
1190
  const item = (i) => this.kind.build(this.name, p => new Term({ op: 'get', map: fname(p), key: i.e }));
1189
1191
  // Every item is a value of the kind (its own laws, as a fact of the first part's function).
1190
1192
  const kindFact = this.kind.invariant(this.kind.value(this.name)).length ? { 'every item is a value of its kind': forall(k => all(...this.kind.invariant(item(k)))) } : {};
1191
- const fns = Object.fromEntries(parts.map((p, j) => [fname(p), fn(1, 'x => 0', j === 0 ? { facts: () => kindFact } : {})]));
1193
+ const fns = Object.fromEntries(parts.map((p, j) => [fname(p), { ...fn(1, 'x => 0', j === 0 ? { facts: () => kindFact } : {}), direct: bindDirect({ js: 'x => 0' }, { kind: 'const', value: 0 }) }]));
1192
1194
  const folds = Object.entries(this.folds);
1193
1195
  const r = rule(`${this.name}'s folds, by induction`).params(Object.fromEntries(this.paramKinds)).fns(fns).inputs({})
1194
1196
  .state({ i: 0, ...Object.fromEntries(folds.map(([f, d]) => [`acc$${f}`, typeof d.from === 'number' ? d.from : (p) => d.from(p)])) })
@@ -1501,6 +1503,8 @@ function prenex(c, what, key) {
1501
1503
  return found ? out : undefined;
1502
1504
  }
1503
1505
  const substKey = (c, from, to) => JSON.parse(JSON.stringify(c).replaceAll(`"op":"var","name":"${from}"`, `"op":"var","name":"${to}"`));
1506
+ // The definitions actually flattened into a rule may have changed since recur captured its inlined helpers.
1507
+ const sourceFreeDef = (d) => sourceFreeFn(d) && Object.values(d.uses ?? {}).every(sourceFreeDef);
1504
1508
  export const fn = (arity, js, opts = {}) => {
1505
1509
  if (!Number.isInteger(arity) || arity < 1)
1506
1510
  throw new Error('a function takes one argument or more');
@@ -1511,23 +1515,26 @@ export const fn = (arity, js, opts = {}) => {
1511
1515
  export const divBy = (c) => {
1512
1516
  if (!Number.isSafeInteger(c) || c < 1)
1513
1517
  throw new RangeError('divBy takes a whole number at least 1');
1514
- return fn(1, `x => Math.floor(x / ${c})`, { lean: `fun x => x / ${c}`, facts: f => ({
1515
- [`${c}·q(x) <= x`]: forall(x => f(x).times(c).atMost(x)),
1516
- [`x < ${c}·q(x) + ${c}`]: forall(x => x.lt(f(x).times(c).plus(c))),
1517
- }) });
1518
+ return { ...fn(1, `x => Math.floor(x / ${c})`, { lean: `fun x => x / ${c}`, facts: f => ({
1519
+ [`${c}·q(x) <= x`]: forall(x => f(x).times(c).atMost(x)),
1520
+ [`x < ${c}·q(x) + ${c}`]: forall(x => x.lt(f(x).times(c).plus(c))),
1521
+ }) }), direct: bindDirect({ js: `x => Math.floor(x / ${c})` }, { kind: 'div', divisor: c }) };
1518
1522
  };
1519
1523
  export const modBy = (c) => {
1520
1524
  if (!Number.isSafeInteger(c) || c < 1)
1521
1525
  throw new RangeError('modBy takes a whole number at least 1');
1522
1526
  // x mod c is below c, and x less it is a multiple of c: x ∸ r = c·q for the q that divBy(c) gives; as facts about r
1523
1527
  // alone, r <= x, r < c, and r(x + c) = r(x).
1524
- return fn(1, `x => x % ${c}`, { lean: `fun x => x % ${c}`, facts: f => ({
1525
- [`r(x) < ${c}`]: forall(x => f(x).lt(c)),
1526
- [`r(x) <= x`]: forall(x => f(x).atMost(x)),
1527
- [`r(x + ${c}) = r(x)`]: forall(x => f(x.plus(c)).eq(f(x))),
1528
- }) });
1528
+ return { ...fn(1, `x => x % ${c}`, { lean: `fun x => x % ${c}`, facts: f => ({
1529
+ [`r(x) < ${c}`]: forall(x => f(x).lt(c)),
1530
+ [`r(x) <= x`]: forall(x => f(x).atMost(x)),
1531
+ [`r(x + ${c}) = r(x)`]: forall(x => f(x.plus(c)).eq(f(x))),
1532
+ }) }), direct: bindDirect({ js: `x => x % ${c}` }, { kind: 'mod', divisor: c }) };
1529
1533
  };
1530
1534
  const reservedInRecur = ['x', 'fx', 'y', 'fy', 'prev', 'x0', 'fx0'];
1535
+ // No dynamic parser is needed for library-generated source. Reject reserved bindings and the globals used by
1536
+ // recurJs (including by inlined helpers), which an argument would otherwise shadow only in compiled mode.
1537
+ const unsafeJsName = new Set(('await break case catch class const continue debugger default delete do else enum export extends false finally for function if implements import in instanceof interface let new null package private protected public return static super switch this throw true try typeof var void while with yield eval arguments Math Number RangeError').split(' '));
1531
1538
  export const recur = (name, def, lemmas = {}, between = {}) => {
1532
1539
  const plain = /^[A-Za-z][A-Za-z0-9_]*$/;
1533
1540
  if (!plain.test(name))
@@ -1536,6 +1543,9 @@ export const recur = (name, def, lemmas = {}, between = {}) => {
1536
1543
  for (const n of [...args, ...uses.map(([u]) => u)])
1537
1544
  if (!plain.test(n) || reservedInRecur.includes(n) || n === name)
1538
1545
  throw new Error(`recur ${name}: ${n} can't name an argument or a function here (${reservedInRecur.join(', ')} and ${name} are taken)`);
1546
+ for (const n of args)
1547
+ if (unsafeJsName.has(n))
1548
+ throw new Error(`recur ${name}: ${n} can't name an argument (it shadows JavaScript syntax or a runtime global)`);
1539
1549
  distinctNames(`recur ${name}`, [...args, ...uses.map(([u]) => u)]);
1540
1550
  // A rule reads the function at its arguments paired, which the kernel multiplies out: with five further arguments that
1541
1551
  // is a polynomial of degree 32, past what it can hold.
@@ -1623,7 +1633,8 @@ export const recur = (name, def, lemmas = {}, between = {}) => {
1623
1633
  ...(withBetween ? Object.fromEntries(Object.entries(between).map(([n, l]) => [n, keysOf(2 + args.length)((k, j, ...as) => k.atMost(j).implies(l(k, f(k, ...as), j, f(j, ...as), env(as))))])) : {}),
1624
1634
  };
1625
1635
  };
1626
- const base = { arity: 1 + args.length, js, lean: `Recur.${name}`, recur: recurrence, ...(uses.length ? { uses: def.fns } : {}) };
1636
+ const direct = bindDirect({ js, arity: 1 + args.length }, { kind: 'recur', name, args: [...args], zero, next, uses: Object.fromEntries(uses.map(([u, d]) => [u, runtimeFn(u, d, false)])) });
1637
+ const base = { arity: 1 + args.length, js, direct, lean: `Recur.${name}`, recur: recurrence, ...(uses.length ? { uses: def.fns } : {}) };
1627
1638
  // The laws between two points: y counting up from x and fy from fx, a value at x that meets the lemmas (as f(x)
1628
1639
  // does: they are given of it, as facts of the params), each law a law of that machine beside the lemmas at y. What
1629
1640
  // holds there for every such fx holds for f(x), and fy is f(y) by the recurrence; the machine reads no f at all.
@@ -1692,7 +1703,7 @@ const recurJs = (name, args, zero, next, uses) => {
1692
1703
  case 'all': throw new Error('a recurrence takes no flag or quantifier');
1693
1704
  }
1694
1705
  };
1695
- const inlined = uses.map(([u, d], i) => `const $f${i} = (${fnSource(u, d)}); ${d.arity > 1 ? `const $g${i} = (${jsOf(d)}); ` : ''}`).join('');
1706
+ const inlined = uses.map(([u, d], i) => `const $f${i} = (${fnSource(u, d, false)}); ${d.arity > 1 ? `const $g${i} = (${jsOf(d)}); ` : ''}`).join('');
1696
1707
  // The last value computed at each tuple of further arguments is kept, so reading f at x after f at a smaller x takes
1697
1708
  // only the steps between (a rule that reads f at a count that grows costs one step a request).
1698
1709
  return `(() => { ${inlined}const $memo = new Map(); return (x, ${args.map(a => `${a}, `).join('')}) => { const $k = ${args.length ? `[${args.join(', ')}].join()` : "''"}; let $at = $memo.get($k); if (!$at || $at[0] > x) $at = [0, ${js(zero)}]; let x0 = $at[0], prev = $at[1]; for (; x0 < x; x0++) { prev = ((x, prev) => ${js(next)})(x0, prev); if (!Number.isSafeInteger(prev)) throw new RangeError(${JSON.stringify(`${name} passes the safe integers`)}); } if ($memo.size > 4096) $memo.clear(); $memo.set($k, [x, prev]); return prev; }; })()`;
@@ -1704,33 +1715,52 @@ const flatFns = (defs) => defs.flatMap(([n, d]) => {
1704
1715
  });
1705
1716
  // A function's JavaScript as one function of its key: its arguments unpaired (left-nested, as argsKey pairs them).
1706
1717
  const jsOf = (d) => (typeof d.js === 'string' ? d.js : String(d.js));
1707
- const fnSource = (name, d) => {
1718
+ const fnSource = (name, d, validate = true) => {
1708
1719
  const src = jsOf(d);
1709
- let f;
1710
- try {
1711
- f = compileFunction([], `return (${src})`)();
1712
- f(...Array.from({ length: d.arity }, () => 0));
1713
- }
1714
- catch (e) {
1715
- throw new Error(`function ${name}: its js must be a function of its arguments that reads nothing else (${e.message})`);
1720
+ if (validate && !sourceFreeDef(d)) {
1721
+ try {
1722
+ const f = compileFunction([], `return (${src})`)();
1723
+ f(...Array.from({ length: d.arity }, () => 0));
1724
+ fnValues.set(d, { js: d.js, arity: d.arity, direct: directOf(d), value: f });
1725
+ }
1726
+ catch (e) {
1727
+ throw new Error(`function ${name}: its js must be a function of its arguments that reads nothing else (${e.message})`);
1728
+ }
1716
1729
  }
1717
1730
  if (d.arity === 1)
1718
1731
  return src;
1719
1732
  return `(() => { const $fn = (${src}); return k => { const u = z => { let s = Math.floor(Math.sqrt(z)); while (s * s > z) s--; while ((s + 1) * (s + 1) <= z) s++; return [s - (z - s * s), z - s * s]; }; const a = []; let z = k; for (let i = 1; i < ${d.arity}; i++) { const [p, q] = u(z); a.unshift(q); z = p; } a.unshift(z); return $fn(...a); }; })()`;
1720
1733
  };
1734
+ // Materialize runtime metadata without evaluating generated source during helper construction.
1735
+ const runtimeFn = (name, d, validate = true) => {
1736
+ const out = { js: fnSource(name, d, validate),
1737
+ ...(d.arity > 1 ? { arity: d.arity, call: jsOf(d) } : {}), ...(d.lean ? { lean: d.lean } : {}),
1738
+ ...(d.recur ? { recur: d.recur } : {}) };
1739
+ const direct = directOf(d);
1740
+ if (direct)
1741
+ out.direct = bindDirect(out, direct);
1742
+ return out;
1743
+ };
1721
1744
  const fnTerm = (name, d) => (...args) => {
1722
1745
  if (args.length !== d.arity)
1723
1746
  throw new Error(`function ${name} takes ${d.arity} argument${d.arity === 1 ? '' : 's'}`);
1724
1747
  const vals = known(args.map(valOf));
1725
- return new Term({ op: 'get', map: name, key: argsKey(args.map(termOf)) }, vals && fnValueOf(d)(...vals));
1748
+ return new Term({ op: 'get', map: name, key: argsKey(args.map(termOf)) }, vals && fnValueOf(d)?.(...vals));
1726
1749
  };
1727
1750
  // A function's JavaScript on its arguments themselves (not through the pairing the kernel reads them by).
1728
1751
  const fnValues = new WeakMap();
1729
1752
  const fnValueOf = (d) => {
1730
- let f = fnValues.get(d);
1753
+ const cached = fnValues.get(d);
1754
+ let f = cached?.js === d.js && cached.arity === d.arity && cached.direct === directOf(d) && (!cached.direct || sourceFreeDef(d)) ? cached.value : undefined;
1731
1755
  if (!f) {
1732
- f = typeof d.js === 'function' ? d.js : compileFunction([], `return (${d.js})`)();
1733
- fnValues.set(d, f);
1756
+ if (sourceFreeDef(d)) {
1757
+ const fn = runtimeFn('constant', d, false);
1758
+ f = (...args) => fnCall(fn, args);
1759
+ }
1760
+ // User source (including callbacks) may be folded only after materialization validated it, never invoked just
1761
+ // to build a term before the runtime's explicit compilation guard.
1762
+ if (f)
1763
+ fnValues.set(d, { js: d.js, arity: d.arity, direct: directOf(d), value: f });
1734
1764
  }
1735
1765
  return f;
1736
1766
  };
@@ -1765,8 +1795,9 @@ export class Rule {
1765
1795
  spec;
1766
1796
  constructor(spec) {
1767
1797
  this.spec = spec;
1798
+ inheritSource(spec, this);
1768
1799
  }
1769
- with(more) { return new Rule({ ...this.spec, ...more }); }
1800
+ with(more) { const next = new Rule({ ...this.spec, ...more }); inheritSource(this, next, Object.keys(more).every(k => k === 'arith' || k === 'sumsRead')); return next; }
1770
1801
  get name() { return this.spec.name; }
1771
1802
  // For core/discover.ts: the functions and carried lists the rule reads, and the same rule with functions made again
1772
1803
  // and lemmas added to its lists' folds (each proven here, as carriesList proves its own).
@@ -2366,7 +2397,7 @@ export class Rule {
2366
2397
  // Functions, and their facts: each function's own (named after it), then the rule's.
2367
2398
  // The functions a function reads come first, each named <function>.<use>.
2368
2399
  const flat = flatFns(s.fns ?? []);
2369
- const fns = Object.fromEntries(flat.map(([n, d]) => [n, { js: fnSource(n, d), ...(d.arity > 1 ? { arity: d.arity, call: jsOf(d) } : {}), ...(d.lean ? { lean: d.lean } : {}), ...(d.recur ? { recur: d.recur } : {}) }]));
2400
+ const fns = Object.fromEntries(flat.map(([n, d]) => [n, runtimeFn(n, d)]));
2370
2401
  const facts = [
2371
2402
  ...flat.flatMap(([n, d, uses]) => Object.entries(d.facts?.(fnTerm(n, d), uses) ?? {}).map(([name, f]) => this.lawOf(`${n}: ${name}`, f))),
2372
2403
  ...(s.facts ?? []).flatMap(f => Object.entries(f(pEnv)).map(([name, out]) => this.lawOf(name, out))),
@@ -2565,29 +2596,85 @@ export class Rule {
2565
2596
  // with requests drawn by their kinds (or `draw`), must hold the same values as the compiled rule (decoded: integers and
2566
2597
  // decimals as numbers) for every field the reference's state has, after every step of `trials` runs of `depth`.
2567
2598
  compare(reference, opts = {}) {
2568
- const s = this.spec, rand = opts.rand ?? seeded(5), bound = opts.bound ?? 100, gen = this.compiled(), run = interpret(this.machine);
2569
- let checked = 0;
2599
+ const s = this.spec, rand = opts.rand ?? seeded(5), bound = compareCount(opts.bound ?? 100, 'bound'), trials = compareCount(opts.trials ?? 200, 'trials');
2600
+ const depth = compareCount(opts.depth ?? 10, 'depth', 1), cap = compareCount(opts.maxCases ?? 100_000, 'maxCases', 1), m = this.machine, gen = this.compiled(), run = interpret(m);
2601
+ const paramsDomain = opts.params || opts.draw ? undefined : finiteFields(s.params, cap);
2602
+ const inputsDomain = paramsDomain && !s.carried?.length && !s.seqs?.length && !s.seqTables?.length && !s.lists2?.length ? finiteFields(s.inputs, Math.floor(cap / paramsDomain.size)) : undefined;
2603
+ const exhaustive = !!(paramsDomain && inputsDomain);
2604
+ let checked = 0, skipped = 0, skippedParams = 0;
2570
2605
  const sample = (kinds) => Object.fromEntries(kinds.map(([n, k]) => [n, k.sample(rand, bound)]));
2571
- for (let trial = 0; trial < (opts.trials ?? 200); trial++) {
2572
- const params = (opts.params?.(rand) ?? sample(s.params)), ps = this.encodeParams(params);
2573
- let ours = gen.init(ps), theirs = reference.init(params);
2574
- const edges = trial === 0 ? opts.edges ?? [] : [];
2575
- for (let d = 0; d < (opts.depth ?? 10) + edges.length; d++) {
2576
- const request = edges[d] ?? opts.draw?.(rand) ?? sample(s.inputs), encoded = this.encodeInput(request, params);
2577
- // A request the rule's assumption refuses is no step of the rule: the runtimes throw, so it isn't compared.
2578
- if (!allowed(this.machine, run, ps, ours, encoded))
2579
- continue;
2580
- ours = gen.step(ps, ours, encoded);
2581
- theirs = reference.step(params, theirs, request);
2606
+ const checkRun = (params, requests, chunks) => {
2607
+ const ps = this.encodeParams(params);
2608
+ if (m.pre && !evalC(m.pre, ps, { scalars: {}, maps: {} }, m)) {
2609
+ skippedParams++;
2610
+ return undefined;
2611
+ }
2612
+ let ours = gen.init(ps), theirs = reference.init(compareCopy(params)), at = 0, trace = [];
2613
+ const mismatch = (where) => {
2582
2614
  const got = this.decode(ours);
2583
- for (const [field, want] of Object.entries(theirs)) {
2584
- checked++;
2615
+ for (const [field, want] of Object.entries(compareFields(theirs)))
2585
2616
  if (!sameRaw(got[field], want))
2586
- return { checked, failure: `${s.name}, params ${JSON.stringify(params)}, after ${JSON.stringify(request)}: ${field} is ${shown(got[field])} here, ${shown(want)} in the code it describes` };
2617
+ return `${s.name}, params ${JSON.stringify(params)}, ${where}, trace ${JSON.stringify(trace)}: ${field} is ${shown(got[field])} here, ${shown(want)} in the code it describes`;
2618
+ return undefined;
2619
+ };
2620
+ let failure = mismatch('at init');
2621
+ if (failure)
2622
+ return failure;
2623
+ for (const request0 of requests) {
2624
+ if (chunks && at === depth) {
2625
+ ours = gen.init(ps);
2626
+ theirs = reference.init(compareCopy(params));
2627
+ at = 0;
2628
+ trace = [];
2629
+ failure = mismatch('at init');
2630
+ if (failure)
2631
+ return failure;
2587
2632
  }
2633
+ const request = compareCopy(request0), encoded = this.encodeInput(request, params);
2634
+ at++;
2635
+ if (!allowed(m, run, ps, ours, encoded)) {
2636
+ skipped++;
2637
+ continue;
2638
+ }
2639
+ trace.push(compareCopy(request));
2640
+ ours = gen.step(ps, ours, encoded);
2641
+ theirs = reference.step(compareCopy(params), theirs, compareCopy(request));
2642
+ checked++;
2643
+ failure = mismatch(`after ${JSON.stringify(request)}`);
2644
+ if (failure)
2645
+ return failure;
2646
+ }
2647
+ return undefined;
2648
+ };
2649
+ if (exhaustive) {
2650
+ const supplied = opts.edges ?? [], edges = supplied.filter((edge, i) => !supplied.slice(0, i).some(old => sameRaw(old, edge)));
2651
+ function* requests() {
2652
+ for (const edge of edges)
2653
+ yield compareCopy(edge);
2654
+ for (const value of inputsDomain.values())
2655
+ if (!edges.some(edge => sameRaw(edge, value)))
2656
+ yield value;
2657
+ }
2658
+ for (const value of paramsDomain.values()) {
2659
+ const failure = checkRun(value, requests(), true);
2660
+ if (failure)
2661
+ return compareResult(checked, false, skipped, skippedParams, failure);
2588
2662
  }
2589
2663
  }
2590
- return { checked };
2664
+ else {
2665
+ for (let trial = 0; trial < trials; trial++) {
2666
+ const params = compareCopy((opts.params?.(rand) ?? sample(s.params))), edges = trial === 0 ? opts.edges ?? [] : [];
2667
+ function* requests() {
2668
+ yield* edges;
2669
+ for (let i = 0; i < depth; i++)
2670
+ yield opts.draw?.(rand) ?? sample(s.inputs);
2671
+ }
2672
+ const failure = checkRun(params, requests(), false);
2673
+ if (failure)
2674
+ return compareResult(checked, false, skipped, skippedParams, failure);
2675
+ }
2676
+ }
2677
+ return compareResult(checked, exhaustive, skipped, skippedParams);
2591
2678
  }
2592
2679
  // --- running it -----------------------------------------------------------------------------------------------------
2593
2680
  // Runtime values (numbers, booleans, choice names, null for a missing value) to the variables the machine reads.
@@ -2706,7 +2793,11 @@ export class Rule {
2706
2793
  }
2707
2794
  // The prune order's variable, if the history is pruned (a runtime must send it nondecreasing).
2708
2795
  get orderedBy() { return this.spec.prune ? new Map(this.spec.inputs).get(this.spec.prune.order).vars(this.spec.prune.order)[0] : undefined; }
2709
- interpreter() { return interpret(this.machine); }
2796
+ interpreter(options = {}) {
2797
+ if (this.spec.fns?.some(([, d]) => !sourceFreeDef(d)) && !options.compileHelpers)
2798
+ throw new Error(`${this.name}: interpreter() does not compile declared helper source; use compiled() or explicitly pass {compileHelpers: true}`);
2799
+ return interpret(this.machine);
2800
+ }
2710
2801
  compiled() {
2711
2802
  return loadJs(this.machine);
2712
2803
  }
@@ -2761,18 +2852,44 @@ export class Fun {
2761
2852
  // check for an encoding: that the terms here are what the real function computes, on its real inputs.
2762
2853
  // cap.compare(({left, local}) => ({out: realCap(left, local)}), {edges: [{left: 2 ** 32 + 5, local: 10}]})
2763
2854
  compare(reference, opts = {}) {
2764
- const rand = opts.rand ?? seeded(5), bound = opts.bound ?? 1000, params = (opts.params ?? {}), kinds = this.r['spec'].inputs;
2765
- let checked = 0;
2766
- const draws = [...(opts.edges ?? []), ...Array.from({ length: opts.trials ?? 2000 }, () => opts.draw?.(rand) ?? Object.fromEntries(kinds.map(([n, k]) => [n, k.sample(rand, bound)])))];
2767
- for (const values of draws) {
2768
- const ours = this.run(values, params), theirs = reference(values, params);
2855
+ const rand = opts.rand ?? seeded(5), bound = compareCount(opts.bound ?? 1000, 'bound'), trials = compareCount(opts.trials ?? 2000, 'trials');
2856
+ const cap = compareCount(opts.maxCases ?? 100_000, 'maxCases', 1), params = compareCopy((opts.params ?? {})), kinds = this.r['spec'].inputs;
2857
+ const parameterKinds = this.r['spec'].params, finiteParams = !!finiteFields(parameterKinds, cap);
2858
+ const domain = opts.draw ? undefined : finiteFields(kinds, cap), r = this.rule, m = r.machine, run = r.interpreter({ compileHelpers: true }), ps = r.encodeParams(params), execute = this.compiled();
2859
+ let checked = 0, skipped = 0;
2860
+ const finish = (exhaustive, skippedParams = 0, failure) => ({
2861
+ ...compareResult(checked, exhaustive && finiteParams, skipped, skippedParams, failure),
2862
+ ...(parameterKinds.length ? { parameterScope: { kind: 'fixed', values: compareCopy(params) } } : {}),
2863
+ });
2864
+ if (m.pre && !evalC(m.pre, ps, { scalars: {}, maps: {} }, m))
2865
+ return finish(false, 1);
2866
+ const initial = run.init(ps), supplied = opts.edges ?? [];
2867
+ const edges = domain ? supplied.filter((edge, i) => !supplied.slice(0, i).some(old => sameRaw(old, edge))) : supplied;
2868
+ function* draws() {
2869
+ for (const edge of edges)
2870
+ yield compareCopy(edge);
2871
+ if (domain) {
2872
+ for (const value of domain.values())
2873
+ if (!edges.some(edge => sameRaw(edge, value)))
2874
+ yield value;
2875
+ }
2876
+ else
2877
+ for (let i = 0; i < trials; i++)
2878
+ yield opts.draw?.(rand) ?? Object.fromEntries(kinds.map(([n, k]) => [n, k.sample(rand, bound)]));
2879
+ }
2880
+ for (const values of draws()) {
2881
+ if (!allowed(m, run, ps, initial, r.encodeInput(values, params))) {
2882
+ skipped++;
2883
+ continue;
2884
+ }
2885
+ const ours = execute(values, params), theirs = compareFields(reference(compareCopy(values), compareCopy(params)));
2886
+ checked++;
2769
2887
  for (const [field, want] of Object.entries(theirs)) {
2770
- checked++;
2771
2888
  if (!sameRaw(ours[field], want))
2772
- return { checked, failure: `${this.name} at ${JSON.stringify(values)}: ${field} is ${shown(ours[field])} here, ${shown(want)} in the code it describes` };
2889
+ return finish(false, 0, `${this.name}, params ${JSON.stringify(params)}, at ${JSON.stringify(values)}: ${field} is ${shown(ours[field])} here, ${shown(want)} in the code it describes`);
2773
2890
  }
2774
2891
  }
2775
- return { checked };
2892
+ return finish(!!domain);
2776
2893
  }
2777
2894
  // The one-step rule it compiles to: the result's fields are its state (named out.<field>, apart from the arguments).
2778
2895
  get rule() {
@@ -2781,15 +2898,31 @@ export class Fun {
2781
2898
  return this.r.state(Object.fromEntries(fields.map(([k, t]) => { const kind = kindOf(t); return [name(k), kind.from(kind.empty())]; })))
2782
2899
  .step(env => Object.fromEntries(Object.entries(this.result(env)).map(([k, t]) => [name(k), t])));
2783
2900
  }
2784
- compiledRule;
2785
- // The result at these arguments (and params), from the compiled rule: numbers, and booleans for the conditions.
2786
- run(values, params = {}) {
2787
- this.compiledRule ??= (rule => ({ rule, gen: rule.compiled() }))(this.rule);
2788
- const { rule, gen } = this.compiledRule, ps = rule.encodeParams(params);
2789
- const kinds = Object.entries(this.result(this.r['env']({ flags: false, state: false, queries: false })));
2790
- const st = rule.decode(gen.step(ps, gen.init(ps), rule.encodeInput(values, params)));
2791
- return Object.fromEntries(kinds.map(([k]) => [k, st[`out.${k}`]]));
2901
+ runtimeRule;
2902
+ runners = {};
2903
+ runner(mode) {
2904
+ const cached = this.runners[mode];
2905
+ if (cached)
2906
+ return cached;
2907
+ // Custom helpers are source code, including callbacks serialized by fnSource. Refuse before materializing a
2908
+ // machine rather than implicitly invoking Function in a runtime which the caller chose to interpret.
2909
+ const helpers = this.r['spec'].fns;
2910
+ if (mode === 'interpreted' && helpers?.some(([, d]) => !sourceFreeDef(d)))
2911
+ throw new Error(`${this.name}: run() does not compile declared helper source (${helpers.map(([name]) => name).join(', ')}); use compiled() explicitly`);
2912
+ this.runtimeRule ??= { rule: this.rule, fields: Object.keys(this.result(this.r['env']({ flags: false, state: false, queries: false }))) };
2913
+ const { rule, fields } = this.runtimeRule, gen = mode === 'compiled' ? rule.compiled() : rule.interpreter();
2914
+ const execute = (values, params = {}) => {
2915
+ const ps = rule.encodeParams(params);
2916
+ const st = rule.decode(gen.step(ps, gen.init(ps), rule.encodeInput(values, params)));
2917
+ return Object.fromEntries(fields.map(k => [k, st[`out.${k}`]]));
2918
+ };
2919
+ this.runners[mode] = execute;
2920
+ return execute;
2792
2921
  }
2922
+ // The default runtime interprets terms without generating JavaScript.
2923
+ run(values, params = {}) { return this.runner('interpreted')(values, params); }
2924
+ // Explicit dynamic-code opt-in. Cache this callable at startup; it has run()'s argument and result types.
2925
+ compiled() { return this.runner('compiled'); }
2793
2926
  }
2794
2927
  export const fun = (name) => new Fun(rule(name));
2795
2928
  // The function a law was stated about. Variants of one function share its arguments, so a law's terms alone don't say
@@ -2797,6 +2930,76 @@ export const fun = (name) => new Fun(rule(name));
2797
2930
  const lawsOfFuns = new WeakMap();
2798
2931
  const lawOfFun = (f, d) => { lawsOfFuns.set(d, f); return d; };
2799
2932
  export const funOf = (d) => lawsOfFuns.get(d);
2933
+ const compareCount = (value, name, minimum = 0) => {
2934
+ if (!Number.isSafeInteger(value) || value < minimum)
2935
+ throw new RangeError(`${name} must be a safe integer at least ${minimum}`);
2936
+ return value;
2937
+ };
2938
+ // Determine cardinality before allocating or enumerating; custom and unbounded kinds sample instead.
2939
+ const finiteKind = (kind, cap) => {
2940
+ if (kind instanceof NatKind) {
2941
+ if (kind.maxValue === undefined || kind.maxValue >= cap)
2942
+ return undefined;
2943
+ const size = kind.maxValue + 1;
2944
+ return { size, values: function* () { for (let i = 0; i < size; i++)
2945
+ yield i; } };
2946
+ }
2947
+ if (kind instanceof BoolKind)
2948
+ return cap < 2 ? undefined : { size: 2, values: () => [false, true] };
2949
+ if (kind instanceof OneOfKind)
2950
+ return kind.values.length > cap ? undefined : { size: kind.values.length, values: () => kind.values };
2951
+ if (kind instanceof MaybeKind) {
2952
+ const inner = finiteKind(kind.of, cap - 1);
2953
+ return inner && { size: inner.size + 1, values: function* () { yield null; yield* inner.values(); } };
2954
+ }
2955
+ if (kind instanceof RecordKind)
2956
+ return finiteFields(Object.entries(kind.fields), cap);
2957
+ if (kind instanceof VariantKind) {
2958
+ let size = 0;
2959
+ const cases = [];
2960
+ for (const name of kind.names) {
2961
+ const domain = finiteFields(Object.entries(kind.cases[name]), cap - size);
2962
+ if (!domain)
2963
+ return undefined;
2964
+ size += domain.size;
2965
+ cases.push([name, domain]);
2966
+ }
2967
+ return { size, values: function* () { for (const [name, domain] of cases)
2968
+ for (const fields of domain.values())
2969
+ yield { [kind.tagKey]: name, ...fields }; } };
2970
+ }
2971
+ return undefined;
2972
+ };
2973
+ const finiteFields = (fields, cap) => {
2974
+ if (cap < 1)
2975
+ return undefined;
2976
+ let size = 1;
2977
+ const domains = [];
2978
+ for (const [name, kind] of fields) {
2979
+ const domain = finiteKind(kind, Math.floor(cap / size));
2980
+ if (!domain)
2981
+ return undefined;
2982
+ size *= domain.size;
2983
+ domains.push([name, domain]);
2984
+ }
2985
+ function* at(index, entries) {
2986
+ if (index === domains.length) {
2987
+ yield Object.fromEntries(entries);
2988
+ return;
2989
+ }
2990
+ const [name, domain] = domains[index];
2991
+ for (const value of domain.values())
2992
+ yield* at(index + 1, [...entries, [name, value]]);
2993
+ }
2994
+ return { size, values: () => at(0, []) };
2995
+ };
2996
+ const compareCopy = (value) => structuredClone(value);
2997
+ const compareFields = (value) => {
2998
+ if (!value || typeof value !== 'object' || Array.isArray(value) || typeof value.then === 'function')
2999
+ throw new TypeError('compare reference must return a synchronous object');
3000
+ return value;
3001
+ };
3002
+ const compareResult = (checked, exhaustive, skipped, skippedParams = 0, failure) => ({ checked, exhaustive: exhaustive && checked > 0 && !skipped && !skippedParams && !failure, ...(skipped ? { skipped } : {}), ...(skippedParams ? { skippedParams } : {}), ...(failure ? { failure } : {}) });
2800
3003
  // A loop runs `body` while `while` holds, each turn with fresh inputs; it halts if a rank over the state and params
2801
3004
  // (or a tuple of them, compared in order) drops on every turn.
2802
3005
  export class LoopRule {
@@ -2910,6 +3113,10 @@ function guidesOf(m) {
2910
3113
  } }];
2911
3114
  });
2912
3115
  }
3116
+ // Model-only negative evidence for inference: never a source-law verdict.
3117
+ export function refuteModelByRuns(r, laws, stepLaws = []) {
3118
+ return refuteByRuns(r, laws, stepLaws);
3119
+ }
2913
3120
  function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
2914
3121
  const m = r.machine;
2915
3122
  const run = interpret(m), rand = seeded(budget.seed ?? 13), bound = budget.bound, shown = shownRequest, guides = budget.mixed ? guidesOf(m) : [];
@@ -3007,7 +3214,9 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
3007
3214
  return { goal: `${l.name} @step`, witness: witness() };
3008
3215
  }
3009
3216
  }
3010
- catch {
3217
+ catch (e) {
3218
+ if (e instanceof WallExpired)
3219
+ throw e;
3011
3220
  return undefined;
3012
3221
  }
3013
3222
  return undefined;
@@ -3020,6 +3229,25 @@ const refutedVerdict = (out) => ({ proven: false, checked: false, goal: out.goal
3020
3229
  const noting = (r, ...xs) => { const ks = divisorsIn(xs); if (ks.size)
3021
3230
  r.dividesBy(...ks); return r; };
3022
3231
  export function proveRule(r, laws, opts = {}) {
3232
+ const ms = typeof opts.search === 'object' ? opts.search.ms : undefined;
3233
+ const run = () => {
3234
+ try {
3235
+ checkWall('rule preflight');
3236
+ const out = proveRuleIn(r, laws, opts);
3237
+ checkWall('rule result');
3238
+ return out;
3239
+ }
3240
+ catch (e) {
3241
+ if (!(e instanceof WallExpired))
3242
+ throw e;
3243
+ return { proven: false, checked: false, stuck: 'unknown', why: e.message };
3244
+ }
3245
+ };
3246
+ // One absolute wall for setup, sampling, generation and proof, not a fresh
3247
+ // allowance for each phase. Nested callers can only shorten it.
3248
+ return translationVerdict(r, laws, ms === undefined ? run() : withWall(searchWall(ms), run));
3249
+ }
3250
+ function proveRuleIn(r, laws, opts) {
3023
3251
  r = r.withSumsOf(laws);
3024
3252
  noting(r, laws);
3025
3253
  const refuted = refuteByRuns(r, laws);
@@ -3051,8 +3279,19 @@ export function proveSteps(r, laws, stepLaws, opts = {}) {
3051
3279
  const ms = typeof opts.search === 'object' ? opts.search.ms : undefined;
3052
3280
  // From any state, the caller's budget includes preflight runs and all initial
3053
3281
  // goals, not a fresh budget per goal. Keep reachable-state search unchanged.
3054
- return opts.from !== 'any' || ms === undefined ? proveStepsIn(r, laws, stepLaws, opts)
3055
- : withWall(performance.now() + ms, () => proveStepsIn(r, laws, stepLaws, opts));
3282
+ const run = () => {
3283
+ try {
3284
+ return proveStepsIn(r, laws, stepLaws, opts);
3285
+ }
3286
+ catch (e) {
3287
+ if (!(e instanceof WallExpired))
3288
+ throw e;
3289
+ return { proven: false, checked: false, stuck: 'unknown', why: e.message };
3290
+ }
3291
+ };
3292
+ const verdict = opts.from !== 'any' || ms === undefined ? run()
3293
+ : withWall(performance.now() + ms, run);
3294
+ return translationVerdict(r, [...laws, ...stepLaws], verdict);
3056
3295
  }
3057
3296
  function proveStepsIn(r, laws, stepLaws, opts) {
3058
3297
  r = r.withSumsOf(laws, stepLaws);
@@ -3359,6 +3598,9 @@ const withAssumes = (found) => (found.length ? { assumes: reachableBy(found) } :
3359
3598
  // The rule a keyed liveness is proven on: the rule with its key as one more param (a natural), any other rule as it is.
3360
3599
  export const keyed = (r, l) => (l.forall ? r.params({ [l.forall]: nat }) : r);
3361
3600
  export function proveLeadsTo(r, laws, l, opts = {}) {
3601
+ return translationVerdict(r, [...laws, l], proveLeadsToIn(r, laws, l, opts));
3602
+ }
3603
+ function proveLeadsToIn(r, laws, l, opts) {
3362
3604
  r = keyed(r, l).withSumsOf(laws, l);
3363
3605
  noting(r, laws, l);
3364
3606
  if (laws.some(law => law.some?.length))
@@ -3408,7 +3650,7 @@ export function refuteLeadsTo(r, laws, l, opts = {}) {
3408
3650
  // prover reads (the counted one inside a counted search): past it the verdict is unknown.
3409
3651
  export const proveDecision = (d, opts = {}) => {
3410
3652
  const go = () => (d.steps ? proveSteps(d.steps.rule, [], [d.steps.law], { search: false }) : goalsVerdict([d.goal]));
3411
- return opts.ms === undefined ? go() : withDeadline(clock() + opts.ms, go);
3653
+ return translationVerdict(d.rule, [d.goal], opts.ms === undefined ? go() : withDeadline(clock() + opts.ms, go));
3412
3654
  };
3413
3655
  // A decision's callbacks against its condition, on random params and requests: `given` and `then` each run with every
3414
3656
  // value known, against what the interpreter evaluates of the decision built from them.
@@ -25,6 +25,7 @@ import { fromModel, namesOf } from "./extract.js";
25
25
  import { check, sandbox } from "./extract-check.js";
26
26
  import { Parts, readSchedule, replaySchedule, scheduleConforms, scheduleRule } from "./effect-schedule.js";
27
27
  import { asRule, lift } from "./system.js";
28
+ import { attachSource, inheritSource } from "./source-check.js";
28
29
  import { rewritePrims } from "./effect-prims.js";
29
30
  export { proveRule, proveSteps } from "./dsl.js";
30
31
  export { jitterRun, replaySchedule, scheduleConforms, stepper } from "./effect-schedule.js";
@@ -686,7 +687,9 @@ export function withLemmas(x, opts = {}) {
686
687
  catch {
687
688
  v = undefined;
688
689
  }
689
- if (v?.proven && v.checked) {
690
+ // These are mathematical supports, not source claims. The caller's marked
691
+ // rule still requires native finalization; a native translation error is not admitted.
692
+ if (v && ((v.proven && v.checked) || (v.kernelProven === true && v.translation === 'unchecked'))) {
690
693
  inv.push(l, ...(v.found?.laws ?? []).map(f => f.law));
691
694
  proven.push(l.name);
692
695
  }
@@ -901,6 +904,8 @@ function fibered(code, file, entry, E, opts) {
901
904
  const one2 = one.rule;
902
905
  const ints = [...one2.kindsOfState().filter(([n]) => shared.includes(n) && shared.includes(`${n}$neg`)), ...one2.kindsOfCells().filter(([n, k]) => k.vars(n).every(p => !local(p)))];
903
906
  const rule = asRule({ ...lifted, name: `${m0.name}, every fiber` }, Object.fromEntries([...parts.params, ...parts.inputs].filter(whole).concat(ints)));
907
+ // Lifting is not transparent native replay: retain provenance, not the old journal.
908
+ inheritSource(one.rule, rule);
904
909
  const names = (one.names ?? []).filter(n => !(n.role === 'state' && local(n.rule)) && n.role !== 'result' && !made.has(n.code));
905
910
  const inv = (one.invariants ?? []).filter(l => ![...JSON.stringify(l.holds).matchAll(/"name":"([^"]*)"/g)].some(m => local(m[1])));
906
911
  const steps = split.map((mt, mi) => ({ name: mt.name, steps: mt.units.length, base: (mi + 1) * 100 }));
@@ -981,6 +986,8 @@ function fromScheduleEntry(code, file, e, E, opts) {
981
986
  const runs = opts.check?.runs ?? 60, c = scheduleConforms(sr, make, E, { runs, depth: 14 });
982
987
  const evidence = { runs, requests: c.checked, fromStates: 0, probes: { conditions: 0, witnesses: 0, steps: 0 }, refusedBoth: 0, outside: 0, edge: 0, compiledAgreed: c.checked, coverage: { arms: 0, hit: 0, missed: [] }, ms: Date.now() - t0, ...(c.failure ? { mismatch: c.failure } : {}) };
983
988
  const source = `// ${e.name}: ${e.expr.getText().replace(/\s+/g, ' ')}\n${sr.rule.machine.name}: state ${Object.keys(sr.rule.machine.state).join(', ')}; inputs ${sr.rule.machine.inputs.join(', ')}${sr.rule.machine.params.length ? `; params ${sr.rule.machine.params.join(', ')}` : ''}`;
989
+ // Schedule conformance checks transitions, not native source-law semantics.
990
+ attachSource(sr.rule, evidence, []);
984
991
  if (c.failure)
985
992
  return { ok: false, rule: sr.rule, source, refusals: [{ where: file, what: `the rule and Effect's own schedule part: ${c.failure}` }], notes, names: sr.names, evidence };
986
993
  return { ok: true, rule: sr.rule, source, refusals: [], notes, names: sr.names, evidence, schedule: sr, replay: run => replaySchedule(sr, make(run.params), E, run) };
@@ -9,7 +9,7 @@ export declare function substVarsE(e: E, s: Record<string, E>): E;
9
9
  export declare function substVars(c: C, s: Record<string, E>): C;
10
10
  export declare function small(m: Machine, p: Env, b: number, cap?: number, work?: number, walks?: number): State[];
11
11
  export declare function ghostOf(m: Machine, law: Law): SomeWitness | undefined;
12
- export declare function smallOf(m: Machine): {
12
+ export declare function smallOf(m: Machine, source?: Machine): {
13
13
  p: Env;
14
14
  sts: State[];
15
15
  }[];