gdp-wired 0.31.1 → 0.32.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 (72) hide show
  1. package/README.md +82 -6
  2. package/dist/core/c/reader.d.ts +86 -0
  3. package/dist/core/c/reader.js +860 -0
  4. package/dist/core/cli.d.ts +66 -0
  5. package/dist/core/cli.js +582 -0
  6. package/dist/core/dsl.d.ts +4 -2
  7. package/dist/core/dsl.js +22 -12
  8. package/dist/core/effect.d.ts +6 -4
  9. package/dist/core/effect.js +48 -10
  10. package/dist/core/ex/harness.exs +177 -0
  11. package/dist/core/ex/json.exs +46 -0
  12. package/dist/core/ex/reader.exs +462 -0
  13. package/dist/core/exists.d.ts +3 -0
  14. package/dist/core/exists.js +3 -1
  15. package/dist/core/extract-c.d.ts +35 -0
  16. package/dist/core/extract-c.js +424 -0
  17. package/dist/core/extract-check.js +27 -6
  18. package/dist/core/extract-ex.d.ts +16 -0
  19. package/dist/core/extract-ex.js +33 -0
  20. package/dist/core/extract-go-check.d.ts +28 -0
  21. package/dist/core/extract-go-check.js +639 -0
  22. package/dist/core/extract-go.d.ts +231 -0
  23. package/dist/core/extract-go.js +1166 -0
  24. package/dist/core/extract-jvm.d.ts +23 -0
  25. package/dist/core/extract-jvm.js +220 -0
  26. package/dist/core/extract-print.js +17 -7
  27. package/dist/core/extract-py.d.ts +15 -0
  28. package/dist/core/extract-py.js +31 -0
  29. package/dist/core/extract-rb.d.ts +17 -0
  30. package/dist/core/extract-rb.js +31 -0
  31. package/dist/core/extract-read.d.ts +20 -0
  32. package/dist/core/extract-read.js +46 -6
  33. package/dist/core/extract-rs.d.ts +12 -0
  34. package/dist/core/extract-rs.js +306 -0
  35. package/dist/core/extract-shapes.d.ts +2 -0
  36. package/dist/core/extract-shapes.js +6 -5
  37. package/dist/core/extract-step.d.ts +806 -0
  38. package/dist/core/extract-step.js +4141 -0
  39. package/dist/core/extract-swift.d.ts +27 -0
  40. package/dist/core/extract-swift.js +484 -0
  41. package/dist/core/extract-xstate.d.ts +10 -3
  42. package/dist/core/extract-xstate.js +50 -4
  43. package/dist/core/extract.d.ts +22 -3
  44. package/dist/core/extract.js +107 -18
  45. package/dist/core/go/go.mod +3 -0
  46. package/dist/core/go/reader.go +901 -0
  47. package/dist/core/infer.js +1770 -52
  48. package/dist/core/jvm/Harness.java +361 -0
  49. package/dist/core/jvm/JavaReader.java +825 -0
  50. package/dist/core/jvm/Jvm.java +332 -0
  51. package/dist/core/jvm/KtReader.java +960 -0
  52. package/dist/core/jvm/Rt.java +10 -0
  53. package/dist/core/laws.d.ts +66 -0
  54. package/dist/core/laws.js +522 -0
  55. package/dist/core/py/harness.py +328 -0
  56. package/dist/core/py/reader.py +447 -0
  57. package/dist/core/rb/harness.rb +233 -0
  58. package/dist/core/rb/reader.rb +375 -0
  59. package/dist/core/rs/Cargo.lock +108 -0
  60. package/dist/core/rs/Cargo.toml +14 -0
  61. package/dist/core/rs/src/main.rs +681 -0
  62. package/dist/core/swift/Harness.swift +124 -0
  63. package/dist/core/swift/Main.swift +34 -0
  64. package/dist/core/swift/Package.swift +13 -0
  65. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +1341 -0
  66. package/dist/kernel/epr.d.ts +35 -0
  67. package/dist/kernel/epr.js +1676 -0
  68. package/dist/kernel/prove.d.ts +44 -0
  69. package/dist/kernel/prove.js +657 -50
  70. package/dist/lean-kernel/emit.d.ts +1 -0
  71. package/dist/lean-kernel/emit.js +21 -4
  72. package/package.json +53 -2
@@ -32,10 +32,10 @@
32
32
  // rules it out (and the most of those seen) is added; a chosen candidate that nothing supports, or that makes a proof slow, is dropped; the set proven as a whole
33
33
  // is the answer, after each chosen candidate the proof doesn't need is taken out again
34
34
  import { quietly } from "./cyclic.js";
35
- import { all, any, atMost, divisorsIn, evalC, evalE, get, interpret, machineTerms, modName, n, not, plus, same, seeded, times, withArithmetic, x } from "./machine.js";
35
+ import { all, any, atMost, carriedView, loadJs, divisorsIn, evalC, evalE, get, interpret, machineTerms, fnValue, modName, n, not, plus, same, seeded, times, walk, withArithmetic, x } from "./machine.js";
36
36
  import { bool, proveRule, proveSteps, verdictOf } from "./dsl.js";
37
37
  import { allowed, keysOf, linKey, watch } from "./watch.js";
38
- import { clock, counted, grow, keyValue, lawInstances, proveLaw, proveLaws, proveStepLaws, stepLawInstances, usedHyps, withDeadline, withModels, withTrees } from "../kernel/prove.js";
38
+ import { clock, counted, decideLaw, decideNote, machineKey, memoHits, withStrict, fullRate, grow, keyValue, lawInstances, proveLaw, proveLaws, proveSetFast, proveStepLaws, stepLawInstances, usedHyps, withDeadline, withModels, withTrees, withWall } from "../kernel/prove.js";
39
39
  import { assumed, obligations, plainOf, stepLawObligations, substC } from "../kernel/kernel.js";
40
40
  import { env, gcd, work } from "./solver.js";
41
41
  import { bgcd } from "./q.js";
@@ -62,7 +62,7 @@ const inferTrace = !!env.GDP_INFER_TRACE;
62
62
  // the control state up to 7, and 128 of its values; a goal tried with 6 parts of the set before all of it, 2 forms added
63
63
  // at a time.
64
64
  const joinOn = env.GDP_JOIN !== '0';
65
- const joinShare = 0.6, joinQueryMs = 8000, joinRequestMs = 150, joinWalk = 8, joinPairs = 10, joinRaises = 2, joinSparse = 4, joinCoef = 1000;
65
+ const joinShare = 0.6, joinQueryMs = 8000, joinGrowWall = 2000, joinRequestMs = 150, joinWalk = 8, joinPairs = 10, joinRaises = 2, joinSparse = 4, joinCoef = 1000;
66
66
  const joinExtras = 24, joinTries = 40, joinBits = 7, joinKeys = 128, joinAttempts = 6, joinAdd = 2;
67
67
  // GDP_JOIN_CORE=0: the join's goals by the prover's trees alone, as before (else a model, or a refutation's core, of the
68
68
  // CDCL search first, at a quarter of the goal's budget).
@@ -222,23 +222,53 @@ function keySorts(m, laws, pairing) {
222
222
  const a = hi && name(hi[0]), b = lo && name(lo[0]);
223
223
  return a && b ? [a, b] : undefined;
224
224
  };
225
+ // (a key of three or more parts, N²·a + N·b + c: its parts, each a place of its own, `${k}:${i}`)
226
+ const arity = new Map();
227
+ const parts = (key, name) => {
228
+ if (!pairing?.n)
229
+ return undefined;
230
+ const lin = new Map();
231
+ if (!linKey(key, () => true, 1, lin) || (lin.get('1') ?? 0) !== pairing.c)
232
+ return undefined;
233
+ const vs = [...lin].filter(([v, c]) => v !== '1' && c).sort((a, b) => b[1] - a[1]), ns = vs.map(([v]) => name(v));
234
+ return vs.length >= 3 && vs.every(([, c], i) => c === pairing.n ** (vs.length - 1 - i)) && ns.every(Boolean) ? ns : undefined;
235
+ };
225
236
  const kids = (t, f) => { for (const v of Object.values(t))
226
237
  if (v && typeof v === 'object')
227
238
  (Array.isArray(v) ? v : [v]).forEach(y => { if (y && typeof y === 'object' && 'op' in y)
228
239
  f(y); }); };
229
240
  const walk = (t, name) => {
230
241
  if (t.op === 'get') {
231
- if (!(t.map in (m.maps ?? {}))) {
242
+ // (a carried map's key has its cells' sort, as a map's: the quorum a request brings, read where the stored one is)
243
+ const carried = (m.inputMaps ?? []).includes(t.map);
244
+ // (a function of a key: its argument's sort, `F:f`)
245
+ if (m.fns?.[t.map] && t.key.op === 'var' && name(t.key.name)) {
246
+ union(name(t.key.name), `F:${t.map}`);
247
+ return;
248
+ }
249
+ if (!carried && !(t.map in (m.maps ?? {}))) {
232
250
  walk(t.key, name);
233
251
  return;
234
252
  }
235
- const sp = split(t.key, name);
253
+ if (carried) {
254
+ if (t.key.op === 'var' && name(t.key.name))
255
+ union(name(t.key.name), `M:${t.map}`);
256
+ else
257
+ walk(t.key, name);
258
+ return;
259
+ }
260
+ const sp = split(t.key, name), ps = parts(t.key, name);
236
261
  if (sp) {
237
262
  composed.add(t.map);
238
263
  union(sp[0], 'hi');
239
264
  union(sp[1], 'lo');
240
265
  return;
241
266
  }
267
+ if (ps) {
268
+ arity.set(t.map, ps.length);
269
+ ps.forEach((q, i) => union(q, `${t.map}:${i}`));
270
+ return;
271
+ }
242
272
  if (t.key.op === 'var' && name(t.key.name)) {
243
273
  plainRead.add(t.map);
244
274
  union(name(t.key.name), `M:${t.map}`);
@@ -258,6 +288,14 @@ function keySorts(m, laws, pairing) {
258
288
  union(a, b);
259
289
  return;
260
290
  }
291
+ // (a write at every key of k parts at one: z = N²·n + N·k + v)
292
+ if (t.op === '=' && t.a.op === 'var' && name(t.a.name)?.startsWith('M:')) {
293
+ const mp = name(t.a.name).slice(2), ps = parts(t.b, name);
294
+ if (ps) {
295
+ arity.set(mp, ps.length);
296
+ ps.forEach((q, i) => union(q, `${mp}:${i}`));
297
+ }
298
+ }
261
299
  kids(t, y => walk(y, name));
262
300
  };
263
301
  const inputs = new Set(m.inputs), rule = (v) => (inputs.has(v) ? v : undefined);
@@ -278,6 +316,12 @@ function keySorts(m, laws, pairing) {
278
316
  const lawName = (l) => { const own = new Set([l.forall, ...(l.keys ?? [])]); return (v) => (own.has(v) ? `L:${l.name}:${v}` : undefined); };
279
317
  for (const l of laws)
280
318
  walk(l.holds, lawName(l));
319
+ // (a map read at a composed key is no plain read where a write at every key reads it at its own key)
320
+ for (const mp of composed)
321
+ plainRead.delete(mp);
322
+ // (a map of keys of k parts read at a write at every key's own key is no plain read)
323
+ for (const mp of arity.keys())
324
+ plainRead.delete(mp);
281
325
  return {
282
326
  find,
283
327
  sortOf: (l, v) => find(`L:${l.name}:${v}`),
@@ -292,15 +336,19 @@ function keySorts(m, laws, pairing) {
292
336
  kids(t, see);
293
337
  };
294
338
  see(l.holds);
295
- // (the antecedent's conditions on the keys alone: k < 64, a ≠ b)
296
- const onKeys = (c) => { const s2 = JSON.stringify(c); return !s2.includes('"op":"get"') && [...s2.matchAll(/"name":"([^"]+)"/g)].every(q => own.has(q[1])); };
339
+ // (the antecedent's conditions on the keys, with the state and params beside: k < 64, a ≠ b, k < size, j < next)
340
+ const onKeys = (c) => { const s2 = JSON.stringify(c), ns = [...s2.matchAll(/"name":"([^"]+)"/g)].map(q => q[1]); return !s2.includes('"op":"get"') && ns.some(v => own.has(v)) && ns.every(v => own.has(v) || v in m.state || m.params.includes(v)); };
297
341
  if (l.holds.op === 'or')
298
342
  for (const y of l.holds.xs)
299
343
  if (y.op === 'not')
300
344
  guards.push(...conj(y.x).filter(onKeys));
301
345
  return { composites, guards };
302
346
  },
303
- composedMaps: [...composed],
347
+ // (a guard that reads the state or params beside the keys: a domain that moves)
348
+ moving: (g, bound) => [...JSON.stringify(g).matchAll(/"name":"([^"]+)"/g)].some(q => !bound.includes(q[1])),
349
+ composedMaps: [...composed], plainRead: [...plainRead], arity,
350
+ // (a key of k parts at these key terms)
351
+ composeAll: (ts) => { const k = ts.reduce((acc, t) => plus(times(pairing.n, acc), t)); return pairing.c ? plus(k, n(pairing.c)) : k; },
304
352
  compose: (a, b) => { const k = plus(times(pairing.n, a), b); return pairing.c ? plus(k, n(pairing.c)) : k; },
305
353
  plainMaps: (sort) => [...plainRead].filter(mp => find(`M:${mp}`) === sort),
306
354
  valuesAt: (st, sort) => {
@@ -315,6 +363,11 @@ function keySorts(m, laws, pairing) {
315
363
  if (find('lo') === sort)
316
364
  ks.add((k - pairing.c) % pairing.n);
317
365
  }
366
+ const ar = arity.get(mp);
367
+ if (ar && pairing?.n && k >= pairing.c)
368
+ for (let i = ar - 1, r = k - pairing.c; i >= 0; i--, r = Math.floor(r / pairing.n))
369
+ if (find(`${mp}:${i}`) === sort)
370
+ ks.add(i ? r % pairing.n : r);
318
371
  }
319
372
  const xs = [...ks].sort((a, b) => a - b);
320
373
  return [...xs, xs.length ? xs.at(-1) + 1 : 0];
@@ -684,12 +737,13 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
684
737
  }
685
738
  return out;
686
739
  };
687
- const prove = (ls) => {
740
+ // (`fast`: the set's proof asked again after a drop, kernel/prove.ts's proveSetFast: what was settled kept where it stands)
741
+ const prove = (ls, fast = false) => {
688
742
  proofs++;
689
743
  const { r: searchRule, m: mm } = forLaws(ls);
690
744
  if (searchRule)
691
- return stepLaws.length ? proveSteps(searchRule, ls, stepLaws, { search: false }) : proveRule(searchRule, ls, { search: false });
692
- const out = stepLaws.length ? proveStepLaws(mm, ls, stepLaws) : proveLaws(mm, ls);
745
+ return stepLaws.length ? proveSteps(searchRule, ls, stepLaws, { search: false }) : proveRule(searchRule, ls, { search: false, fast });
746
+ const out = stepLaws.length ? proveStepLaws(mm, ls, stepLaws) : (fast ? proveSetFast : proveLaws)(mm, ls);
693
747
  return verdictOf(out);
694
748
  };
695
749
  const stats = (samples, candidates, alive) => ({ samples, candidates, alive, proofs, ms: Math.round(performance.now() - t0), stopped: stop() });
@@ -699,9 +753,9 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
699
753
  // --- runs ------------------------------------------------------------------------------------------------------------
700
754
  const run = interpret(m), rand = seeded(17), kinds = rule ? rule.kindsOfState() : [];
701
755
  const given = rule ? [...rule.kindLaws().filter(k => !laws.some(l => l.name === k.name)), ...laws] : laws;
702
- const randomParams = (bound) => (rule ? rule.randomParams(rand, bound) : Object.fromEntries(m.params.map(p => [p, rand(bound + 1)])));
703
- const randomInput = (params, bound) => (rule ? rule.randomInput(rand, bound, params)
704
- : { ...Object.fromEntries(m.inputs.map(i => [i, rand(bound + 1)])), ...Object.fromEntries((m.inputMaps ?? []).map(i => [i, new Map()])) });
756
+ const randomParams = (bound, r = rand) => (rule ? rule.randomParams(r, bound) : Object.fromEntries(m.params.map(p => [p, r(bound + 1)])));
757
+ const randomInput = (params, bound, r = rand) => (rule ? rule.randomInput(r, bound, params)
758
+ : { ...Object.fromEntries(m.inputs.map(i => [i, r(bound + 1)])), ...Object.fromEntries((m.inputMaps ?? []).map(i => [i, new Map()])) });
705
759
  const samples = [], cap = 3000;
706
760
  const keep = (s) => { if (samples.length < cap)
707
761
  samples.push(s);
@@ -714,7 +768,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
714
768
  const mapsText = (st) => JSON.stringify(Object.values(st.maps).map(c => [...c]));
715
769
  // Counted: `runs` requests tried at least, and on until the samples are full (a trial keeps its start at least, so as
716
770
  // many trials as they hold fill them), the trials at most `runs` or that many. Timed: `runsMs` of wall time.
717
- const runsTimed = timed || opts.runsMs !== undefined, runsUntil = Math.min(wallUntil, performance.now() + (opts.runsMs ?? 500)), least = opts.runs ?? inferRuns;
771
+ const runsTimed = timed || opts.runsMs !== undefined, runsUntil = Math.min(wallUntil, performance.now() + (opts.runsMs ?? 500)), least = opts.runs ?? Math.min(inferRuns, Math.max(2000, 4 * ms));
718
772
  const moreRuns = (trial) => (runsTimed ? performance.now() < runsUntil : trial < Math.max(cap, least) && (used.tries < least || samples.length < cap) && !stop());
719
773
  let trials = 0;
720
774
  // (an assumption with "there exists", a value the request brings, may admit no request at a small bound, a multiple
@@ -931,8 +985,12 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
931
985
  pick(3, mags, terms, scalarOk, false);
932
986
  else if (choose(3, P) * 8 <= maxCandidates / 2)
933
987
  pick(3, [1], terms, scalarOk, false);
988
+ // (a map at a composed key and a map at a plain one read at one key are of two sorts: Leader[k] against
989
+ // VoteRequestMsg[k], a pair relation's raw key, is no law of the rule's)
990
+ const pairMaps = new Set(pairingOf(m)?.n ? keySorts(m, laws, pairingOf(m)).composedMaps : []), pairOf = (i) => pairMaps.has(atoms[i].parts[0][0]);
991
+ const sortedCells = (acc) => { const cs = acc.filter(([i]) => atoms[i].cell); return cs.every(([i]) => pairOf(i)) || cs.every(([i]) => !pairOf(i)); };
934
992
  if (cellAtoms.length) {
935
- const all = atoms.flatMap((_, i) => (modeOf(i)?.choice ? [] : [i])), cellOk = (acc) => acc.some(([i]) => atoms[i].cell) && acc.filter(([i]) => !atoms[i].cell).length <= 1;
993
+ const all = atoms.flatMap((_, i) => (modeOf(i)?.choice ? [] : [i])), cellOk = (acc) => acc.some(([i]) => atoms[i].cell) && acc.filter(([i]) => !atoms[i].cell).length <= 1 && sortedCells(acc);
936
994
  pick(1, [1], cellAtoms, () => true, true);
937
995
  pick(2, [1], all, cellOk, true);
938
996
  if (choose(3, A) * 8 <= maxCandidates / 4)
@@ -965,7 +1023,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
965
1023
  forms.push({ coef, d: b, cells, size: sizeOf(coef) + 1 + (cells ? 10 : 0) });
966
1024
  if (coef.length > 2)
967
1025
  continue;
968
- const here = guards.filter(mode => !coef.some(([i]) => i === mode.atom) && (cells || !atoms[mode.atom].cell));
1026
+ const here = guards.filter(mode => !coef.some(([i]) => i === mode.atom) && (cells ? !atoms[mode.atom].cell || sortedCells([...coef, [mode.atom, 1]]) : !atoms[mode.atom].cell));
969
1027
  const most = here.map(() => new Map()), away = cells ? keyNots.map(() => -Infinity) : [];
970
1028
  for (let j = 0; j < N; j += cells ? strideK : strideS) {
971
1029
  const value = at(coef, vals, j);
@@ -1148,6 +1206,28 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1148
1206
  const body = f.when ? any(condOf({ coef: f.when.coef.map(([i, c]) => [i, -c]), d: -f.when.d - 1, cells: false, size: 0 }), atMost(lhs, rhs)) : atMost(lhs, rhs);
1149
1207
  return !f.guard ? body : 'keyNot' in f.guard ? any(same(x(KEY), x(atoms[f.guard.keyNot].parts[0][0])), body) : any(notAt(f.guard.atom, f.guard.value, f.guard.hi), body);
1150
1208
  };
1209
+ // A view's frame as builder code (its keys by their names; comparisons of a name with a name or a constant), and the
1210
+ // state and params it reads.
1211
+ const frameSource = (v) => {
1212
+ const ren = new Map(v.vars.map((k2, i) => [k2, v.names[i]])), reads = [];
1213
+ const name = (t) => (t.op !== 'var' ? undefined : ren.get(t.name) ?? (reads.push(t.name), t.name));
1214
+ const c = (t) => {
1215
+ if (t.op === 'not') {
1216
+ const y = c(t.x);
1217
+ return y && `${y}.not()`;
1218
+ }
1219
+ if (t.op === 'and') {
1220
+ const xs = t.xs.map(c);
1221
+ return xs.length && xs.every(Boolean) ? xs.slice(1).reduce((a, b) => `${a}.and(${b})`, xs[0]) : undefined;
1222
+ }
1223
+ if (t.op !== '<' && t.op !== '<=' && t.op !== '=')
1224
+ return undefined;
1225
+ const a = name(t.a), b = t.b.op === 'const' ? String(t.b.value) : name(t.b);
1226
+ return a && b ? `${a}.${t.op === '<' ? 'lt' : t.op === '<=' ? 'atMost' : 'eq'}(${b})` : undefined;
1227
+ };
1228
+ const src = c(v.frame);
1229
+ return src ? { binder: v.names.length === 1 ? v.names[0] : `(${v.names.join(', ')})`, src, reads } : undefined;
1230
+ };
1151
1231
  // The builder call, for a rule whose atoms are its own variables (naturals, or integers alone).
1152
1232
  const sourceOf = (f, text) => {
1153
1233
  if (!rule || f.when || f.mod || f.also || f.never || f.nevers || f.cube || [...f.coef.map(([i]) => i), ...(f.guard && 'atom' in f.guard ? [f.guard.atom] : [])].some(i => atoms[i].term))
@@ -1156,18 +1236,24 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1156
1236
  const ints = f.coef.filter(([i]) => atoms[i].int).length;
1157
1237
  if (ints && ints !== f.coef.length)
1158
1238
  return undefined;
1159
- // (a view's cell: its map at x or at y; over two plain keys alone, as the frame is then x ≠ y)
1160
- if (f.view !== undefined && !views[f.view].printable)
1239
+ // (a view's cell: its map at x or at y, a view of one or two plain keys whose frame compares names and constants)
1240
+ const fr = f.view !== undefined ? frameSource(views[f.view]) : undefined;
1241
+ if (f.view !== undefined && (!views[f.view].printable || !fr))
1161
1242
  return undefined;
1162
1243
  const mapOf = (i) => { const a = atoms[i], p = a.parts[0][0]; return a.place !== undefined ? p.slice(2, p.lastIndexOf(AT)) : p; };
1163
1244
  const ref = (i) => (atoms[i].place !== undefined ? `${mapOf(i)}.at(${atoms[i].place === 0 ? 'x' : 'y'})` : atoms[i].cell ? `${atoms[i].parts[0][0]}.at(k)` : nameOf(i));
1164
1245
  // (a cell of a map of yes/nos, at k or at x or y, reads as its 0/1 term too)
1165
1246
  const boolCell = (i) => (atoms[i].cell || atoms[i].place !== undefined) && rule.kindsOfCells().some(([mp, kd]) => mp === mapOf(i) && kd === bool);
1166
1247
  const val = (i) => { const mo = modeOf(i); return mo?.choice && !atoms[i].cell ? `${ref(i)}.index` : (mo?.bool && !atoms[i].cell) || boolCell(i) ? `${ref(i)}.n` : ref(i); };
1167
- const cond = (i, value, hi) => { const mo = modeOf(i); if (hi !== undefined)
1168
- return hi === Infinity ? `${ref(i)}.atLeast(${value})` : `${ref(i)}.atLeast(${value}).and(${ref(i)}.atMost(${hi}))`; return mo?.choice && !atoms[i].cell ? `${ref(i)}.is('${mo.choice[value]}')` : mo?.bool && !atoms[i].cell ? (value === 1 ? ref(i) : `${ref(i)}.not()`) : `${ref(i)}.eq(${value})`; };
1169
- const args = `({${[...new Set(used.map(i => (atoms[i].cell || atoms[i].place !== undefined ? mapOf(i) : nameOf(i))))].join(', ')}})`;
1170
- const wrap = (body) => (f.cells ? `forall(k => ${body})` : f.view !== undefined ? `forall((x, y) => x.eq(y).not().implies(${body}))` : body);
1248
+ // (a yes/no, a cell of yes/nos too, as itself or its negation; a level of any value by its number)
1249
+ const cond = (i, value, hi) => {
1250
+ const mo = modeOf(i), v = val(i);
1251
+ if (hi !== undefined)
1252
+ return hi === Infinity ? `${v}.atLeast(${value})` : `${v}.atLeast(${value}).and(${v}.atMost(${hi}))`;
1253
+ return mo?.choice && !atoms[i].cell ? `${ref(i)}.is('${mo.choice[value]}')` : (mo?.bool && !atoms[i].cell) || boolCell(i) ? (value === 1 ? ref(i) : `${ref(i)}.not()`) : `${v}.eq(${value})`;
1254
+ };
1255
+ const args = `({${[...new Set([...used.map(i => (atoms[i].cell || atoms[i].place !== undefined ? mapOf(i) : nameOf(i))), ...(fr?.reads ?? [])])].join(', ')}})`;
1256
+ const wrap = (body) => (f.cells ? `forall(k => ${body})` : fr ? `forall(${fr.binder} => ${fr.src}.implies(${body}))` : body);
1171
1257
  if (f.unreachable)
1172
1258
  return `r.law('${text}', ${args} => ${cond(f.unreachable.atom, f.unreachable.value, f.unreachable.hi)}.not())`;
1173
1259
  if (f.cong) {
@@ -1279,6 +1365,48 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1279
1365
  }
1280
1366
  return out;
1281
1367
  };
1368
+ // A kernel witness's function values (a function the kernel knows by its facts alone: the model's own), the steps and
1369
+ // the views reading them where it names them and the interpreter's elsewhere, within f.
1370
+ const withFnsOf = (w, f) => {
1371
+ const fns = m.fns, saved = [], named = { ...Object.fromEntries([...scalars, ...m.params, ...m.inputs].map(v => [v, 0])), ...w };
1372
+ for (const [name, fn] of Object.entries(fns ?? {})) {
1373
+ if (fn.call || fn.recur)
1374
+ continue;
1375
+ const table = {};
1376
+ for (const [c, v] of Object.entries(w))
1377
+ if (c.startsWith(`${name}[`) && c.endsWith(']')) {
1378
+ const key = keyValue(c, named);
1379
+ if (key !== undefined)
1380
+ table[key] = v;
1381
+ }
1382
+ if (Object.keys(table).length) {
1383
+ saved.push([name, fn]);
1384
+ fns[name] = { ...fn, js: `(k) => (${JSON.stringify(table)})[k] ?? (${fn.js})(k)` };
1385
+ }
1386
+ }
1387
+ try {
1388
+ return f();
1389
+ }
1390
+ finally {
1391
+ for (const [name, fn] of saved)
1392
+ fns[name] = fn;
1393
+ }
1394
+ };
1395
+ // A kernel witness's request: its inputs, and each map it carries at the cells the model names (a quorum).
1396
+ const requestOf = (w) => {
1397
+ const out = Object.fromEntries(m.inputs.map(i => [i, w[i] ?? 0])), named = { ...Object.fromEntries([...scalars, ...m.params, ...m.inputs].map(v => [v, 0])), ...w };
1398
+ for (const q of m.inputMaps ?? []) {
1399
+ const cells = new Map();
1400
+ for (const [name, value] of Object.entries(w))
1401
+ if (name.startsWith(`${q}[`) && name.endsWith(']')) {
1402
+ const key = keyValue(name, named);
1403
+ if (key !== undefined)
1404
+ cells.set(key, value);
1405
+ }
1406
+ out[q] = cells;
1407
+ }
1408
+ return out;
1409
+ };
1282
1410
  // --- Houdini on the runs' neighbors ----------------------------------------------------------------------------------
1283
1411
  let alive = forms.slice().sort((p, q) => p.size - q.size).slice(0, maxCandidates);
1284
1412
  const ctis = [];
@@ -1355,6 +1483,11 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1355
1483
  const names = new Set(given.map(l => l.name));
1356
1484
  alive = alive.filter(f => !names.has(textOf(f)));
1357
1485
  let pool = alive.slice(), chosen = [];
1486
+ // (the enumeration's set, proven where the join found nothing: the answer, the search below not run)
1487
+ let enumProof;
1488
+ // (the ∃ law the engine's set proved with, its ghost's: reported in `found` with the cubes, so the verdict's laws prove
1489
+ // again as they are, and export to Lean)
1490
+ let enumSome = [];
1358
1491
  const goalName = (g) => g.replace(/ @[^@]*$/, '');
1359
1492
  let last = first;
1360
1493
  const slow = Math.max(3000, ms / 10);
@@ -1520,8 +1653,23 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1520
1653
  // A view's atoms (each map at each place it is read at there) and rows: each assignment of its keys to keys a state
1521
1654
  // holds (by sort: the keys of the maps read at the key's place, the parts of composed keys there, and a fresh one;
1522
1655
  // per key at most `per`), the frame met, each map's cell at each of its places.
1523
- const addView = (v, mapsAt, valuesOf2, per) => {
1656
+ // The join's rows of a space of keys (the cells, a view): rows alike but for their keys once, up to 6,000. The hull
1657
+ // and the levels read only which rows there are, so the cap holds as many of the samples' kinds of rows as it can.
1658
+ const distinctRows = (rowsOf) => {
1659
+ const rows = [], seen = new Set(), fresh = (r) => { let t = ''; for (const q in r)
1660
+ if (q !== K)
1661
+ t += `${r[q]},`; return !seen.has(t) && !!seen.add(t); };
1662
+ for (const s2 of samples) {
1663
+ if (rows.length > 6000)
1664
+ break;
1665
+ rows.push(...rowsOf(s2.params, s2.st).filter(fresh));
1666
+ }
1667
+ return rows;
1668
+ };
1669
+ const addView = (v, mapsAt, valuesOf2, per, extra = [], product = false) => {
1524
1670
  const vi = views.length, va = [];
1671
+ // (`extra`: values of its keys that are atoms too, a key or a function of one: e ≤ Ep[a], idn(x) < idn(y))
1672
+ extra.forEach((t, j) => { va.push(atoms.length); atoms.push({ name: t.name, parts: [[`$x${vi}:${j}`, 1]], param: false, int: false, cell: false, term: t.term, view: vi }); });
1525
1673
  mapsAt.forEach((mps, place) => {
1526
1674
  for (const i of cellAtoms) {
1527
1675
  const a = atoms[i];
@@ -1531,8 +1679,19 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1531
1679
  atoms.push({ name: `${a.parts[0][0]}[${viewText(v, showE(v.places[place]))}]`, parts: a.parts.map(([q, sg]) => [`${AT}${AT}${q}${AT}${vi}:${place}`, sg]), param: false, int: a.int, cell: false, place, view: vi });
1532
1680
  }
1533
1681
  });
1534
- const rowsOf = (params, st) => {
1535
- const cand = valuesOf2(st).map(vs => (named.has(st) ? vs.slice(0, -1) : vs).slice(0, per)), out = [];
1682
+ const rowsOf = (params, st, full = false) => {
1683
+ // (`per` values a key; the engine's views (`product`) at most per^keys rows a state, 64 at least, the fewer-valued
1684
+ // sorts' keys taking all of theirs and the cut on the most-valued: a sort's values past a few are still read where
1685
+ // another sort has few; a model's state, every row up to 1024, so that its diagram is read at the keys it names)
1686
+ const all2 = valuesOf2(st).map(vs => (named.has(st) ? vs.slice(0, -1) : vs)), lens = all2.map(vs => (product ? vs.length : Math.min(per, vs.length))), most = !product || full ? Infinity : named.has(st) ? 1024 : Math.max(64, per ** all2.length);
1687
+ for (let size = lens.reduce((a, b) => a * b, 1); size > most;) {
1688
+ const i = lens.indexOf(Math.max(...lens));
1689
+ if (lens[i] <= 1)
1690
+ break;
1691
+ size = size / lens[i] * (lens[i] - 1);
1692
+ lens[i]--;
1693
+ }
1694
+ const cand = all2.map((vs, i) => vs.slice(0, lens[i])), out = [];
1536
1695
  const go = (i, env) => {
1537
1696
  if (i === v.vars.length) {
1538
1697
  try {
@@ -1542,7 +1701,12 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1542
1701
  catch {
1543
1702
  return;
1544
1703
  }
1545
- const row = { ...params, ...st.scalars, [K]: env[v.vars[0]] }, cells = [];
1704
+ const row = { ...params, ...st.scalars, [K]: env[v.vars[0]], ...Object.fromEntries(extra.map((t, j) => { try {
1705
+ return [`$x${vi}:${j}`, evalE(t.term, env, st, m)];
1706
+ }
1707
+ catch {
1708
+ return [`$x${vi}:${j}`, 0];
1709
+ } })) }, cells = [];
1546
1710
  mapsAt.forEach((mps, place) => { const key = evalE(v.places[place], env, st, m); for (const mp of mps) {
1547
1711
  const q = `${AT}${AT}${mp}${AT}${vi}:${place}`;
1548
1712
  row[q] = cellOf(st, mp, key);
@@ -1557,13 +1721,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1557
1721
  go(0, { ...params, ...st.scalars });
1558
1722
  return out;
1559
1723
  };
1560
- const rows = [];
1561
- for (const s2 of samples) {
1562
- if (rows.length > 6000)
1563
- break;
1564
- rows.push(...rowsOf(s2.params, s2.st));
1565
- }
1566
- views.push({ ...v, atoms: va, rows, rowsOf });
1724
+ views.push({ ...v, atoms: va, rows: distinctRows(rowsOf), rowsOf });
1567
1725
  };
1568
1726
  // The pairs: where the rule composes two keys into one (Link[N·a + b] beside Known[a], Known[b]), the cells at two
1569
1727
  // keys x and y and at N·x + y, a row per two keys a state holds (or the parts of a composed key it holds, or a fresh
@@ -1600,11 +1758,28 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1600
1758
  const seen = new Set();
1601
1759
  for (const l of callerLaws) {
1602
1760
  const bound = l.forall ? [l.forall, ...(l.keys ?? [])] : [];
1603
- if (bound.length < 2 || bound.length > 4)
1761
+ if (!bound.length || bound.length > 4)
1604
1762
  continue;
1605
1763
  const shape = sorts.shape(l, bound);
1606
- // (two keys the pairs already relate: a row and a column of the composed key, or two plain keys)
1607
- if (!shape || (bound.length === 2 && pairing && (!pairing.n || (shape.composites.length === 1 && sorts.sortOf(l, bound[0]) !== sorts.sortOf(l, bound[1])))))
1764
+ if (!shape)
1765
+ continue;
1766
+ const reads = (g) => bound.filter(b2 => JSON.stringify(g).includes(`"name":"${b2}"`)), moving = shape.guards.some((g) => sorts.moving(g, bound));
1767
+ // A key's domain that moves (its guards that read no other key but the state or params: k < size, j < next): a
1768
+ // view of that key alone, the cells of its sort at it where the domain holds (the cells' space reads every key a
1769
+ // state holds, a map written at every key holding its value past the domain too).
1770
+ for (const b2 of bound) {
1771
+ const dom = shape.guards.filter((g) => reads(g).length === 1 && reads(g)[0] === b2 && sorts.moving(g, bound)), mps = sorts.plainMaps(sorts.sortOf(l, b2));
1772
+ if (!dom.length || !mps.length)
1773
+ continue;
1774
+ const frame = all(...dom.map((g) => substC(g, { vars: { [b2]: x(KEY) }, maps: {}, flags: {} }))), sig = JSON.stringify([sorts.sortOf(l, b2), frame]);
1775
+ if (seen.has(sig))
1776
+ continue;
1777
+ seen.add(sig);
1778
+ addView({ vars: [KEY], names: ['x'], places: [x(KEY)], covers: [[0]], frame, need: 1, printable: true }, [mps], st => [sorts.valuesAt(st, sorts.sortOf(l, b2))], 64);
1779
+ }
1780
+ // (two keys the pairs already relate: a row and a column of the composed key, or two plain keys where no domain
1781
+ // of the law's moves)
1782
+ if (bound.length < 2 || (bound.length === 2 && pairing && ((!pairing.n && !moving) || (shape.composites.length === 1 && sorts.sortOf(l, bound[0]) !== sorts.sortOf(l, bound[1])))))
1608
1783
  continue;
1609
1784
  const vars = bound.map((_, i) => (i ? `key${i + 1}$found` : KEY)), ren = Object.fromEntries(bound.map((b2, i) => [b2, x(vars[i])]));
1610
1785
  const places = [], mapsAt = [], covers = [];
@@ -1618,14 +1793,16 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1618
1793
  mapsAt.push(mps);
1619
1794
  covers.push([i]);
1620
1795
  } });
1621
- const sig = JSON.stringify([bound.map(b2 => sorts.sortOf(l, b2)), covers, mapsAt]);
1796
+ const distinct = bound.flatMap((b2, i) => bound.slice(i + 1).flatMap((c2, j) => (sorts.sortOf(l, b2) === sorts.sortOf(l, c2) ? [not(same(x(vars[i]), x(vars[i + 1 + j])))] : [])));
1797
+ const frame = all(...shape.guards.map((g) => substC(g, { vars: ren, maps: {}, flags: {} })), ...distinct);
1798
+ const sig = JSON.stringify([bound.map(b2 => sorts.sortOf(l, b2)), covers, mapsAt, frame]);
1622
1799
  if (seen.has(sig) || !places.length)
1623
1800
  continue;
1624
1801
  seen.add(sig);
1625
- const distinct = bound.flatMap((b2, i) => bound.slice(i + 1).flatMap((c2, j) => (sorts.sortOf(l, b2) === sorts.sortOf(l, c2) ? [not(same(x(vars[i]), x(vars[i + 1 + j])))] : [])));
1626
- const frame = all(...shape.guards.map((g) => substC(g, { vars: ren, maps: {}, flags: {} })), ...distinct);
1627
1802
  const per = Math.max(2, Math.floor(64 ** (1 / bound.length)));
1628
- addView({ vars, names: ['x', 'y', 'z', 'w'].slice(0, bound.length), places, covers, frame, need: bound.length, printable: false }, mapsAt, st => bound.map(b2 => sorts.valuesAt(st, sorts.sortOf(l, b2))), per);
1803
+ // (printed where its places are its two keys, x and y)
1804
+ const printable = bound.length === 2 && places.length === 2 && places.every((p2, i) => p2.op === 'var' && p2.name === vars[i]);
1805
+ addView({ vars, names: ['x', 'y', 'z', 'w'].slice(0, bound.length), places, covers, frame, need: bound.length, printable }, mapsAt, st => bound.map(b2 => sorts.valuesAt(st, sorts.sortOf(l, b2))), per);
1629
1806
  }
1630
1807
  }
1631
1808
  // The directions over some values: each value up and down, pairs of them where there are few, the rule's own
@@ -1724,7 +1901,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1724
1901
  const vecs = (p) => (cells ? p.cells.map(valuesOf) : view ? (p.views[kind] ?? []).map(valuesOf) : [valuesOf(p.scalar)]);
1725
1902
  const add = (p, widen) => { for (const v of vecs(p))
1726
1903
  join(keyOf(v), v, widen); };
1727
- const rows = (cells ? rowsK : view ? view.rows : rowsS).map(valuesOf);
1904
+ const rows = (cells ? distinctRows(cellRows) : view ? view.rows : rowsS).map(valuesOf);
1728
1905
  for (const v of rows)
1729
1906
  join(keyOf(v), v, false);
1730
1907
  opts.progress?.('join start', { space: kind, control: ctl.map(c => `${nameOf(c.atom)}:${c.cuts.join('/')}`).join(' '), groups: groups.size, dirs: dirs.length, coords: CN });
@@ -1978,6 +2155,9 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1978
2155
  };
1979
2156
  // (a step law's goal: its step from a state the set allows)
1980
2157
  const stepLawOf = new Map(stepLaws.map(sl => [sl.name, sl]));
2158
+ // (the engine runs after a join that finds nothing, on a rule whose scalars the runs held at few values: below)
2159
+ let follows;
2160
+ const engineFollows = () => (follows ??= !!sorts && callerLaws.some(l => l.keys?.length) && atoms.every((a, i) => a.cell || a.param || !!a.term || a.view !== undefined || i >= valsS.length || new Set(valsS[i]).size <= 4));
1981
2161
  const stepWith = (name, form, ctx) => {
1982
2162
  const ctxLaws = [...ctx, ...(form ? [form] : [])].map(lawFor), ls = [...given, ...ctxLaws], mm = forLaws(ctxLaws).m, sl = form ? undefined : stepLawOf.get(name);
1983
2163
  const idx = form ? ls.length - 1 : ls.findIndex(l => l.name === name);
@@ -2002,7 +2182,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2002
2182
  if (!('tree' in quick) && quick.stuck === 'sat' && quick.witness)
2003
2183
  return { stuck: 'sat', witness: quick.witness, g: g };
2004
2184
  }
2005
- const out = budgeted(joinQueryMs, until2 => grow(g, new Map(), { nodes: 0, until: until2 }));
2185
+ // (where the engine follows, the usual search on the wall too, joinGrowWall: the proving joins' searches take under a
2186
+ // second (decentralized lock's sums pass, 0.7–0.8 s), and an unknown one ran 13 s (wo's every k: Leader[k] <=
2187
+ // VoteRequestMsg[k]), the engine's time)
2188
+ const out = withWall(engineFollows() ? performance.now() + joinGrowWall : Infinity, () => budgeted(joinQueryMs, until2 => grow(g, new Map(), { nodes: 0, until: until2 })));
2006
2189
  if (!('tree' in out))
2007
2190
  return { stuck: out.stuck, witness: out.stuck === 'sat' ? out.witness : undefined, g: g };
2008
2191
  for (const h of usedHyps(g, out.tree))
@@ -2135,8 +2318,30 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2135
2318
  return true;
2136
2319
  };
2137
2320
  const formOf = (c, view) => ({ coef: [], d: 0, cells: false, cube: c, size: 1, ...(view !== undefined ? { view } : {}) });
2321
+ // (a view's key read only by order literals bounding it from below (Ep[x] + 1 <= y, y nowhere else): a value past the
2322
+ // small instance's always has that literal, so the cube is a stronger one in disguise, and false where that is: no such
2323
+ // cube. One bounded from above alone is 0 there, the cube a true one (started is 0 and y + 1 <= Ep[x]: Ep is 0 before
2324
+ // init))
2325
+ const oneSided = (c, vi) => {
2326
+ const v = views[vi], side = new Map(), held = new Set();
2327
+ for (const l of c)
2328
+ for (const [a, k] of 'at' in l ? [[l.at.atom, 0]] : l.lin.coef) {
2329
+ const at = atoms[a];
2330
+ if (at.place !== undefined)
2331
+ for (const ki of v.covers[at.place] ?? [])
2332
+ held.add(v.vars[ki]);
2333
+ else if (at.term?.op === 'var' && k) {
2334
+ const s0 = side.get(at.term.name), dir = Math.sign(k);
2335
+ side.set(at.term.name, s0 === undefined || s0 === dir ? dir : 2);
2336
+ }
2337
+ else if (at.term)
2338
+ walk(at.term, o => { if (o.op === 'var')
2339
+ held.add(String(o.name)); });
2340
+ }
2341
+ return [...side].some(([nm, d]) => d === -1 && !held.has(nm));
2342
+ };
2138
2343
  const witnessStep = (w) => {
2139
- const pre = stateAt(w), input = Object.fromEntries(m.inputs.map(i => [i, w[i] ?? 0]));
2344
+ const pre = stateAt(w), input = requestOf(w);
2140
2345
  try {
2141
2346
  return { pre, post: run.step({}, pre, input) };
2142
2347
  }
@@ -2310,6 +2515,574 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2310
2515
  }
2311
2516
  return [];
2312
2517
  };
2518
+ // The template (DistAI's): per sort, as many keys as the most places of that sort one map or a caller's law reads; a
2519
+ // view of each sub-template of one to four keys (each plain map at each key of its sort, each composed map at each
2520
+ // row and column key, a column's keys below N, keys of one sort distinct). Its cubes: each set of at most three
2521
+ // literals (a few-valued cell or scalar at a value, its largest as "at least") no row of the samples or the start is
2522
+ // in, minimal, reading every key, one per renaming of a sort's keys, the fewest literals first.
2523
+ const known = new Map();
2524
+ // (each enumerated view's keys' sorts: minimal implication's renamings)
2525
+ const viewSorts = new Map();
2526
+ // (order literals that can't hold together, p ≤ q + d around a cycle summing below 0: a cube nothing is in)
2527
+ const contradicts = (c) => {
2528
+ const e = c.flatMap(l => ('lin' in l && l.lin.coef.length === 2 && l.lin.coef[0][1] === 1 && l.lin.coef[1][1] === -1 ? [[l.lin.coef[0][0], l.lin.coef[1][0], l.lin.d]] : []));
2529
+ const ns = [...new Set(e.flatMap(([p, q]) => [p, q]))], dist = new Map(ns.map(q => [q, 0]));
2530
+ for (let k = 0; k <= ns.length; k++)
2531
+ for (const [p, q, d] of e)
2532
+ if (dist.get(q) + d < dist.get(p)) {
2533
+ if (k === ns.length)
2534
+ return true;
2535
+ dist.set(p, dist.get(q) + d);
2536
+ }
2537
+ return false;
2538
+ };
2539
+ const smallReq = [];
2540
+ // (each pool cube's near misses: rows of the filter's larger instances where every literal but one holds)
2541
+ const nearMiss = new Map();
2542
+ let smallAll = [];
2543
+ // (a small state run under another table of a function: its params' table, the rule's functions swapped while it is read)
2544
+ const tableOf = new WeakMap();
2545
+ const withTable = (params, f) => {
2546
+ const tb = tableOf.get(params);
2547
+ if (!tb || !m.fns)
2548
+ return f();
2549
+ const saved = Object.entries(tb).map(([k]) => [k, m.fns[k]]);
2550
+ Object.assign(m.fns, tb);
2551
+ try {
2552
+ return f();
2553
+ }
2554
+ finally {
2555
+ for (const [k, fn] of saved)
2556
+ m.fns[k] = fn;
2557
+ }
2558
+ };
2559
+ const enumerated = () => {
2560
+ const ks = sorts, comp = ks.composedMaps.length && pairing?.n ? [ks.find('hi'), ks.find('lo')] : undefined;
2561
+ const multi = [...ks.arity].map(([mp, k]) => ({ mp, slots: Array.from({ length: k }, (_, i) => ks.find(`${mp}:${i}`)) }));
2562
+ const ss = [...new Set([...ks.plainRead.map(mp => ks.find(`M:${mp}`)), ...(comp ?? []), ...multi.flatMap(q => q.slots)])];
2563
+ // (a map's values of a key's sort, and the sorts an order compares: e < Ep[a] makes Ep's values epochs, ordered)
2564
+ const vp = new Map(), vf = (a) => { const q = vp.get(a); return q === undefined || q === a ? a : vf(q); };
2565
+ const node = (e) => (e.op === 'var' ? (m.inputs.includes(e.name) ? ks.find(e.name) : m.params.includes(e.name) ? `P:${e.name}` : undefined) : e.op === 'get' && (mapSet.has(e.map) || m.fns?.[e.map]) ? `V:${e.map}` : undefined);
2566
+ const ord = new Set(), leaves = (e) => (e.op === 'if' ? [...leaves(e.then), ...leaves(e.else)] : [e]);
2567
+ const relate = (a, b, less = false) => { if (a && b) {
2568
+ const ra = vf(a), rb = vf(b);
2569
+ if (ra !== rb)
2570
+ vp.set(ra, rb);
2571
+ if (less)
2572
+ ord.add(vf(b));
2573
+ } };
2574
+ walk([m.step, m.assume], o => { const c = o; if (c.op === '<' || c.op === '<=' || c.op === '=')
2575
+ relate(node(c.a), node(c.b), c.op !== '='); });
2576
+ // (a param that bounds a sort's keys, k < p, is that sort's size in the small instance; a param a key equals, a write
2577
+ // at every key at it (k = first) or a read at it, is an element of that sort, which pins it against renaming)
2578
+ const bounding = new Map(), elementOf = new Map();
2579
+ walk([m.step, m.assume], o => { const c = o; if ((c.op === '<' || c.op === '<=') && c.b.op === 'var' && m.params.includes(c.b.name) && c.a.op === 'var' && m.inputs.includes(c.a.name))
2580
+ bounding.set(c.b.name, new Set([...(bounding.get(c.b.name) ?? []), ks.find(c.a.name)])); });
2581
+ for (const [mp, w] of Object.entries(m.step.maps ?? {})) {
2582
+ const srt = ks.plainRead.includes(mp) ? ks.find(`M:${mp}`) : undefined;
2583
+ if (srt && 'each' in w)
2584
+ walk(w.value, o => { const c = o; if (c.op === '=' && c.a.op === 'var' && c.b.op === 'var') {
2585
+ const q = c.a.name === w.each ? c.b.name : c.b.name === w.each ? c.a.name : undefined;
2586
+ if (q && m.params.includes(q))
2587
+ elementOf.set(q, srt);
2588
+ } });
2589
+ }
2590
+ walk([m.step, m.assume], o => { const e = o; if (e.op === 'get' && e.key.op === 'var' && m.params.includes(e.key.name) && ks.plainRead.includes(e.map))
2591
+ elementOf.set(e.key.name, ks.find(`M:${e.map}`)); });
2592
+ for (const [mp, w] of Object.entries(m.step.maps ?? {}))
2593
+ for (const l of leaves(w.value))
2594
+ relate(`V:${mp}`, node(l));
2595
+ const valueSort = (mp) => ss.find(q => vf(q) === vf(`V:${mp}`)), ordered = (q) => [...ord].some(o => vf(o) === vf(q));
2596
+ // (a function of a key whose values are a composed map's rows: Pending[idn(x)·N + y])
2597
+ const fnHi = Object.keys(m.fns ?? {}).filter(f => comp && ss.includes(ks.find(`F:${f}`)) && vf(`V:${f}`) === vf(comp[0]));
2598
+ const placesOf = (s) => (comp ? comp.filter(c => c === s).length + fnHi.filter(f => ks.find(`F:${f}`) === s).length : 0);
2599
+ const width = ss.map(s => Math.min(3, Math.max(ordered(s) ? 2 : 0, ks.plainMaps(s).length ? 1 : 0, placesOf(s) + (placesOf(s) >= 2 ? 1 : 0), ...multi.map(q => q.slots.filter(c => c === s).length), ...callerLaws.map(l => [l.forall, ...(l.keys ?? [])].filter(b => b && ks.sortOf(l, b) === s).length))));
2600
+ // (a key's own bounds and domain: a caller's law's guards on one key of the sort, k < 64, k < size)
2601
+ const bounds = new Map();
2602
+ for (const l of callerLaws) {
2603
+ const b = [l.forall, ...(l.keys ?? [])].filter((q) => !!q);
2604
+ for (const g of b.length ? ks.shape(l, b).guards : []) {
2605
+ const one = b.filter(q => JSON.stringify(g).includes(`"name":"${q}"`)), s = one.length === 1 ? ks.sortOf(l, one[0]) : undefined;
2606
+ if (s)
2607
+ bounds.set(s, [...(bounds.get(s) ?? []), substC(g, { vars: { [one[0]]: x(KEY) }, maps: {}, flags: {} })]);
2608
+ }
2609
+ }
2610
+ opts.progress?.('join template', { sorts: ss.map((s, i) => `${s}:${width[i]}`).join(' '), multi: multi.map(q => `${q.mp}:${q.slots.join(',')}`).join(' ') });
2611
+ // The small instance (BRAB's, DuoAI's simulation made complete): each key sort its first 2 to 3 elements (its width),
2612
+ // an ordered one 0..3, a function's values over its argument's, params small, each input over its sort's elements
2613
+ // (a carried set over their subsets, any other over the values a few draws give), every reachable state by BFS up
2614
+ // to 20,000 states and a seventh of what is left; its states the views' rows first.
2615
+ // (an instance: the small one (`grow` none, the samples), or `grow` more elements of a sort within `share` ms, its
2616
+ // BFS uncut and its own draws (the pool's data filter))
2617
+ const instance = (grow, share, rnd) => {
2618
+ const base = share === undefined, most = base ? 20_000 : 2_000_000, combosMax = base ? 2048 : 16_384, reqs = [];
2619
+ const size = (q) => Math.max(2, Math.min(3, width[ss.indexOf(q)] ?? 2)) + grow(q), keyDom = (q) => Array.from({ length: ordered(q) ? 4 + grow(q) : size(q) }, (_, i) => i);
2620
+ const fnDom = (q) => Object.keys(m.fns ?? {}).filter(f => vf(`V:${f}`) === vf(q) && ss.includes(ks.find(`F:${f}`))).flatMap(f => keyDom(ks.find(`F:${f}`)).map(k => { try {
2621
+ return fnValue(m.fns[f], k);
2622
+ }
2623
+ catch {
2624
+ return 0;
2625
+ } }));
2626
+ const domOf = (v, drawn) => { const q = ks.find(v); return ss.includes(q) ? (fnDom(q).length ? fnDom(q) : keyDom(q)) : [...drawn].sort((a, b) => a - b); };
2627
+ const pvs = new Map();
2628
+ for (let t = 0; t < 200 && pvs.size < (base ? 4 : 8); t++) {
2629
+ // (a param a sort's keys are compared with, n < size, is that sort's size in the instance)
2630
+ const p = randomParams(2, rnd);
2631
+ for (const q of m.params) {
2632
+ const el = elementOf.get(q), srts = ss.filter(r => vf(r) === vf(`P:${q}`));
2633
+ if (el && ss.includes(el))
2634
+ p[q] = keyDom(el)[rnd(keyDom(el).length)];
2635
+ else if (bounding.has(q) && [...bounding.get(q)].some(r => ss.includes(r)))
2636
+ p[q] = Math.min(...[...bounding.get(q)].filter(r => ss.includes(r)).map(r => keyDom(r).length));
2637
+ else if (srts.length) {
2638
+ const d = keyDom(srts[0]);
2639
+ p[q] = d[rnd(d.length)];
2640
+ }
2641
+ }
2642
+ if ((m.pre && !evalC(m.pre, p, { scalars: {}, maps: {} }, m)) || m.params.some(q => ss.includes(ks.find(q)) && !domOf(q, new Set()).includes(p[q])))
2643
+ continue;
2644
+ pvs.set(JSON.stringify(p), p);
2645
+ }
2646
+ const t3 = performance.now(), seen = new Set(), small = [];
2647
+ let end2 = performance.now() + (share ?? Math.min(4000, (wallUntil - performance.now()) / 7));
2648
+ let cut = false;
2649
+ // (a state's key: its cells off the map's default, in key order, the least under the renamings of each symmetric
2650
+ // sort's elements: a sort the step neither orders, nor computes on (a function's argument, a param's bound), nor
2651
+ // stores in a cell or a scalar; every map's key read as its parts' sorts, else no renaming)
2652
+ const layout = new Map();
2653
+ for (const mp of Object.keys(m.maps ?? {})) {
2654
+ const ar = ks.arity.get(mp);
2655
+ if (ks.plainRead.includes(mp))
2656
+ layout.set(mp, [ks.find(`M:${mp}`)]);
2657
+ else if (ks.composedMaps.includes(mp) && pairing?.n)
2658
+ layout.set(mp, [ks.find('hi'), ks.find('lo')]);
2659
+ else if (ar && pairing?.n)
2660
+ layout.set(mp, Array.from({ length: ar }, (_, i) => ks.find(`${mp}:${i}`)));
2661
+ }
2662
+ const stored = new Set(m.inputs.filter(i => JSON.stringify(m.step.state ?? {}).includes(`"name":"${i}"`)).map(i => ks.find(i)));
2663
+ const pinned = new Set(elementOf.values()), sym = layout.size === Object.keys(m.maps ?? {}).length ? ss.filter(q => !pinned.has(q) && !ordered(q) && !valueSort2(q) && !stored.has(q) && !Object.keys(m.fns ?? {}).some(f => ks.find(`F:${f}`) === q) && !m.params.some(p2 => vf(`P:${p2}`) === vf(q))) : [];
2664
+ function valueSort2(q) { return Object.keys(m.maps ?? {}).some(mp => valueSort(mp) === q); }
2665
+ const perms = (k) => (k <= 1 ? [[0]] : perms(k - 1).flatMap(p2 => Array.from({ length: k }, (_, i) => [...p2.slice(0, i), k - 1, ...p2.slice(i)])));
2666
+ let rens = [new Map()];
2667
+ for (const q of sym) {
2668
+ const next = rens.flatMap(r2 => perms(size(q)).map(pm => new Map([...r2, [q, pm]])));
2669
+ if (next.length > 36)
2670
+ break;
2671
+ rens = next;
2672
+ }
2673
+ const renKey = (mp, k, ren) => {
2674
+ const lay = layout.get(mp);
2675
+ if (!lay || !ren.size)
2676
+ return k;
2677
+ if (lay.length === 1) {
2678
+ const pm = ren.get(lay[0]);
2679
+ return pm && k < pm.length ? pm[k] : k;
2680
+ }
2681
+ if (k < pairing.c)
2682
+ return k;
2683
+ const digits = [];
2684
+ for (let i = 0, r = k - pairing.c; i < lay.length; i++, r = Math.floor(r / pairing.n))
2685
+ digits.unshift(i === lay.length - 1 ? r : r % pairing.n);
2686
+ return pairing.c + digits.reduce((acc, d, i) => { const pm = ren.get(lay[i]); return acc * pairing.n + (pm && d < pm.length ? pm[d] : d); }, 0);
2687
+ };
2688
+ const textAt = (q, ren) => JSON.stringify([q.params, q.st.scalars, Object.entries(q.st.maps).map(([mp, cells]) => { const d = q.st.defaults?.[mp] ?? m.maps?.[mp] ?? 0; return [...cells].filter(([, v]) => v !== d).map(([k, v]) => [renKey(mp, k, ren), v]).sort((a, b) => a[0] - b[0]); }), q.st.defaults ?? null]);
2689
+ // (the state's own text first, its renamings' only for a text not seen)
2690
+ const canon = new Map();
2691
+ const keyOf3 = (q) => {
2692
+ const own = textAt(q, new Map());
2693
+ let best = canon.get(own);
2694
+ if (best === undefined) {
2695
+ best = own;
2696
+ for (const ren of rens) {
2697
+ const t = textAt(q, ren);
2698
+ if (t < best)
2699
+ best = t;
2700
+ }
2701
+ canon.set(own, best);
2702
+ }
2703
+ return best;
2704
+ };
2705
+ // (the step compiled once: core/machine.ts's JavaScript, its assumption refusing a request as `allowed` does)
2706
+ // (a function the kernel knows by its facts alone (no recurrence, no call) on a template sort: its own table and a
2707
+ // few others that keep its facts on the sort's keys (its values reversed, and each turned by one), each run as its
2708
+ // own machine; their states' rows read under their table. One table alone is a fact of it, not of the rule: ring's
2709
+ // ids, every node past another one's below it)
2710
+ const tables = [{ m, run, js: m.history ? undefined : loadJs(m), fns: {} }];
2711
+ for (const [f, fn] of Object.entries(m.fns ?? {})) {
2712
+ const arg = ks.find(`F:${f}`);
2713
+ if (fn.call || fn.recur || (fn.arity ?? 1) !== 1 || !ss.includes(arg) || m.history)
2714
+ continue;
2715
+ const dom = keyDom(arg), vals = dom.map(k => { try {
2716
+ return fnValue(fn, k);
2717
+ }
2718
+ catch {
2719
+ return 0;
2720
+ } }), turn = (vs) => [...vs.slice(1), vs[0]];
2721
+ for (const vs of [[...vals].reverse(), turn(vals), turn([...vals].reverse())]) {
2722
+ const fn2 = { ...fn, js: `(k) => (${JSON.stringify(Object.fromEntries(dom.map((k, i) => [k, vs[i]])))})[k] ?? (${fn.js})(k)` }, m2 = { ...m, fns: { ...m.fns, [f]: fn2 } };
2723
+ const keeps = (m.facts ?? []).every(fc => { const b = [fc.forall, ...(fc.keys ?? [])].filter((q) => !!q); return b.reduce(acc => acc.flatMap(t2 => dom.map(k => [...t2, k])), [[]]).every(t => { try {
2724
+ return evalC(fc.holds, Object.fromEntries(b.map((q, k) => [q, t[k]])), { scalars: {}, maps: {} }, m2);
2725
+ }
2726
+ catch {
2727
+ return false;
2728
+ } }); });
2729
+ if (keeps && tables.length < 4)
2730
+ tables.push({ m: m2, run: interpret(m2), js: loadJs(m2), fns: { [f]: fn2 } });
2731
+ }
2732
+ }
2733
+ const stepIn = (tb, params, st, input) => {
2734
+ try {
2735
+ if (tb.js)
2736
+ return tb.js.step(params, tb.js.fork(st), input);
2737
+ return allowed(tb.m, tb.run, params, st, input) ? tb.run.step(params, st, input) : undefined;
2738
+ }
2739
+ catch {
2740
+ return undefined;
2741
+ }
2742
+ };
2743
+ const stepOf = (params, st, input) => stepIn(tables[0], params, st, input);
2744
+ const others = [];
2745
+ for (const params of pvs.values()) {
2746
+ const drawn = new Map(m.inputs.map(i => [i, new Set()]));
2747
+ for (let t = 0; t < 200; t++) {
2748
+ const inp = randomInput(params, 2, rnd);
2749
+ for (const i of m.inputs)
2750
+ if (typeof inp[i] === 'number')
2751
+ drawn.get(i).add(inp[i]);
2752
+ }
2753
+ // (an input no template sort holds, bounded by a param (n1 < size): every value below it)
2754
+ const boundBy = (i) => [...bounding].find(([, v2]) => v2.has(ks.find(i)))?.[0];
2755
+ const doms = m.inputs.map(i => [i, !ss.includes(ks.find(i)) && boundBy(i) !== undefined && (params[boundBy(i)] ?? 0) <= 8 ? Array.from({ length: params[boundBy(i)] ?? 0 }, (_, k) => k) : domOf(i, drawn.get(i))]);
2756
+ for (const q of m.inputMaps ?? []) {
2757
+ const ks2 = keyDom(ks.find(`M:${q}`));
2758
+ doms.push([q, Array.from({ length: 2 ** ks2.length }, (_, b) => new Map(ks2.filter((_, j) => b >> j & 1).map(k => [k, 1])))]);
2759
+ }
2760
+ let combos = [{}];
2761
+ for (const [i, d] of doms)
2762
+ combos = combos.flatMap(c => d.map(v2 => ({ ...c, [i]: v2 })));
2763
+ if (combos.length > combosMax)
2764
+ combos = Array.from({ length: combosMax }, () => combos[rnd(combos.length)]);
2765
+ reqs.push({ params, combos });
2766
+ if (base)
2767
+ smallReq.push({ params, combos });
2768
+ if (base)
2769
+ opts.progress?.('join small domains', { params: JSON.stringify(params), doms: doms.map(([i, d]) => `${i}:${d.length > 8 ? d.length : d.map(v2 => (typeof v2 === 'number' ? v2 : 'map')).join('/')}`).join(' '), combos: combos.length });
2770
+ let st0;
2771
+ try {
2772
+ st0 = run.init(params);
2773
+ }
2774
+ catch {
2775
+ continue;
2776
+ }
2777
+ const tB = performance.now(), queue = [{ params, st: st0 }], qi = { at: 0 }, bfsEnd = performance.now() + (end2 - performance.now()) * 0.75 / (pvs.size - reqs.length + 1);
2778
+ seen.add(keyOf3(queue[0]));
2779
+ small.push(queue[0]);
2780
+ // (a BFS that won't finish (a quarter of its share gone, 1 s at least, and its queue still a quarter of what it
2781
+ // found): cut there, the walks half a second after; an instance it does finish is what it was)
2782
+ const cutAt = base ? tB + Math.max(1000, (bfsEnd - tB) / 4) : Infinity;
2783
+ while (qi.at < queue.length && small.length < most && performance.now() < bfsEnd) {
2784
+ if (performance.now() > cutAt && (queue.length - qi.at) * 4 >= small.length) {
2785
+ end2 = Math.min(end2, performance.now() + 500);
2786
+ break;
2787
+ }
2788
+ const q0 = queue[qi.at++];
2789
+ for (const input of combos) {
2790
+ used.tries++;
2791
+ const next = stepOf(params, q0.st, input);
2792
+ if (!next)
2793
+ continue;
2794
+ const q1 = { params, st: next }, k1 = keyOf3(q1);
2795
+ if (!seen.has(k1)) {
2796
+ seen.add(k1);
2797
+ small.push(q1);
2798
+ queue.push(q1);
2799
+ }
2800
+ }
2801
+ }
2802
+ if (qi.at < queue.length)
2803
+ cut = true;
2804
+ queue.length = 0;
2805
+ // (the other tables: a BFS each from the same start, within the same share)
2806
+ for (const tb of tables.slice(1)) {
2807
+ let s0;
2808
+ try {
2809
+ s0 = tb.run.init(params);
2810
+ }
2811
+ catch {
2812
+ continue;
2813
+ }
2814
+ const p2 = { ...params }, q2 = [{ params: p2, st: s0 }], q2i = { at: 0 }, seen2 = new Set([keyOf3(q2[0])]), end3 = Math.min(end2, performance.now() + (bfsEnd - tB));
2815
+ tableOf.set(p2, tb.fns);
2816
+ others.push(q2[0]);
2817
+ while (q2i.at < q2.length && others.length < most && performance.now() < end3) {
2818
+ const q0 = q2[q2i.at++];
2819
+ for (const input of combos) {
2820
+ const next = stepIn(tb, p2, q0.st, input);
2821
+ if (!next)
2822
+ continue;
2823
+ const q1 = { params: p2, st: next }, k1 = keyOf3(q1);
2824
+ if (!seen2.has(k1)) {
2825
+ seen2.add(k1);
2826
+ others.push(q1);
2827
+ q2.push(q1);
2828
+ }
2829
+ }
2830
+ }
2831
+ }
2832
+ }
2833
+ // (then random walks from its last states, deeper than the BFS's levels reach: each step the first of a few
2834
+ // requests that changes the state, to the end of its share)
2835
+ const bfs = small.length;
2836
+ for (let t = 0; cut && reqs.length && small.length < most && performance.now() < end2; t++) {
2837
+ const from = small[Math.max(0, small.length - 1 - rnd(Math.min(small.length, 64)))], req = reqs.find(q => q.params === from.params);
2838
+ if (!req)
2839
+ break;
2840
+ let at = from.st;
2841
+ for (let d = 0; d < 40 && performance.now() < end2; d++) {
2842
+ let next;
2843
+ for (let k = 0; k < 16 && !next; k++) {
2844
+ const input = req.combos[rnd(req.combos.length)];
2845
+ used.tries++;
2846
+ const s2 = stepOf(from.params, at, input);
2847
+ if (s2 && keyOf3({ params: from.params, st: s2 }) !== keyOf3({ params: from.params, st: at }))
2848
+ next = s2;
2849
+ }
2850
+ if (!next)
2851
+ break;
2852
+ at = next;
2853
+ const q1 = { params: from.params, st: at }, k1 = keyOf3(q1);
2854
+ if (!seen.has(k1)) {
2855
+ seen.add(k1);
2856
+ small.push(q1);
2857
+ }
2858
+ }
2859
+ }
2860
+ if (base)
2861
+ opts.progress?.('join small instance', { states: small.length, bfs, params: pvs.size, symmetric: sym.slice(0, rens.length > 1 ? sym.length : 0).join(), ms: Math.round(performance.now() - t0), took: Math.round(performance.now() - t3) });
2862
+ return { small, others, bfs, cut, params: pvs.size, ms: Math.round(performance.now() - t3) };
2863
+ };
2864
+ let baseMs = 0;
2865
+ {
2866
+ const r0 = instance(() => 0, undefined, rand);
2867
+ baseMs = r0.ms;
2868
+ samples.unshift(...r0.small);
2869
+ smallAll = [...r0.small, ...r0.others];
2870
+ }
2871
+ const out = [];
2872
+ for (const counts of width.reduce((acc, w) => acc.flatMap(c => Array.from({ length: w + 1 }, (_, k) => [...c, k])), [[]])) {
2873
+ const keys = ss.flatMap((s, i) => Array.from({ length: counts[i] }, () => s)), vars = keys.map((_, i) => `key${i + 1}$enum`);
2874
+ if (!keys.length || keys.length > 5 || stop())
2875
+ continue;
2876
+ const places = [], mapsAt = [], covers = [];
2877
+ keys.forEach((s, i) => { if (ks.plainMaps(s).length) {
2878
+ places.push(x(vars[i]));
2879
+ mapsAt.push(ks.plainMaps(s));
2880
+ covers.push([i]);
2881
+ } });
2882
+ if (comp)
2883
+ keys.forEach((a, i) => keys.forEach((b, j) => { if (a === comp[0] && b === comp[1]) {
2884
+ places.push(ks.compose(x(vars[i]), x(vars[j])));
2885
+ mapsAt.push(ks.composedMaps);
2886
+ covers.push(i === j ? [i] : [i, j]);
2887
+ } }));
2888
+ for (const q of multi)
2889
+ for (const t of q.slots.reduce((acc, s) => acc.flatMap(p => keys.flatMap((k2, j) => (k2 === s ? [[...p, j]] : []))), [[]])) {
2890
+ places.push(ks.composeAll(t.map(j => x(vars[j]))));
2891
+ mapsAt.push([q.mp]);
2892
+ covers.push([...new Set(t)]);
2893
+ }
2894
+ for (const f of fnHi)
2895
+ keys.forEach((a, i) => keys.forEach((b, j) => { if (a === ks.find(`F:${f}`) && b === comp[1]) {
2896
+ places.push(ks.compose(get(f, x(vars[i])), x(vars[j])));
2897
+ mapsAt.push(ks.composedMaps);
2898
+ covers.push(i === j ? [i] : [i, j]);
2899
+ } }));
2900
+ const names = ['x', 'y', 'z', 'w', 'u'].slice(0, keys.length), fns = Object.keys(m.fns ?? {}).filter(f => ordered(`V:${f}`) && ss.includes(ks.find(`F:${f}`)));
2901
+ const extra = [...keys.flatMap((q, i) => (ordered(q) ? [{ name: names[i], term: x(vars[i]) }] : [])), ...fns.flatMap(f => keys.flatMap((q, i) => (q === ks.find(`F:${f}`) ? [{ name: `${f}(${names[i]})`, term: get(f, x(vars[i])) }] : [])))];
2902
+ const frame = all(...keys.flatMap((s, i) => [...(comp && s === comp[1] && !bounds.has(s) ? [atMost(x(vars[i]), n(pairing.n - 1))] : []), ...[...new Set((bounds.get(s) ?? []).map(g => JSON.stringify(substC(g, { vars: { [KEY]: x(vars[i]) }, maps: {}, flags: {} }))))].map(t => JSON.parse(t)), ...keys.slice(0, i).flatMap((t, j) => (t === s ? [not(same(x(vars[j]), x(vars[i])))] : []))]));
2903
+ const vi = views.length;
2904
+ addView({ vars, names, places, covers, frame, need: keys.length, printable: false }, mapsAt, st => keys.map(s => ks.valuesAt(st, s)), Math.max(2, Math.floor(64 ** (1 / keys.length))), extra, true);
2905
+ // (the rows: every small state's, distinct, at most 20,000; the view's own rows stop at its first states, the shallow
2906
+ // ones, so a deep state's (a leader's) would be left out)
2907
+ viewSorts.set(vi, keys);
2908
+ const v = views[vi], R = [], seenRows = new Set();
2909
+ for (const q of smallAll.length ? smallAll : []) {
2910
+ if (R.length >= 20_000)
2911
+ break;
2912
+ for (const row of withTable(q.params, () => v.rowsOf(q.params, q.st))) {
2913
+ const r = valuesOf(row), k2 = vecKey(r);
2914
+ if (!seenRows.has(k2)) {
2915
+ seenRows.add(k2);
2916
+ R.push(r);
2917
+ }
2918
+ }
2919
+ }
2920
+ if (!R.length)
2921
+ R.push(...v.rows.slice(0, 3000).map(valuesOf));
2922
+ try {
2923
+ if (!m.params.length)
2924
+ R.push(...v.rowsOf({}, run.init({})).map(valuesOf));
2925
+ }
2926
+ catch { /* (the samples hold the start) */ }
2927
+ // (each literal with the rows it is true at, as bits; `id` its atoms, `name` its text under a renaming of the keys)
2928
+ const W = Math.ceil(R.length / 32), lits = [];
2929
+ const where = (i) => { const pl = atoms[i].place; return pl === undefined ? [] : covers[pl]; };
2930
+ // (an extra atom's key, and its function where it is one)
2931
+ const keyOf2 = (i) => { const t = atoms[i].term; return t?.op === 'var' ? v.vars.indexOf(t.name) : t?.op === 'get' && t.key.op === 'var' ? v.vars.indexOf(t.key.name) : -1; };
2932
+ const fnOf = (i) => { const t = atoms[i].term; return t?.op === 'get' ? t.map : undefined; };
2933
+ const term = (i, ren) => (atoms[i].place !== undefined ? `${atoms[i].parts[0][0].split(AT)[2]}[${where(i).map(k => ren[k]).join()}]` : keyOf2(i) >= 0 ? `${fnOf(i) ?? ''}#${ren[keyOf2(i)]}` : `s${i}`);
2934
+ const reads = (i) => (keyOf2(i) >= 0 ? [keyOf2(i)] : where(i));
2935
+ const add = (lit, id, name, rd, holds, before) => {
2936
+ const bits = new Uint32Array(W);
2937
+ R.forEach((r, k) => { if (holds(r))
2938
+ bits[k >> 5] |= 1 << (k & 31); });
2939
+ lits.push({ lit, id, name, reads: rd, bits, ...(before ? { before } : {}), state: ('at' in lit ? [lit.at.atom] : lit.lin.coef.map(([a]) => a)).some(a => atoms[a].place !== undefined || (!atoms[a].term && !atoms[a].param)) });
2940
+ };
2941
+ const valued = (i) => atoms[i].place !== undefined && !!valueSort(atoms[i].parts[0][0].split(AT)[2]);
2942
+ for (const i of [...v.atoms.filter(j => !atoms[j].int && !atoms[j].term), ...modes.filter(mo => !atoms[mo.atom].cell && !atoms[mo.atom].param).map(mo => mo.atom)]) {
2943
+ const vals = [...new Set(R.map(r => r[i]))].sort((a, b) => a - b);
2944
+ // (a value of a key's sort: 0 alone, an order literal below)
2945
+ for (const value of valued(i) ? vals.filter(q => q === 0) : vals.length <= 3 ? vals : []) {
2946
+ const top = value > 0 && value === vals.at(-1);
2947
+ add(top ? { lin: { coef: [[i, -1]], d: -value } } : { at: { atom: i, value } }, `${i}`, ren => `${term(i, ren)}=${value}`, reads(i), r => (top ? r[i] >= value : r[i] === value));
2948
+ }
2949
+ }
2950
+ // (an ordered sort's keys and values compared: t ≤ u and u < t, of a key and a value or two values)
2951
+ const ts = v.atoms.filter(i => keyOf2(i) >= 0 || valued(i));
2952
+ const sortOf2 = (i) => vf(fnOf(i) ? `V:${fnOf(i)}` : keyOf2(i) >= 0 ? keys[keyOf2(i)] : valueSort(atoms[i].parts[0][0].split(AT)[2]));
2953
+ for (const [a2, i] of ts.entries())
2954
+ for (const j of ts.slice(a2 + 1)) {
2955
+ if (sortOf2(i) !== sortOf2(j))
2956
+ continue;
2957
+ // (two keys of one sort are distinct: one before the other)
2958
+ const keysOnly = !fnOf(i) && !fnOf(j) && atoms[i].place === undefined && atoms[j].place === undefined;
2959
+ for (const [p, q] of [[i, j], [j, i]])
2960
+ for (const d of keysOnly ? [-1] : [0, -1])
2961
+ add({ lin: { coef: [[p, 1], [q, -1]], d } }, `${i}~${j}`, ren => `${term(p, ren)}<=${d}+${term(q, ren)}`, [...reads(p), ...reads(q)], r => r[p] - r[q] <= d, keysOnly ? [keyOf2(p), keyOf2(q)] : undefined);
2962
+ }
2963
+ used.rows += R.length * lits.length;
2964
+ opts.progress?.('join view', { keys: keys.join(), places: places.length, lits: lits.length, rows: R.length, names: lits.map(l => l.name(keys.map((_, i) => i))).join(' ').slice(0, 900) });
2965
+ if (lits.length > 96)
2966
+ continue;
2967
+ const empty = (b) => b.every(w => w === 0), and = (a, b) => a.map((w, k) => w & b[k]);
2968
+ const none = (ls) => empty(ls.slice(1).reduce((b, l) => and(b, lits[l].bits), lits[ls[0]].bits));
2969
+ // (a renaming of a sort's keys moves each literal to the place its keys go to)
2970
+ const perms = keys.reduce((acc, s) => acc.flatMap(p => keys.flatMap((t, j) => (t === s && !p.includes(j) ? [[...p, j]] : []))), [[]]);
2971
+ const canon = (ls) => perms.map(ren => ls.map(l => lits[l].name(ren)).sort().join('&')).sort()[0];
2972
+ const seen = new Set(), found = [];
2973
+ const dfs = (from, chosen, size, bits, most = 400) => {
2974
+ for (let j = from; j < lits.length && found.length < most; j++) {
2975
+ if (chosen.some(c => lits[c].id === lits[j].id))
2976
+ continue;
2977
+ const now2 = [...chosen, j], b = bits ? and(bits, lits[j].bits) : lits[j].bits;
2978
+ if (now2.length < size) {
2979
+ if (!empty(b))
2980
+ dfs(j + 1, now2, size, b, most);
2981
+ continue;
2982
+ }
2983
+ if (!empty(b) || now2.some((_, k) => now2.length > 1 && none(now2.filter((__, q) => q !== k))))
2984
+ continue;
2985
+ // (a cube reading no state (keys and functions alone) is a fact of the functions' tables, or false: none)
2986
+ if (contradicts(now2.map(l => lits[l].lit)) || !now2.some(l => lits[l].state) || oneSided(now2.map(l => lits[l].lit), vi))
2987
+ continue;
2988
+ const read = new Set(now2.flatMap(l => lits[l].reads)), k2 = canon(now2);
2989
+ if (read.size === keys.length && !seen.has(k2)) {
2990
+ seen.add(k2);
2991
+ found.push(now2);
2992
+ }
2993
+ }
2994
+ };
2995
+ // (four literals where a view's literals are few: a ring's order of three keys with what holds there)
2996
+ for (let size = 1; size <= (lits.length <= 40 ? 4 : 3); size++)
2997
+ dfs(0, [], size);
2998
+ // (where they are more: the four-literal cubes with a chain of three keys of one sort, a < b < c (betweenness, and a
2999
+ // cycle's turns of it), the two order literals and any two others, 200 at most; and the doubled patterns below)
3000
+ if (lits.length > 40) {
3001
+ const at = found.length;
3002
+ lits.forEach((a, i) => lits.forEach((b, j) => { if (a.before && b.before && a.before[1] === b.before[0] && a.before[0] !== b.before[1] && found.length < at + 200) {
3003
+ const ab = and(a.bits, b.bits);
3004
+ if (!empty(ab))
3005
+ dfs(0, [i, j], 4, ab, at + 200);
3006
+ } }));
3007
+ // (and "two of a pattern are one", DuoAI's: a two-literal pattern some row has, beside its image under a renaming of
3008
+ // the view's keys within their sorts (Transfer[z, x] and Ep[x] < z, twice: two live transfers), 200 at most)
3009
+ const byName = new Map(lits.map((l, i) => [l.name(keys.map((_, k) => k)), i])), at2 = found.length;
3010
+ for (const ren of perms.filter(r => r.some((k, i) => k !== i)))
3011
+ for (let i = 0; i < lits.length && found.length < at2 + 200; i++)
3012
+ for (let j = i + 1; j < lits.length && found.length < at2 + 200; j++) {
3013
+ const i2 = byName.get(lits[i].name(ren)), j2 = byName.get(lits[j].name(ren));
3014
+ if (i2 === undefined || j2 === undefined || new Set([i, j, i2, j2]).size < 4 || lits[i].id === lits[j].id || empty(and(lits[i].bits, lits[j].bits)))
3015
+ continue;
3016
+ const ls2 = [i, j, i2, j2], b2 = ls2.slice(1).reduce((b, l) => and(b, lits[l].bits), lits[i].bits);
3017
+ if (!empty(b2) || ls2.some((_, k) => none(ls2.filter((__, q) => q !== k))) || contradicts(ls2.map(l => lits[l].lit)) || oneSided(ls2.map(l => lits[l].lit), vi))
3018
+ continue;
3019
+ const read = new Set(ls2.flatMap(l => lits[l].reads)), k2 = canon(ls2);
3020
+ if (read.size === keys.length && !seen.has(k2)) {
3021
+ seen.add(k2);
3022
+ found.push(ls2);
3023
+ }
3024
+ }
3025
+ }
3026
+ known.set(vi, { R, lits: lits.map(l => l.lit) });
3027
+ out.push(...found.map(ls => formOf(ls.map(l => lits[l].lit), vi)));
3028
+ }
3029
+ const made0 = out.filter((f, i) => !set.some(g => textOf(g) === textOf(f)) && out.findIndex(g => textOf(g) === textOf(f)) === i);
3030
+ return env.GDP_POOL !== '0' ? dataFilter(made0) : made0;
3031
+ // The pool's data filter (DuoAI's junk killed by data before any solver call; research/protocols/engine/DESIGN.md,
3032
+ // gen/pool): each cube asked at every reachable state of larger instances, one more element of every sort and then
3033
+ // of each sort alone, within a budget of its own (3 s, at most a tenth of what is left: half an instance's share its
3034
+ // BFS, uncut, the rest reading its states); a cube some row of such a state is in is no law, and goes
3035
+ function dataFilter(pool) {
3036
+ // (its budget scales with the small instance's own search: six times it, 3 s at least, 10 s and a sixth of what is
3037
+ // left at most; ring's one more node needs about 8 s)
3038
+ const t5 = performance.now(), until5 = t5 + Math.min(Number(env.GDP_POOL_MS ?? 10_000), (wallUntil - t5) / 6, Math.max(3000, 6 * baseMs));
3039
+ const litAt = (l, r) => ('at' in l ? valueOf(atoms[l.at.atom], r) === l.at.value : l.lin.coef.reduce((s2, [i, c]) => s2 + c * valueOf(atoms[i], r), 0) <= l.lin.d);
3040
+ const plans = [() => 1, ...(ss.length > 1 ? ss.map(s2 => (q) => (q === s2 ? 1 : 0)) : [])];
3041
+ let live = pool, states = 0;
3042
+ for (const [k, grow] of plans.entries()) {
3043
+ if (!live.length || performance.now() > until5 - 100)
3044
+ break;
3045
+ const r = instance(grow, (until5 - performance.now()) / (plans.length - k) / 2, seeded(29 + k)), killed = new Set();
3046
+ const byView = new Map();
3047
+ for (const f of live)
3048
+ byView.set(f.view, [...(byView.get(f.view) ?? []), f]);
3049
+ for (const q of [...r.small, ...r.others]) {
3050
+ if (performance.now() > until5)
3051
+ break;
3052
+ states++;
3053
+ for (const [vi, fs] of byView) {
3054
+ const alive = fs.filter(f => !killed.has(f));
3055
+ if (!alive.length)
3056
+ continue;
3057
+ const rows = withTable(q.params, () => views[vi].rowsOf(q.params, q.st, true));
3058
+ for (const f of alive) {
3059
+ let near = 0;
3060
+ for (const row of rows) {
3061
+ let off = 0;
3062
+ for (const l of f.cube)
3063
+ if (!litAt(l, row) && ++off > 1)
3064
+ break;
3065
+ if (off === 0) {
3066
+ killed.add(f);
3067
+ break;
3068
+ }
3069
+ if (off === 1)
3070
+ near++;
3071
+ }
3072
+ if (near)
3073
+ nearMiss.set(f, (nearMiss.get(f) ?? 0) + near);
3074
+ }
3075
+ }
3076
+ }
3077
+ live = live.filter(f => !killed.has(f));
3078
+ // (no instance after one that kills nothing; GDP_POOL_STOP=0 runs them all)
3079
+ if (env.GDP_POOL_STOP !== '0' && k > 0 && !killed.size)
3080
+ break;
3081
+ }
3082
+ opts.progress?.('join pool', { made: pool.length, left: live.length, states, ms: Math.round(performance.now() - t5) });
3083
+ return live;
3084
+ }
3085
+ };
2313
3086
  // The control refined on demand (as CEGAR refines its predicates, here read off the rule): a counterexample to a
2314
3087
  // caller's law that the set allows and nothing rules out lies among the samples of its control state. A level of a
2315
3088
  // value the rule compares with a constant (the first, of the values the laws read first, whose levels keep the control
@@ -2319,6 +3092,944 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2319
3092
  stood.clear();
2320
3093
  reached.length = 0;
2321
3094
  } return ok; };
3095
+ // The engine, after a join that found nothing, on a rule of keyed maps whose scalars take few values (no counters;
3096
+ // research/protocols/engine/DESIGN.md): the template's cubes (DuoAI's ∀ candidates, research/protocols/enum/
3097
+ // DESIGN.md) read off the small instance, those the caller's and the kinds' laws don't imply; then Houdini, the
3098
+ // caller's laws first, every cube assumed: the CDCL search's refutation (its core settles the goal while the laws it
3099
+ // read stay) or model, else the proof path's. A model the interpreter reads as a real step out of the goal drops its
3100
+ // cube; one out of the caller's law from a state no small state is has its diagrams blocked as cubes, the caller asked
3101
+ // again first (IC3's order); the caller's law unproven otherwise ends it. A round with nothing real drops the
3102
+ // unsettled. The set is then proven, its trees kept. Later rounds leave a sums pass its reserve (core/dsl.ts's:
3103
+ // decentralized lock's) while the caller's law fails from the set.
3104
+ const engine = () => {
3105
+ if (sorts && callerLaws.some(l => l.keys?.length) && now() < until && !stop()) {
3106
+ opts.progress?.('join engine', { wall: Math.round(performance.now() - t0) });
3107
+ // (a sums pass's reserve where one follows: 10 s, or a quarter of what is left where less is)
3108
+ const v0 = views.length, reserve = rule?.withMapSums() ? Math.min(10_000, (wallUntil - performance.now()) / 4) : 0;
3109
+ const implied = (f) => {
3110
+ const v = views[f.view], sk = { vars: Object.fromEntries(v.vars.map(k => [k, x(`${k}#`)])), maps: {}, flags: {} }, hyps = [substC(v.frame, sk), not(substC(condOf(f), sk))];
3111
+ for (const l of given) {
3112
+ const b = [l.forall, ...(l.keys ?? [])].filter((q) => !!q);
3113
+ if (v.vars.length ** b.length > 64)
3114
+ return false;
3115
+ for (const t of b.reduce(acc => acc.flatMap(t2 => v.vars.map(k => [...t2, k])), [[]]))
3116
+ hyps.push(substC(l.holds, { vars: Object.fromEntries(b.map((q, k) => [q, sk.vars[t[k]]])), maps: {}, flags: {} }));
3117
+ }
3118
+ return 'tree' in withWall(wallUntil, () => budgeted(joinQueryMs / 8, until2 => grow({ name: 'implied', hyps }, new Map(), { nodes: 0, until: until2 })));
3119
+ };
3120
+ // (the cubes that read a map the caller's laws read first)
3121
+ const callerMaps = new Set(laws.flatMap(l => [...JSON.stringify(l.holds).matchAll(/"map":"([^"]+)"/g)].map(q => q[1])));
3122
+ const near = (f) => (f.cube.some(l => atomsIn(formOf([l])).some(i => callerMaps.has(atoms[i].parts[0][0].split(AT)[2] ?? ''))) ? 0 : 1);
3123
+ // (the rounds over the data-filtered pool cut to its minimal cubes)
3124
+ const minPool = env.GDP_POOL !== '0' ? minimal(enumerated()) : { kept: enumerated(), by: new Map() }, made = minPool.kept;
3125
+ const tEngine = performance.now();
3126
+ let cubes = [];
3127
+ // (in turn by the maps a cube reads, those reading the caller's first: one of each kind before a second of any; in
3128
+ // a kind, the fewer literals first (DuoAI's minimal clauses), then the cube over more distinct keys (the law its
3129
+ // diagonal case is a case of))
3130
+ const mapsOfCube = (f) => [...new Set(f.cube.flatMap(l => atomsIn(formOf([l])).map(i => atoms[i].parts[0][0].split(AT)[2] ?? '')))].sort().join();
3131
+ const byMaps = new Map();
3132
+ const width2 = (f) => views[f.view].vars.length;
3133
+ for (const f of [...made].sort((a, b) => near(a) - near(b) || a.cube.length - b.cube.length || width2(b) - width2(a))) {
3134
+ const k2 = mapsOfCube(f);
3135
+ byMaps.set(k2, [...(byMaps.get(k2) ?? []), f]);
3136
+ }
3137
+ // (each turn the kinds in order of their own first cube: its fewer literals, then whether it reads the caller's maps)
3138
+ const kinds2 = [...byMaps.values()].sort((a, b) => a[0].cube.length - b[0].cube.length || near(a[0]) - near(b[0])), turns = [];
3139
+ for (let i = 0; turns.length < made.length; i++)
3140
+ for (const fs of kinds2)
3141
+ if (fs[i])
3142
+ turns.push(fs[i]);
3143
+ // (every cube of at most two literals first, DuoAI's minimal clauses, the turns' order kept within each part)
3144
+ turns.sort((a, b) => Math.min(a.cube.length, 3) - Math.min(b.cube.length, 3));
3145
+ // (round 0 the minimal cubes, at most 24, or the whole enumeration where it is 16 or fewer; the rest by relevance to
3146
+ // the counterexamples, IC3's order)
3147
+ const whole = made.length <= 16;
3148
+ for (const f of turns) {
3149
+ if (cubes.length >= 24 || stop())
3150
+ break;
3151
+ if ((whole || f.cube.length <= 2) && !names.has(textOf(f)) && !implied(f))
3152
+ cubes.push(f);
3153
+ }
3154
+ opts.progress?.('join enumerated', { views: views.length - v0, cubes: cubes.length, ms: Math.round(performance.now() - t0) });
3155
+ opts.progress?.('join cubes', { cubes: cubes.map(textOf).join(' | ') });
3156
+ opts.progress?.('join made', { cubes: made.map(textOf).join(' | ') });
3157
+ // (a goal's proof within the search's own end, on the cost model's clock: a counted search inside it keeps the end)
3158
+ const within = (endWall, f) => withWall(endWall, () => counted(fullRate, () => withDeadline(clock() + Math.max(0, endWall - performance.now()), f), true));
3159
+ // (a model's values past the rule's constants renamed onto small ones in order, a gap kept up to 64: the step then
3160
+ // runs at every key, and the model's equalities, order, +1 and comparisons with the constants are kept)
3161
+ const top = Math.max(1024, ...[...JSON.stringify([m.step, m.assume ?? null, m.pre ?? null]).matchAll(/"value":(\d+)/g)].map(q => Number(q[1])));
3162
+ const smallOf = (w) => {
3163
+ const big = [...new Set(Object.values(w).filter(v => v > top))].sort((a, b) => a - b);
3164
+ if (!big.length)
3165
+ return w;
3166
+ const to = new Map();
3167
+ big.forEach((v, i) => to.set(v, i ? to.get(big[i - 1]) + Math.min(64, v - big[i - 1]) : top + 1));
3168
+ return Object.fromEntries(Object.entries(w).map(([c, v]) => [c, to.get(v) ?? v]));
3169
+ };
3170
+ const realCti = (w0, f, others) => {
3171
+ const w = smallOf(w0);
3172
+ return withFnsOf(w, () => {
3173
+ const { params, st } = stateOf(w), read = new Set([...others, f].map(g => g?.view));
3174
+ // (a model's cells past the keys the interpreter steps at every key, a million, left out)
3175
+ for (const cells of Object.values(st.maps))
3176
+ for (const k of [...cells.keys()])
3177
+ if (k > 1_000_000)
3178
+ cells.delete(k);
3179
+ const at = (s2) => ({ scalar: withTerms({ ...params, ...s2.scalars }, s2), cells: [], views: views.map((v, i) => (read.has(i) ? v.rowsOf(params, s2) : [])) });
3180
+ let post;
3181
+ if (performance.now() > wallUntil)
3182
+ return false;
3183
+ try {
3184
+ post = run.step(params, st, requestOf(w));
3185
+ stepNamed(st, post);
3186
+ }
3187
+ catch {
3188
+ return false;
3189
+ }
3190
+ if (performance.now() > wallUntil)
3191
+ return false;
3192
+ const before = at(st);
3193
+ if (!others.every(g => holdsAt(g, before)))
3194
+ return false;
3195
+ lastPre = { params, st, w };
3196
+ if (!f)
3197
+ return breaks(params, post, st, requestOf(w));
3198
+ return (at(post).views[f.view] ?? []).some(r => judged(f, r) && !holdsRow(f, r));
3199
+ });
3200
+ };
3201
+ // (a cube false at a start: its start goal's model, judged at the interpreter's own start at the model's params (a
3202
+ // start is reachable, so it is a real counterexample); such a cube is not asked, nor kept)
3203
+ const startBad = new Map();
3204
+ // (the law at the model's keys, at the interpreter's start for the model's params, with the model's function values
3205
+ // where they keep the facts at those keys)
3206
+ const badAtStart = (f, w0) => {
3207
+ const w = smallOf(w0), l = lawFor(f);
3208
+ return withFnsOf(w, () => {
3209
+ const { params } = stateOf(w);
3210
+ try {
3211
+ const st = run.init(params), env2 = { ...params, ...st.scalars };
3212
+ for (const k of [l.forall, ...(l.keys ?? [])])
3213
+ if (k)
3214
+ env2[k] = w[k] ?? w[`${k}#`] ?? 0;
3215
+ const vals = [...new Set([l.forall, ...(l.keys ?? [])].filter((k) => !!k).map(k => env2[k]))];
3216
+ for (const fct of m.facts ?? []) {
3217
+ const b = [fct.forall, ...(fct.keys ?? [])].filter((q) => !!q);
3218
+ if (vals.length ** b.length > 4096)
3219
+ return false;
3220
+ for (const t of b.reduce(acc => acc.flatMap(t2 => vals.map(v => [...t2, v])), [[]]))
3221
+ if (!evalC(fct.holds, { ...env2, ...Object.fromEntries(b.map((q, k) => [q, t[k]])) }, st, m))
3222
+ return false;
3223
+ }
3224
+ return !evalC(l.holds, env2, st, m);
3225
+ }
3226
+ catch {
3227
+ return false;
3228
+ }
3229
+ });
3230
+ };
3231
+ const atStart = (f) => {
3232
+ let b = startBad.get(f);
3233
+ if (b === undefined) {
3234
+ const ls2 = [...given, lawFor(f)], g = obligations(forLaws(ls2).m, ls2, {}, given.length)[0];
3235
+ const q = budgeted(joinQueryMs / 32, until2 => growCdcl(g, new Map(), { nodes: 0, until: until2 }, { model: true, wall: wallUntil }));
3236
+ b = !('tree' in q) && q.stuck === 'sat' && !!q.witness && badAtStart(f, q.witness);
3237
+ startBad.set(f, b);
3238
+ }
3239
+ return b;
3240
+ };
3241
+ // (a counterexample's diagram (UPDR's, IC3PO's): in each template view, a row of its state no reachable small state's
3242
+ // row is, as the literals true there, generalized by taking out each literal while no small state's row is inside;
3243
+ // blocked as a law ¬diagram, at most four a counterexample)
3244
+ let lastPre;
3245
+ const reachedRows = new Map();
3246
+ const diagrams = (pre) => {
3247
+ const out2 = [];
3248
+ for (const [vi, k] of known) {
3249
+ const seenR = reachedRows.get(vi) ?? new Set(k.R.map(vecKey));
3250
+ reachedRows.set(vi, seenR);
3251
+ // (a model names some cells: the literals over those alone)
3252
+ for (const row of views[vi].rowsOf(pre.params, pre.st)) {
3253
+ const r = valuesOf(row);
3254
+ if (!unnamed.get(row) && seenR.has(vecKey(r)))
3255
+ continue;
3256
+ let c = k.lits.filter(l => litHolds(l, r) && judged(formOf([l], vi), row));
3257
+ if (!c.length || k.R.some(y => inCube(c, y)))
3258
+ continue;
3259
+ for (const l of [...c]) {
3260
+ const c2 = c.filter(x2 => x2 !== l);
3261
+ if (c2.length && !k.R.some(y => inCube(c2, y)))
3262
+ c = c2;
3263
+ }
3264
+ if (c.length <= 5 && !k.R.some(y => inCube(c, y)) && !oneSided(c, vi))
3265
+ out2.push(formOf(c, vi));
3266
+ if (out2.length >= 4)
3267
+ return out2;
3268
+ }
3269
+ }
3270
+ return out2;
3271
+ };
3272
+ let ghost, ghosts;
3273
+ const ghosted = new WeakMap();
3274
+ const withGhost = (mm) => {
3275
+ if (!ghost)
3276
+ return mm;
3277
+ let g = ghosted.get(mm);
3278
+ if (!g) {
3279
+ g = { ...mm, state: { ...mm.state, [ghost.name]: ghost.start }, step: { ...mm.step, state: { ...mm.step.state, [ghost.name]: ghost.step } } };
3280
+ ghosted.set(mm, g);
3281
+ }
3282
+ return g;
3283
+ };
3284
+ const ghostsOf = () => {
3285
+ const out3 = [];
3286
+ const states = samples.slice(0, 3000), conds = new Map();
3287
+ for (const w of Object.values(m.step.maps ?? {}))
3288
+ walk(w.value, o => { if (o.op === 'if' && conds.size < 16)
3289
+ conds.set(JSON.stringify(o.c), o.c); });
3290
+ for (const [vi, k] of known) {
3291
+ const v = views[vi];
3292
+ if (v.vars.length !== 1 || stop())
3293
+ continue;
3294
+ const keyed = (l) => atomsIn(formOf([l])).some(i => atoms[i].place !== undefined || !!atoms[i].term);
3295
+ const As = [[], ...k.lits.filter(l => !keyed(l)).map(l => [l])], Bs0 = k.lits.filter(keyed);
3296
+ const off = (l) => !('at' in l) || l.at.value !== 0;
3297
+ const Bs = [...Bs0.map(l => [l]), ...Bs0.flatMap((l, i) => Bs0.slice(i + 1).map(l2 => [l, l2]))].filter(b => !contradicts(b) && b.some(off));
3298
+ const rowsAt = states.map(q => v.rowsOf(q.params, q.st).map(valuesOf));
3299
+ for (const A of As)
3300
+ for (const B of Bs) {
3301
+ if (out3.length >= 6)
3302
+ return out3;
3303
+ let some2 = false, notAll = false, ok = true;
3304
+ for (const rows of rowsAt) {
3305
+ if (!rows.length || !inCube(A, rows[0]))
3306
+ continue;
3307
+ some2 = true;
3308
+ if (!rows.some(r => inCube(B, r))) {
3309
+ ok = false;
3310
+ break;
3311
+ }
3312
+ if (!rows.every(r => inCube(B, r)))
3313
+ notAll = true;
3314
+ }
3315
+ if (!ok || !some2 || !notAll)
3316
+ continue;
3317
+ const y = `some$enum${vi}`, sub = { vars: { [v.vars[0]]: x(y) }, maps: {}, flags: {} };
3318
+ const holds = any(...(A.length ? [condOf(formOf(A, vi))] : []), all(substC(v.frame, sub), substC(not(condOf(formOf(B, vi))), sub)));
3319
+ const name = `${A.length ? textOf(formOf(A, vi)) + ' else ' : ''}some ${textOf(formOf(B, vi))}`;
3320
+ // (the witness: along random runs of the small instance, the first ghost the law holds at)
3321
+ witness: for (const c of [all(), ...conds.values()])
3322
+ for (const i of m.inputs) {
3323
+ const step = { op: 'if', c, then: x(i), else: x(y) };
3324
+ let held2 = 0, bad = false;
3325
+ for (const { params, combos } of smallReq)
3326
+ for (let walk2 = 0; walk2 < 40 && !bad; walk2++) {
3327
+ let st, g = 0;
3328
+ try {
3329
+ st = run.init(params);
3330
+ }
3331
+ catch {
3332
+ break;
3333
+ }
3334
+ for (let d = 0; d < 30 && !bad; d++) {
3335
+ const input = combos[rand(combos.length)];
3336
+ try {
3337
+ if (!allowed(m, run, params, st, input))
3338
+ continue;
3339
+ const env2 = { ...params, ...st.scalars, ...Object.fromEntries(m.inputs.map(i2 => [i2, input[i2]])), [y]: g }, seen2 = carriedView(m, st, input);
3340
+ for (const [fl, c2] of Object.entries(m.step.flags ?? {}))
3341
+ env2[`?${fl}`] = evalC(c2, env2, seen2, m) ? 1 : 0;
3342
+ const next = run.step(params, st, input);
3343
+ g = evalE(step, env2, seen2, m);
3344
+ st = next;
3345
+ if (evalC(holds, { ...params, ...st.scalars, [y]: g }, st, m))
3346
+ held2++;
3347
+ else
3348
+ bad = true;
3349
+ }
3350
+ catch {
3351
+ continue;
3352
+ }
3353
+ }
3354
+ }
3355
+ if (bad || held2 < 50)
3356
+ continue;
3357
+ out3.push({ name: y, start: n(0), step, plain: { name, holds }, some: { name, holds, some: [y], witness: { ghost: { [y]: { start: n(0), step } } } } });
3358
+ break witness;
3359
+ }
3360
+ }
3361
+ }
3362
+ return out3;
3363
+ };
3364
+ // (a goal the CDCL search refuted, by the laws its core read: settled while each is still in the set, Houdini's
3365
+ // cores)
3366
+ // (`stands`: the goals proven since the set last lost a law; a set that only grows keeps their proofs)
3367
+ // (a goal's proof had every cube in the set as it stood: a drop takes back the proofs since the dropped cube came in)
3368
+ const settled = new Map(), kept2 = new Set(), stands = new Set(), provenAt = new Map(), addedAt = new Map();
3369
+ const unstand = (gs) => { const r = Math.min(...[...gs].map(g => addedAt.get(g) ?? 0)); for (const [nm, at] of provenAt)
3370
+ if (at >= r) {
3371
+ stands.delete(nm);
3372
+ provenAt.delete(nm);
3373
+ } };
3374
+ let held = false;
3375
+ const pres = [], subs = [], preAt = new WeakMap();
3376
+ let perGoal = 0, houdinied = false;
3377
+ const engineStart = performance.now();
3378
+ const ptOf = (q) => { let pt = preAt.get(q); if (!pt) {
3379
+ pt = withFnsOf(q.w, () => pointOf(q.params, q.st));
3380
+ preAt.set(q, pt);
3381
+ } return pt; };
3382
+ // (a kernel model's state, its values past the rule's constants renamed small, its cells past a million left out)
3383
+ const preOf = (wit) => { const w2 = smallOf(wit); return withFnsOf(w2, () => { const { params, st } = stateOf(w2); for (const cells of Object.values(st.maps))
3384
+ for (const k of [...cells.keys()])
3385
+ if (k > 1_000_000)
3386
+ cells.delete(k); return { params, st, w: w2 }; }); };
3387
+ // (the cubes dropped, never asked again: false at a start)
3388
+ const dead = new Set();
3389
+ // (IC3's frames: a cube whose relative induction fails without a counterexample from a start is not dropped but
3390
+ // pending: out of the set the others assume, asked again (pushed) with the set and itself once the set has changed
3391
+ // since its last try, back in the set where that proves; twice at most)
3392
+ const pending = new Set(), tried = new Map(), backs = new Map();
3393
+ const versionOf = () => cubes.map(textOf).sort().join('|');
3394
+ // (what blocks a counterexample's state: the enumeration's minimal cubes false there (the antichain is the
3395
+ // generalization), or that may be (cells the model leaves unnamed), four at most (the frames' pushes prune the wrong
3396
+ // ones; distributed's needed blockers ranked 2nd to 4th): the false first, then those false at
3397
+ // the most of the counterexamples' states so far, then the fewest literals; else its diagrams)
3398
+ const seenCtis = [];
3399
+ // (every cube ranked in the top eight at some counterexample: the pool a fixpoint's Houdini runs over)
3400
+ const pool = new Set();
3401
+ const blockers = (pre) => {
3402
+ const pt = ptOf(pre), pts = (seenCtis.push(pre), seenCtis.slice(-16).map(ptOf)), bs = [];
3403
+ const scored = made.filter(g => !dead.has(textOf(g)) && !pending.has(g)).map(g => ({ g, f: !holdsAt(g, pt) ? 2 : mayFail(g, pt) ? 1 : 0 })).filter(q => q.f).map(({ g, f }) => ({ g, k: f * 1024 + pts.filter(p2 => !holdsAt(g, p2)).length }));
3404
+ const ranked = scored.sort((a, b) => b.k - a.k || a.g.cube.length - b.g.cube.length || width2(b.g) - width2(a.g));
3405
+ for (const { g } of ranked.slice(0, 8))
3406
+ pool.add(g);
3407
+ for (const { g } of ranked) {
3408
+ if (bs.length >= 4)
3409
+ break;
3410
+ if (!bs.some(h => textOf(h) === textOf(g)) && !atStart(g))
3411
+ bs.push(g);
3412
+ }
3413
+ return bs.length ? bs : withFnsOf(pre.w, () => diagrams(pre)).filter(g => !dead.has(textOf(g)) && !atStart(g));
3414
+ };
3415
+ // (a cube that may be false at a counterexample: at a row where it reads cells the model doesn't name, every literal
3416
+ // the model does name in its pattern)
3417
+ const mayFail = (g, pt) => g.view !== undefined && (pt.views[g.view] ?? []).some(r => !judged(g, r) && g.cube.every(l => { const h = formOf([l], g.view); return !judged(h, r) || !holdsRow(h, r); }));
3418
+ const relevant = (room, kept) => {
3419
+ if (room <= 0 || !pres.length && !subs.length)
3420
+ return [];
3421
+ const have = new Set([...kept.map(textOf), ...dead, ...[...pending].map(textOf)]), pts = pres.map(ptOf), sts = subs.slice(-32).map(ptOf);
3422
+ const scored = made.filter(g => !have.has(textOf(g)) && !names.has(textOf(g))).map(g => ({ g, k: pts.filter(pt => !holdsAt(g, pt)).length * 4096 + pts.filter(pt => mayFail(g, pt)).length * 64 + sts.filter(pt => !holdsAt(g, pt)).length })).filter(q => q.k > 0);
3423
+ // (ties: the fewer literals, then the fewer keys, the more particular law)
3424
+ scored.sort((a, b) => b.k - a.k || a.g.cube.length - b.g.cube.length || width2(a.g) - width2(b.g));
3425
+ const out3 = [];
3426
+ for (const { g } of scored) {
3427
+ if (out3.length >= room || stop())
3428
+ break;
3429
+ if (!implied(g) && !atStart(g))
3430
+ out3.push(g);
3431
+ }
3432
+ return out3;
3433
+ };
3434
+ // (minimal implication, DuoAI's: a cube B goes where a kept cube A's law implies B's law: A's keys sent into B's one
3435
+ // to one within each sort, each literal of A entailed by one of B's (the same; the same sum at a bound no larger; a
3436
+ // value at least A's bound); `by`, B's kept impliers)
3437
+ function minimal(pool) {
3438
+ const letters = ['x', 'y', 'z', 'w', 'u'], tok = /\b([xyzwu])\b/g;
3439
+ const litsOf = (f, ren) => f.cube.map(l => {
3440
+ const nm = (i) => atoms[i].name.replace(tok, (_, c) => letters[ren[letters.indexOf(c)]]);
3441
+ return 'at' in l ? { sum: nm(l.at.atom), d: 0, at: l.at.value } : { sum: l.lin.coef.map(([i, c]) => `${c}*${nm(i)}`).sort().join('+'), d: l.lin.d };
3442
+ });
3443
+ const entails = (b, a) => (a.at !== undefined ? b.at !== undefined && b.sum === a.sum && b.at === a.at
3444
+ : b.at !== undefined ? a.sum === `-1*${b.sum}` && -b.at <= a.d : b.sum === a.sum && b.d <= a.d);
3445
+ const sortsOf = (f) => viewSorts.get(f.view) ?? [];
3446
+ const maps2 = (sa, sb) => sa.reduce((acc, s2) => acc.flatMap(r => sb.flatMap((t2, j) => (t2 === s2 && !r.includes(j) ? [[...r, j]] : []))), [[]]);
3447
+ const own = new Map(pool.map(f => [f, litsOf(f, sortsOf(f).map((_, i) => i))]));
3448
+ const implies = (a, b) => a !== b && maps2(sortsOf(a), sortsOf(b)).some(ren => { const la = litsOf(a, ren), lb = own.get(b); return la.every(x2 => lb.some(y2 => entails(y2, x2))); });
3449
+ const order = [...pool].sort((p2, q2) => p2.cube.length - q2.cube.length || sortsOf(p2).length - sortsOf(q2).length);
3450
+ const kept = [], by = new Map();
3451
+ for (const b of order)
3452
+ if (!kept.some(a => implies(a, b)))
3453
+ kept.push(b);
3454
+ for (const b of pool)
3455
+ if (!kept.includes(b))
3456
+ by.set(b, kept.filter(a => implies(a, b)));
3457
+ return { kept: pool.filter(f => kept.includes(f)), by };
3458
+ }
3459
+ // The top-down phase (DuoAI's, research/protocols/engine/DESIGN.md gen/ring2, gen/ring3): the filtered minimal
3460
+ // pool, not given, not implied by the caller's laws, not false at a start; Houdini, each round every cube's goal with
3461
+ // the others assumed (decideLaw, a short cap first, the undecided again at a longer one only where the round would
3462
+ // end with no drop), every failure dropped at once, a cube a dropped one implied back where nothing kept implies it,
3463
+ // and only the goals whose proofs read a dropped cube asked again; then the caller's goals, the cone (their support,
3464
+ // closed under each cube's; a cube with no known support asked with the cone alone, a model's pre-state bringing in
3465
+ // the fixpoint's cubes false there), and prove() of the cone. A fixpoint that doesn't prove leaves the rounds below.
3466
+ // (by default where the pool is past what the rounds' first round takes, 24, and Houdini can afford it, 64: GDP_TD=1
3467
+ // always, GDP_TD=0 never)
3468
+ if ((env.GDP_TD === '1' || (env.GDP_TD !== '0' && made.length > 24 && made.length <= 64)) && !stop())
3469
+ withTrees(() => withStrict(() => {
3470
+ const T0 = performance.now(), ph = (o) => opts.progress?.('join td', { ...o, td: Math.round(performance.now() - T0), wall: Math.round(performance.now() - t0) });
3471
+ const by = minPool.by, q1 = Number(env.GDP_TD_Q1 ?? joinQueryMs / 8), q2 = Number(env.GDP_TD_Q2 ?? q1);
3472
+ ph({ phase: 'start', made: made.length, before: Math.round(tEngine - t0) });
3473
+ const fresh = (f) => !names.has(textOf(f)) && !dead.has(textOf(f)) && !implied(f) && !atStart(f);
3474
+ let hs = made.filter(fresh);
3475
+ ph({ phase: 'pool', cubes: hs.length });
3476
+ const uses = new Map(), undecided = new Set(), reasked = new Set();
3477
+ let asked = new Set(hs);
3478
+ for (let r = 0; hs.length && performance.now() < wallUntil && !stop(); r++) {
3479
+ const ls = [...given, ...hs.map(lawFor)], mm = forLaws(ls).m, failed = new Set(), tr = performance.now(), at = new Map(hs.map((f, i) => [f, given.length + i]));
3480
+ const ask = (f, ms2) => {
3481
+ if (performance.now() > wallUntil) {
3482
+ undecided.add(f);
3483
+ return;
3484
+ }
3485
+ const dl = within(Math.min(wallUntil, performance.now() + ms2), () => decideLaw(mm, ls, at.get(f)));
3486
+ if (!dl) {
3487
+ undecided.add(f);
3488
+ return;
3489
+ }
3490
+ undecided.delete(f);
3491
+ if (dl.proven)
3492
+ uses.set(textOf(f), dl.uses);
3493
+ else {
3494
+ failed.add(f);
3495
+ uses.delete(textOf(f));
3496
+ }
3497
+ };
3498
+ // (a goal left undecided is kept, as optimistic Houdini keeps it, and asked again only once a round has dropped
3499
+ // nothing: a drop's round would ask it again at the same cap for nothing most rounds)
3500
+ let todo = r === 0 ? hs : hs.filter(f => asked.has(f) && !undecided.has(f));
3501
+ // (the goals with the most near misses in the larger instances first, and a failure dropped at
3502
+ // once, the round's later goals asked with the smaller set)
3503
+ if (env.GDP_TD_ORDER !== '0') {
3504
+ todo = [...todo].sort((a2, b2) => (nearMiss.get(b2) ?? 0) - (nearMiss.get(a2) ?? 0));
3505
+ let cur = hs.filter(f => !failed.has(f));
3506
+ for (const f of todo) {
3507
+ if (performance.now() > wallUntil) {
3508
+ undecided.add(f);
3509
+ continue;
3510
+ }
3511
+ const ls2 = [...given, ...cur.map(lawFor)], dl = within(Math.min(wallUntil, performance.now() + q1), () => decideLaw(mm, ls2, given.length + cur.indexOf(f)));
3512
+ if (!dl) {
3513
+ undecided.add(f);
3514
+ continue;
3515
+ }
3516
+ undecided.delete(f);
3517
+ if (dl.proven)
3518
+ uses.set(textOf(f), dl.uses);
3519
+ else {
3520
+ failed.add(f);
3521
+ uses.delete(textOf(f));
3522
+ cur = cur.filter(g => g !== f);
3523
+ }
3524
+ }
3525
+ }
3526
+ else
3527
+ for (const f of todo)
3528
+ ask(f, q1);
3529
+ let second = 0;
3530
+ // (each once: one still undecided then is kept, the cone's proof deciding)
3531
+ if (!failed.size && undecided.size)
3532
+ for (const f of hs.filter(g => undecided.has(g) && !reasked.has(g))) {
3533
+ second++;
3534
+ reasked.add(f);
3535
+ ask(f, Math.max(q1, q2));
3536
+ }
3537
+ ph({ phase: 'round', round: r, cubes: hs.length, asked: todo.length, second, failed: failed.size, undecided: undecided.size, ms: Math.round(performance.now() - tr) });
3538
+ if (!failed.size)
3539
+ break;
3540
+ for (const f of failed)
3541
+ dead.add(textOf(f));
3542
+ const gone = new Set([...failed].map(textOf)), inSet = new Set(hs.filter(f => !failed.has(f)));
3543
+ const back = [...by].filter(([b, as]) => !inSet.has(b) && !dead.has(textOf(b)) && as.some(a => failed.has(a)) && !as.some(a => inSet.has(a))).map(([b]) => b).filter(fresh);
3544
+ hs = [...inSet, ...back];
3545
+ // (only the goals whose proofs read a dropped cube, the new ones, and the undecided are asked again)
3546
+ asked = new Set([...back, ...hs.filter(f => !uses.has(textOf(f)) || uses.get(textOf(f)).some(u => gone.has(u)))]);
3547
+ }
3548
+ if (stop() || performance.now() > wallUntil) {
3549
+ ph({ phase: 'out of time' });
3550
+ return;
3551
+ }
3552
+ // (GDP_TD_DECIDED=1: the cubes Houdini left undecided out before the caller's goals: the cone of decided cubes)
3553
+ if (env.GDP_TD_DECIDED === '1')
3554
+ hs = hs.filter(f => !undecided.has(f));
3555
+ const tc = performance.now(), need = new Set();
3556
+ const callerFrom = () => {
3557
+ need.clear();
3558
+ const ls = [...given, ...hs.map(lawFor), ...(ghost ? [ghost.plain] : [])], mm = withGhost(forLaws(ls).m);
3559
+ for (const l of [...laws, ...(ghost ? [ghost.plain] : [])]) {
3560
+ const dl = within(Math.min(wallUntil, performance.now() + joinQueryMs), () => decideLaw(mm, ls, ls.findIndex(k => k.name === l.name)));
3561
+ if (!dl?.proven)
3562
+ return false;
3563
+ for (const u of dl.uses)
3564
+ need.add(u);
3565
+ }
3566
+ return true;
3567
+ };
3568
+ let callerOk = callerFrom();
3569
+ if (!callerOk && !ghosts) {
3570
+ ghosts = ghostsOf();
3571
+ for (ghost = ghosts.shift(); ghost && !(callerOk = callerFrom()); ghost = ghosts.shift())
3572
+ ;
3573
+ }
3574
+ const close = () => { for (const todo = [...need]; todo.length;)
3575
+ for (const u of uses.get(todo.pop()) ?? [])
3576
+ if (!need.has(u)) {
3577
+ need.add(u);
3578
+ todo.push(u);
3579
+ } };
3580
+ close();
3581
+ for (let it = 0; callerOk && it < 8 && performance.now() < wallUntil && !stop(); it++) {
3582
+ const inCone = hs.filter(f => need.has(textOf(f))), open = inCone.filter(f => !uses.has(textOf(f)));
3583
+ if (!open.length)
3584
+ break;
3585
+ const ls = [...given, ...inCone.map(lawFor), ...(ghost ? [ghost.plain] : [])], mm = withGhost(forLaws(ls).m);
3586
+ let grew = 0, settledN = 0;
3587
+ for (const f of open) {
3588
+ if (performance.now() > wallUntil)
3589
+ break;
3590
+ const dl = within(Math.min(wallUntil, performance.now() + q2), () => decideLaw(mm, ls, ls.findIndex(k => k.name === textOf(f))));
3591
+ if (dl?.proven) {
3592
+ uses.set(textOf(f), dl.uses);
3593
+ settledN++;
3594
+ continue;
3595
+ }
3596
+ if (!dl || !dl.goal.endsWith('@step'))
3597
+ continue;
3598
+ const pt = ptOf(preOf(dl.witness));
3599
+ for (const g of hs)
3600
+ if (!need.has(textOf(g)) && !holdsAt(g, pt)) {
3601
+ need.add(textOf(g));
3602
+ grew++;
3603
+ }
3604
+ }
3605
+ close();
3606
+ if (!grew && !settledN)
3607
+ break;
3608
+ }
3609
+ let cut = hs.filter(f => need.has(textOf(f)));
3610
+ ph({ phase: 'cone', fixpoint: hs.length, undecided: undecided.size, caller: callerOk ? 1 : 0, cone: cut.length, undecidedInCone: cut.filter(f => undecided.has(f)).length, ms: Math.round(performance.now() - tc) });
3611
+ if (callerOk)
3612
+ for (let k = 0; k < 24 && performance.now() < wallUntil && !stop(); k++) {
3613
+ const t2 = performance.now(), setLaws = [...laws, ...cut.map(lawFor), ...(ghost ? [ghost.some] : [])];
3614
+ const h0 = memoHits.n, m0 = memoHits.miss;
3615
+ let v = within(t0 + ms, () => prove(setLaws, true));
3616
+ const hits = memoHits.n - h0, misses = memoHits.miss - m0, fastMs = Math.round(performance.now() - t2), fast = v.proven && v.checked ? 1 : 0, fastAt = String(v.goal ?? '').slice(0, 100);
3617
+ if (!(v.proven && v.checked))
3618
+ v = within(t0 + ms, () => prove(setLaws));
3619
+ const at = String(v.goal ?? ''), g = v.proven && v.checked ? undefined : cut.find(c => at.startsWith(`${textOf(c)} @`));
3620
+ ph({ phase: 'prove', cubes: cut.length, proven: v.proven && v.checked ? 1 : 0, ms: Math.round(performance.now() - t2), fastMs, fast, hits, misses, setKey: memoHits.setKey, tdKey: env.GDP_MEMO_TRACE ? machineKey(forLaws([...given, ...cut.map(lawFor)]).m) : '', diff: env.GDP_MEMO_TRACE ? ((x, y) => { let i = 0; while (i < x.length && x[i] === y[i])
3621
+ i++; return `${i}: ${x.slice(Math.max(0, i - 60), i + 60)} || ${y.slice(Math.max(0, i - 60), i + 60)}`; })(JSON.stringify(forLaws([...given, ...cut.map(lawFor)]).m), memoHits.setJson) : '', fastAt, at: at.slice(0, 100) });
3622
+ if (v.proven && v.checked) {
3623
+ why = 'inductive';
3624
+ cone = cut;
3625
+ enumProof = v;
3626
+ enumSome = ghost ? [ghost.some] : [];
3627
+ cubes = cut;
3628
+ break;
3629
+ }
3630
+ if (!g)
3631
+ break;
3632
+ cut = cut.filter(c => c !== g);
3633
+ }
3634
+ }));
3635
+ for (let round = 0, over = false; !over && cubes.length && !stop(); round++)
3636
+ withTrees(() => {
3637
+ // (one cube once: a cube in the set is not pending, and a text in the set once)
3638
+ cubes = cubes.filter((g, i) => !atStart(g) && cubes.findIndex(h => textOf(h) === textOf(g)) === i);
3639
+ for (const g of cubes)
3640
+ if (pending.has(g) || [...pending].some(h => textOf(h) === textOf(g)))
3641
+ for (const h of [...pending])
3642
+ if (textOf(h) === textOf(g))
3643
+ pending.delete(h);
3644
+ for (const g of cubes)
3645
+ if (!addedAt.has(g))
3646
+ addedAt.set(g, round);
3647
+ const stand = (nm) => { stands.add(nm); provenAt.set(nm, round); };
3648
+ // (DuoAI's: the Houdini fixpoint of the relevant candidates, once, with 40% of the engine's time left: the set, the pending cubes and every cube a
3649
+ // counterexample ranked in its top eight, a cube the fast proof fails at dropped (the usual proof where it fails at
3650
+ // a cube the rounds proved), until the whole proves or the time is out)
3651
+ if (!houdinied && !enumProof && performance.now() > wallUntil - 0.4 * (wallUntil - engineStart)) {
3652
+ houdinied = true;
3653
+ let hs = [...new Map([...cubes, ...pending, ...pool].filter(g => !dead.has(textOf(g)) && !atStart(g)).map(g => [textOf(g), g])).values()];
3654
+ for (let k = 0; k < 200 && hs.length && performance.now() < wallUntil && !stop(); k++) {
3655
+ const t2 = performance.now(), hl = [...laws, ...hs.map(lawFor), ...(ghost ? [ghost.some] : [])];
3656
+ let v = within(t0 + ms, () => prove(hl, true));
3657
+ const at0 = String(v.goal ?? ''), g0 = v.proven && v.checked ? undefined : hs.find(c => at0.startsWith(`${textOf(c)} @`));
3658
+ // (or at a law the caller gave, a kind's: no cube to blame, so the usual proof's verdict)
3659
+ if (!(v.proven && v.checked) && (g0 ? at0.endsWith('@step') && stands.has(lawFor(g0).name) : true))
3660
+ v = within(t0 + ms, () => prove(hl));
3661
+ const at = String(v.goal ?? ''), g = v.proven && v.checked ? undefined : hs.find(c => at.startsWith(`${textOf(c)} @`));
3662
+ opts.progress?.('join houdini', { cubes: hs.length, proven: v.proven && v.checked ? 1 : 0, ms: Math.round(performance.now() - t2), at: at.slice(0, 100) });
3663
+ if (v.proven && v.checked) {
3664
+ why = 'inductive';
3665
+ cone = hs;
3666
+ enumProof = v;
3667
+ enumSome = ghost ? [ghost.some] : [];
3668
+ cubes = hs;
3669
+ break;
3670
+ }
3671
+ if (!g)
3672
+ break;
3673
+ hs = hs.filter(c => c !== g);
3674
+ }
3675
+ }
3676
+ if (enumProof) {
3677
+ over = true;
3678
+ return;
3679
+ }
3680
+ let asked = 0, cubeMs = 0, tGoal = 0;
3681
+ // (later rounds less the sums pass's reserve, unless the caller's law holds from the set: Houdini's part, then)
3682
+ const kUntil = () => wallUntil - (round && !held ? reserve : 0);
3683
+ const real = new Set(), unsure = new Set(), lsAll = [...given, ...cubes.map(lawFor), ...(ghost ? [ghost.plain] : [])], blocked2 = [], mmRound = withGhost(forLaws(lsAll).m), at2 = new Map(cubes.map((g, i) => [g, i]));
3684
+ const version = versionOf(), startReal = new Set(), promoted = [];
3685
+ let caller = false, complete = true, again = false, coneTried = false;
3686
+ // (relative induction of the caller's cone first, IC3's: once the caller's goals (and the ∃ law's) are proven, the
3687
+ // cubes their proofs read, closed under each cube's own proof's, each asked (one undecided stays, its support
3688
+ // unknown), and the cone proven whole; a proof ends the rounds. A cone cube with a model, or the one the cone's
3689
+ // proof fails at, is left out and the caller asked again (Houdini over the cone), a few times. The memo keeps every
3690
+ // decision for the round's goals after it. GDP_IC3_CONE=0 off)
3691
+ const tryCone = () => {
3692
+ const t1 = performance.now(), out2 = new Set();
3693
+ for (let it = 0; it < 6; it++) {
3694
+ const cs = cubes.filter(c => !out2.has(c)), ls2 = it ? [...given, ...cs.map(lawFor), ...(ghost ? [ghost.plain] : [])] : lsAll, mm2 = it ? withGhost(forLaws(ls2).m) : mmRound;
3695
+ const byName = new Map(cs.map(c => [textOf(c), c])), at3 = new Map(cs.map((c, i) => [c, given.length + i])), need = new Set(), todo = [];
3696
+ const ask = (i) => (performance.now() > kUntil() || stop() ? undefined : within(Math.min(kUntil(), performance.now() + joinQueryMs / 8), () => decideLaw(mm2, ls2, i)));
3697
+ const add = (us) => { for (const u of us)
3698
+ if (!need.has(u)) {
3699
+ need.add(u);
3700
+ todo.push(u);
3701
+ } };
3702
+ for (const l of [...laws, ...(ghost ? [ghost.plain] : [])]) {
3703
+ const dl = ask(ls2.findIndex(k => k.name === l.name));
3704
+ if (!dl?.proven)
3705
+ return false;
3706
+ add(dl.uses);
3707
+ }
3708
+ let open2 = 0, failed;
3709
+ while (todo.length && !failed) {
3710
+ const c = byName.get(todo.pop());
3711
+ if (!c)
3712
+ continue;
3713
+ if (performance.now() > kUntil() || stop())
3714
+ return false;
3715
+ const dl = ask(at3.get(c));
3716
+ if (!dl) {
3717
+ open2++;
3718
+ continue;
3719
+ }
3720
+ if (dl.proven)
3721
+ add(dl.uses);
3722
+ else
3723
+ failed = c;
3724
+ }
3725
+ if (failed) {
3726
+ out2.add(failed);
3727
+ opts.progress?.('join cone', { round, it, failed: textOf(failed).slice(0, 100), need: need.size, ms: Math.round(performance.now() - t1) });
3728
+ continue;
3729
+ }
3730
+ const cut = cs.filter(c => need.has(textOf(c)));
3731
+ const v = within(t0 + ms, () => prove([...laws, ...cut.map(lawFor), ...(ghost ? [ghost.some] : [])], true));
3732
+ const at = String(v.goal ?? ''), g = v.proven && v.checked ? undefined : cut.find(c => at.startsWith(`${textOf(c)} @`));
3733
+ opts.progress?.('join cone', { round, it, cubes: cubes.length, cone: cut.length, undecided: open2, proven: v.proven && v.checked ? 1 : 0, ms: Math.round(performance.now() - t1), at: at.slice(0, 100) });
3734
+ if (v.proven && v.checked) {
3735
+ why = 'inductive';
3736
+ cone = cut;
3737
+ enumProof = v;
3738
+ enumSome = ghost ? [ghost.some] : [];
3739
+ cubes = cut;
3740
+ return true;
3741
+ }
3742
+ if (!g)
3743
+ return false;
3744
+ out2.add(g);
3745
+ }
3746
+ return false;
3747
+ };
3748
+ {
3749
+ for (const goal of [...laws.map(l => l.name), ...(ghost ? [ghost.plain.name] : []), ...cubes]) {
3750
+ if (performance.now() > kUntil() || stop()) {
3751
+ complete = false;
3752
+ break;
3753
+ }
3754
+ const f = typeof goal === 'string' ? undefined : goal, ls = lsAll, others = cubes.filter(g => g !== f);
3755
+ const idx = f ? given.length + at2.get(f) : ls.findIndex(l => l.name === goal), mm = mmRound;
3756
+ if (f && !coneTried && env.GDP_IC3_CONE !== '0') {
3757
+ coneTried = true;
3758
+ if (tryCone()) {
3759
+ over = true;
3760
+ return;
3761
+ }
3762
+ }
3763
+ if (f)
3764
+ held = true;
3765
+ if ((f && kept2.has(f)) || stands.has(ls[idx].name))
3766
+ continue;
3767
+ const was = settled.get(ls[idx].name);
3768
+ if (was && was.every(n2 => ls.some(l => l.name === n2)))
3769
+ continue;
3770
+ settled.delete(ls[idx].name);
3771
+ // (a goal decided by the EPR path alone first (a proof or a model, a cube's within a quarter of a join query, the
3772
+ // caller's within one); else a model or a refutation of the CDCL search alone, then the proof path's)
3773
+ if (f) {
3774
+ if (tGoal)
3775
+ cubeMs += performance.now() - tGoal;
3776
+ tGoal = performance.now();
3777
+ asked++;
3778
+ }
3779
+ else
3780
+ tGoal = 0;
3781
+ const tDl = performance.now(), dlEnd = Math.min(kUntil(), performance.now() + (f ? joinQueryMs / 8 : joinQueryMs)), dl = within(dlEnd, () => decideLaw(mm, ls, idx));
3782
+ // (the EPR path out of time on the caller's goal, or refuting it with a core the kernel's search didn't finish:
3783
+ // the proof path would be no quicker)
3784
+ const outOfTime = !dl && (performance.now() - tDl >= 0.9 * (dlEnd - tDl) || decideNote.refuted);
3785
+ if (dl?.proven) {
3786
+ stand(ls[idx].name);
3787
+ continue;
3788
+ }
3789
+ let isReal = !!dl && (f && dl.goal.endsWith('@start') ? badAtStart(f, dl.witness) : realCti(dl.witness, f, others)), wit = dl?.witness;
3790
+ if (f && isReal && dl.goal.endsWith('@start'))
3791
+ startReal.add(f);
3792
+ // (a cube the EPR path ran out of time on: unsure at once, kept as optimistic Houdini keeps it; the CDCL search
3793
+ // after it would be no quicker)
3794
+ if (!dl && !(f && outOfTime)) {
3795
+ const inst = mapNames.length ? lawInstances(mm, ls, idx) : undefined, g = obligations(mm, ls, inst ? { [ls[idx].name]: inst } : {}, idx)[1];
3796
+ // (the engine's wall too: a counted budget alone runs on past it, wo's 6 s)
3797
+ // (its share on the wall too: a counted budget of 2 s ran 8.8 s on wo's 3-key cubes)
3798
+ const quick = budgeted(joinQueryMs / 4, until2 => growCdcl(g, new Map(), { nodes: 0, until: until2 }, { model: true, core: true, wall: Math.min(kUntil(), performance.now() + joinQueryMs / 4) }));
3799
+ if (!('tree' in quick) && quick.why === REFUTED && quick.core) {
3800
+ const lawAt = lawsFrom(mm, ls, false, inst ?? {});
3801
+ settled.set(ls[idx].name, [...new Set([...quick.core].map(h => lawAt.get(h)).filter((k) => k !== undefined && k >= given.length && k !== idx).map(k => ls[k].name))]);
3802
+ }
3803
+ if ('tree' in quick || quick.why === REFUTED) {
3804
+ stand(ls[idx].name);
3805
+ continue;
3806
+ }
3807
+ // (the caller's law's model from the proof path alone: EPR's, real or with the instances that refute it)
3808
+ isReal = !!f && quick.stuck === 'sat' && !!quick.witness && realCti(quick.witness, f, others);
3809
+ if (quick.stuck === 'sat')
3810
+ wit = quick.witness;
3811
+ // (a cube the EPR path doesn't decide: the CDCL search's answer alone; the caller's, the proof path's too)
3812
+ if (!isReal && !f && !outOfTime) {
3813
+ proofs++;
3814
+ const r2 = within(Math.min(kUntil() - 2000, performance.now() + Math.max(joinQueryMs * 1.25, (kUntil() - performance.now()) / 2)), () => proveLaw(mm, ls, idx));
3815
+ if (r2.proven) {
3816
+ stand(ls[idx].name);
3817
+ continue;
3818
+ }
3819
+ isReal = !!r2.witness && realCti(r2.witness, f, others);
3820
+ wit = r2.witness ?? wit;
3821
+ }
3822
+ }
3823
+ // (a real counterexample from a state no small state is: its diagram blocked, the goal's laws kept)
3824
+ // (a blocker blocked already this round blocks as well: the goal kept, nothing new blocked; one in the set doesn't
3825
+ // (a model the set rules out is no counterexample to learn from))
3826
+ const fresh = (g) => !blocked2.some(h => textOf(h) === textOf(g)) && !!blocked2.push(g);
3827
+ const outside = (g) => !ls.some(l => l.name === textOf(g));
3828
+ const ds = isReal && lastPre ? blockers(lastPre).filter(outside) : [];
3829
+ ds.filter(fresh);
3830
+ // (the caller's: blocked at once, IC3's order, the caller asked again before the cubes)
3831
+ if (ds.length && !f && lastPre)
3832
+ pres.push(lastPre);
3833
+ if (ds.length) {
3834
+ if (!f) {
3835
+ held = false;
3836
+ if (!ghosts) {
3837
+ ghosts = ghostsOf();
3838
+ ghost = ghosts.shift();
3839
+ if (ghost)
3840
+ opts.progress?.('join exists', { law: ghost.plain.name.slice(0, 160) });
3841
+ }
3842
+ break;
3843
+ }
3844
+ continue;
3845
+ }
3846
+ // (a model the interpreter doesn't confirm: PDR's obligation at its state, its diagrams blocked and the goal kept
3847
+ // (the caller's asked again first) where a row of it no small state has; else unsure)
3848
+ if (!isReal && wit) {
3849
+ const pre = preOf(wit);
3850
+ const ds2 = blockers(pre).filter(outside);
3851
+ ds2.filter(fresh);
3852
+ if (ds2.length && !f)
3853
+ pres.push(pre);
3854
+ if (ds2.length) {
3855
+ if (!f) {
3856
+ held = false;
3857
+ break;
3858
+ }
3859
+ continue;
3860
+ }
3861
+ ;
3862
+ (f ? subs : pres).push(pre);
3863
+ }
3864
+ else if (!f && isReal && lastPre)
3865
+ pres.push(lastPre);
3866
+ // (the ∃ law's own goal unproven: it goes; the caller's unproven with no diagram (every view's rows reached, or no
3867
+ // model to read): the ∀∃ laws, once)
3868
+ if (!f && ghost && goal === ghost.plain.name) {
3869
+ opts.progress?.('join exists', { dropped: ghost.plain.name.slice(0, 120) });
3870
+ ghost = ghosts?.shift();
3871
+ stands.clear();
3872
+ again = true;
3873
+ break;
3874
+ }
3875
+ if (!f && !ghosts) {
3876
+ const t1 = performance.now();
3877
+ ghosts = ghostsOf();
3878
+ ghost = ghosts.shift();
3879
+ opts.progress?.('join exists', { law: ghost ? `${ghost.plain.name.slice(0, 160)}; ${ghost.name} := ${JSON.stringify(ghost.step).slice(0, 160)}` : 'none', ms: Math.round(performance.now() - t1) });
3880
+ if (ghost) {
3881
+ again = true;
3882
+ held = false;
3883
+ break;
3884
+ }
3885
+ }
3886
+ if (!f) {
3887
+ caller = true;
3888
+ held = false;
3889
+ break;
3890
+ }
3891
+ ;
3892
+ (isReal ? real : unsure).add(f);
3893
+ }
3894
+ }
3895
+ opts.progress?.('join enumerated', { round, cubes: cubes.length, real: real.size, unsure: unsure.size, caller: caller ? 1 : 0, diagrams: blocked2.length, ms: Math.round(performance.now() - t0) });
3896
+ // (optimistic Houdini: an unsure cube holds at every small state and every step from one (they are its rows), so
3897
+ // it stays; the set's proof decides, a cube it fails at dropped and the rounds go on)
3898
+ // (IC3's push: the pending cubes asked together, each with the set and every other pending one assumed (one frame),
3899
+ // those with a model out (an undecided one stays, as Houdini keeps it) and the rest asked again, until none has
3900
+ // one; what is left comes back into the set together.
3901
+ // Once the set has changed since the last push; each cube back twice at most)
3902
+ let frame = complete && !caller ? [...pending].filter(g => tried.get(g) !== version && (backs.get(g) ?? 0) < 2) : [];
3903
+ const pushed = frame.length;
3904
+ for (const g of frame)
3905
+ tried.set(g, version);
3906
+ for (let pass = 0; frame.length && pass < 4 && performance.now() < kUntil() && !stop(); pass++) {
3907
+ frame = frame.filter((g, i) => !lsAll.some(l => l.name === textOf(g)) && frame.findIndex(h => textOf(h) === textOf(g)) === i);
3908
+ const lsP = [...lsAll, ...frame.map(lawFor)], mmP = withGhost(forLaws(lsP).m), failed = new Set();
3909
+ frame.forEach((g, i) => {
3910
+ if (performance.now() > kUntil()) {
3911
+ failed.add(g);
3912
+ return;
3913
+ }
3914
+ const dl = within(Math.min(kUntil(), performance.now() + joinQueryMs / 8), () => decideLaw(mmP, lsP, lsAll.length + i));
3915
+ if (!dl || dl.proven)
3916
+ return;
3917
+ failed.add(g);
3918
+ // (the push's counterexample an obligation, IC3's: blocked as a round's are, by the enumeration's cubes false
3919
+ // there, so that the next push has what it lacked)
3920
+ if (dl.goal.endsWith('@step'))
3921
+ for (const b of blockers(preOf(dl.witness)))
3922
+ if (!lsP.some(l => l.name === textOf(b)) && !pending.has(b) && !blocked2.some(h => textOf(h) === textOf(b)))
3923
+ blocked2.push(b);
3924
+ });
3925
+ if (!failed.size) {
3926
+ promoted.push(...frame);
3927
+ break;
3928
+ }
3929
+ frame = frame.filter(g => !failed.has(g));
3930
+ }
3931
+ if (pending.size)
3932
+ opts.progress?.('join frames', { round, pending: pending.size, pushed, promoted: promoted.length });
3933
+ // (IC3's frames: a failing cube pending, not dropped, unless a start breaks it)
3934
+ const drops = new Set(real);
3935
+ for (const g of unsure)
3936
+ kept2.add(g);
3937
+ const demote = (gs) => { for (const g of gs) {
3938
+ if (startReal.has(g))
3939
+ dead.add(textOf(g));
3940
+ else
3941
+ pending.add(g);
3942
+ addedAt.delete(g);
3943
+ tried.delete(g);
3944
+ } };
3945
+ const back = () => { for (const g of promoted) {
3946
+ pending.delete(g);
3947
+ backs.set(g, (backs.get(g) ?? 0) + 1);
3948
+ addedAt.delete(g);
3949
+ } return promoted; };
3950
+ // (the costliest round's mean a goal, 250 ms at least: round 0's minimal cubes are the cheapest)
3951
+ if (asked > 1)
3952
+ perGoal = Math.max(perGoal, 250, cubeMs / (asked - 1));
3953
+ // (the next round's new cubes: what a quarter of what is left affords past the goals it asks again, 8 at least)
3954
+ const grow = (kept) => { const ask = kept.filter(g => !kept2.has(g) && !stands.has(lawFor(g).name)).length, afford = perGoal ? Math.floor((wallUntil - performance.now()) / (4 * perGoal)) : 16; return relevant(Math.max(8, Math.min(256 - kept.length, afford - ask)), kept); };
3955
+ if (blocked2.length) {
3956
+ if (drops.size)
3957
+ unstand(drops);
3958
+ demote(drops);
3959
+ const kept = [...cubes.filter(g => !drops.has(g)), ...back(), ...blocked2];
3960
+ cubes = [...kept, ...grow(kept)];
3961
+ return;
3962
+ }
3963
+ if (again)
3964
+ return;
3965
+ // (the caller's law unproven with no diagram: the cubes its counterexamples make relevant, while there are some)
3966
+ if (caller && complete) {
3967
+ if (drops.size)
3968
+ unstand(drops);
3969
+ demote(drops);
3970
+ const kept = [...cubes.filter(g => !drops.has(g)), ...back()], more = grow(kept);
3971
+ if (more.length) {
3972
+ cubes = [...kept, ...more];
3973
+ return;
3974
+ }
3975
+ }
3976
+ // (the set's proof, relative induction over the set: a cube it fails at dropped and the proof asked again at once, the
3977
+ // rounds again only where the caller's law fails or a cube's goal can't be named)
3978
+ const gone = [];
3979
+ let grown = false;
3980
+ if (complete && !caller && !drops.size)
3981
+ for (let k = 0; k < 24 && !stop() && performance.now() < wallUntil; k++) {
3982
+ const t2 = performance.now(), setLaws = [...laws, ...cubes.map(lawFor), ...(ghost ? [ghost.some] : [])];
3983
+ let v = within(t0 + ms, () => prove(setLaws, true));
3984
+ // (the fast proof failing at a cube whose own goal the rounds proved from this set: the two disagree, and the
3985
+ // usual proof decides (proveSetFast has a spurious model on ring's own-id law))
3986
+ const at0 = String(v.goal ?? ''), g0 = v.proven && v.checked ? undefined : cubes.find(c => at0.startsWith(`${textOf(c)} @`));
3987
+ if (g0 && at0.endsWith('@step') && stands.has(lawFor(g0).name))
3988
+ v = within(t0 + ms, () => prove(setLaws));
3989
+ const at = String(v.goal ?? ''), g = v.proven && v.checked ? undefined : cubes.find(c => at.startsWith(`${textOf(c)} @`));
3990
+ opts.progress?.('join set', { cubes: cubes.length, exists: ghost ? 1 : 0, proven: v.proven && v.checked ? 1 : 0, ms: Math.round(performance.now() - t2), at: at.slice(0, 120) });
3991
+ if (v.proven && v.checked) {
3992
+ why = 'inductive';
3993
+ cone = cubes;
3994
+ enumProof = v;
3995
+ enumSome = ghost ? [ghost.some] : [];
3996
+ break;
3997
+ }
3998
+ if (!g)
3999
+ break;
4000
+ // (IC3's: the failing cube's model at its step, blocked by the enumeration's cubes false at its state where there
4001
+ // are some new ones, the cube kept and the rounds again; else the cube dropped)
4002
+ const wit2 = v.witness, bs = wit2 && at.endsWith('@step') ? blockers(preOf(wit2)).filter(b => !cubes.some(c => textOf(c) === textOf(b)) && ![...pending].some(c => textOf(c) === textOf(b)) && !dead.has(textOf(b)) && !atStart(b)) : [];
4003
+ if (bs.length) {
4004
+ cubes = [...cubes, ...bs];
4005
+ grown = true;
4006
+ break;
4007
+ }
4008
+ if (wit2 && at.endsWith('@step'))
4009
+ subs.push(preOf(wit2));
4010
+ cubes = cubes.filter(c => c !== g);
4011
+ gone.push(g);
4012
+ }
4013
+ if (!complete || caller || (!drops.size && !gone.length && !grown && !promoted.length && !pending.size) || enumProof)
4014
+ over = true;
4015
+ if (drops.size || gone.length)
4016
+ unstand([...drops, ...gone]);
4017
+ demote([...drops, ...gone]);
4018
+ cubes = [...cubes.filter(g => !drops.has(g)), ...back()];
4019
+ // (nothing changed and nothing left to push: the frames at their fixpoint, the set grown by relevance to the
4020
+ // counterexamples while there is something relevant)
4021
+ if (!enumProof && !drops.size && !gone.length && !grown && !promoted.length && [...pending].every(g => tried.get(g) === versionOf() || (backs.get(g) ?? 0) >= 2)) {
4022
+ const more = complete && !enumProof ? grow(cubes) : [];
4023
+ if (more.length) {
4024
+ cubes = [...cubes, ...more];
4025
+ over = false;
4026
+ }
4027
+ else
4028
+ over = true;
4029
+ }
4030
+ });
4031
+ }
4032
+ };
2322
4033
  for (;;) {
2323
4034
  if (now() > jUntil || stop()) {
2324
4035
  why = 'time';
@@ -2361,8 +4072,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2361
4072
  // (before the whole set, the forms proven so far beside the context: a proof there is a proof with the whole set,
2362
4073
  // at a fraction of its hypotheses; a model there, the whole set asked as before)
2363
4074
  const provenFirst = () => { const ps = whole.filter(f => !ctx.includes(f) && stood.has(textOf(f))); return ps.length && ctx.length + ps.length < whole.length / 2 ? [...ctx, ...ps] : undefined; };
2364
- for (let attempt = 0; attempt <= joinAttempts; attempt++) {
2365
- if (attempt === joinAttempts && ctx !== whole) {
4075
+ // (a few tries, more where the set is large: until the context would hold a sixteenth of it)
4076
+ const tries = Math.max(joinAttempts, Math.ceil(whole.length / 16 / joinAdd));
4077
+ for (let attempt = 0; attempt <= tries; attempt++) {
4078
+ if (attempt === tries && ctx !== whole) {
2366
4079
  const pf = provenFirst();
2367
4080
  if (pf) {
2368
4081
  const out = stepWith(todo, todoForm, pf);
@@ -2388,7 +4101,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2388
4101
  if (ctx === whole)
2389
4102
  break;
2390
4103
  ctx = whole;
2391
- attempt = joinAttempts - 1;
4104
+ attempt = tries - 1;
2392
4105
  continue;
2393
4106
  }
2394
4107
  const w = out.witness, { params: pp0, st: st0 } = stateOf(w), pre0 = pointOf(pp0, st0);
@@ -2417,7 +4130,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2417
4130
  const w = witness, { params, st } = stateOf(w);
2418
4131
  if (todoForm?.nevers)
2419
4132
  neversBroken++;
2420
- const input = Object.fromEntries(m.inputs.map(i => [i, w[i] ?? 0]));
4133
+ const input = requestOf(w);
2421
4134
  let post;
2422
4135
  try {
2423
4136
  post = run.step(params, st, input);
@@ -2563,6 +4276,9 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2563
4276
  }
2564
4277
  opts.progress?.('join', { round: rounds, set: set.length, ms: qms, goal: todo.slice(0, 60), joins: joins - j0, walked, dropped: dropped - d0 });
2565
4278
  }
4279
+ // (a rule whose scalars the runs held at a few values each: no counter, the engine's shape)
4280
+ if (engineFollows() && why !== 'inductive')
4281
+ engine();
2566
4282
  opts.progress?.('join end', { rounds, set: set.length, why, cone: cone.length, ms: Math.round(performance.now() - jT0) });
2567
4283
  // (unproven, the search below begins as it would have: the candidates and the counterexamples as they were)
2568
4284
  if (why === 'inductive')
@@ -2618,7 +4334,9 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2618
4334
  };
2619
4335
  // A cell form's mirror, −Σ ≤ −d beside Σ ≤ d under the same guard (its text).
2620
4336
  const mirrorText = (f) => (!f.cells || f.mod || f.cong || f.never || f.nevers || f.cube || f.unreachable || f.also || !f.coef.length ? undefined : textOf({ ...f, coef: f.coef.map(([i, c]) => [i, -c]), d: -f.d }));
2621
- for (let iter = 0; iter < 300 && now() < until && !stop(); iter++) {
4337
+ if (enumProof)
4338
+ last = enumProof;
4339
+ for (let iter = 0; iter < 300 && !enumProof && now() < until && !stop(); iter++) {
2622
4340
  const began = now(), wall = performance.now();
2623
4341
  // (each law proven alone, then the set as a whole: the same goals, grown once)
2624
4342
  last = withTrees(() => search([...given, ...chosen.map(lawFor)]));
@@ -2691,8 +4409,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2691
4409
  trace('end', { proven: false, stopped: stop() });
2692
4410
  return { ...last, found: [], stats: stats(samples.length, forms.length, alive.length) };
2693
4411
  }
2694
- // Take out what the proof doesn't need, the last added first.
2695
- for (const f of opts.minimize === false ? [] : [...chosen].reverse()) {
4412
+ // Take out what the proof doesn't need, the last added first (not the engine's set: Houdini's, each cube minimal).
4413
+ for (const f of opts.minimize === false || enumProof ? [] : [...chosen].reverse()) {
2696
4414
  if (now() > until || stop())
2697
4415
  break;
2698
4416
  const without = chosen.filter(g => g !== f), v = prove([...laws, ...without.map(lawFor)]);
@@ -2703,5 +4421,5 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2703
4421
  if (kept.length)
2704
4422
  rule?.dividesBy(...kept);
2705
4423
  trace('end', { proven: true, stopped: stop(), found: chosen.map(f => textOf(f)).join('; ') });
2706
- return { ...last, found: chosen.map(f => { const law = lawFor(f), text = law.name, source = sourceOf(f, text); return { law, text, ...(source ? { source } : {}) }; }), stats: stats(samples.length, forms.length, alive.length) };
4424
+ return { ...last, found: [...chosen.map(f => { const law = lawFor(f), text = law.name, source = sourceOf(f, text); return { law, text, ...(source ? { source } : {}) }; }), ...(enumProof ? enumSome : []).map(law => ({ law, text: law.name }))], stats: stats(samples.length, forms.length, alive.length) };
2707
4425
  }