gdp-wired 0.46.0 → 0.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/README.md +18 -5
  2. package/dist/core/carry.d.ts +15 -0
  3. package/dist/core/carry.js +651 -0
  4. package/dist/core/cli.d.ts +4 -1
  5. package/dist/core/cli.js +31 -11
  6. package/dist/core/count-cases.d.ts +24 -0
  7. package/dist/core/count-cases.js +320 -0
  8. package/dist/core/count-cert-grow.d.ts +4 -0
  9. package/dist/core/count-cert-grow.js +37 -0
  10. package/dist/core/count-cert-transport.d.ts +3 -0
  11. package/dist/core/count-cert-transport.js +58 -0
  12. package/dist/core/count-completion.d.ts +9 -0
  13. package/dist/core/count-completion.js +27 -0
  14. package/dist/core/count-cubes.d.ts +8 -0
  15. package/dist/core/count-cubes.js +69 -0
  16. package/dist/core/count-demand.d.ts +37 -0
  17. package/dist/core/count-demand.js +361 -0
  18. package/dist/core/count-facts.d.ts +52 -0
  19. package/dist/core/count-facts.js +247 -0
  20. package/dist/core/count-focus-proof.d.ts +8 -0
  21. package/dist/core/count-focus-proof.js +140 -0
  22. package/dist/core/count-focused.d.ts +22 -0
  23. package/dist/core/count-focused.js +676 -0
  24. package/dist/core/count-ranges.d.ts +5 -0
  25. package/dist/core/count-ranges.js +65 -0
  26. package/dist/core/count-recovery/action-guard.d.ts +5 -0
  27. package/dist/core/count-recovery/action-guard.js +51 -0
  28. package/dist/core/count-recovery/boolean-core.d.ts +16 -0
  29. package/dist/core/count-recovery/boolean-core.js +258 -0
  30. package/dist/core/count-recovery/carried-case.d.ts +2 -0
  31. package/dist/core/count-recovery/carried-case.js +24 -0
  32. package/dist/core/count-recovery/conditional-check-cache.d.ts +23 -0
  33. package/dist/core/count-recovery/conditional-check-cache.js +130 -0
  34. package/dist/core/count-recovery/conditional-cuts.d.ts +6 -0
  35. package/dist/core/count-recovery/conditional-cuts.js +318 -0
  36. package/dist/core/count-recovery/conditional-proof.d.ts +19 -0
  37. package/dist/core/count-recovery/conditional-proof.js +306 -0
  38. package/dist/core/count-recovery/derivability-closure.d.ts +14 -0
  39. package/dist/core/count-recovery/derivability-closure.js +533 -0
  40. package/dist/core/count-recovery/empty-count-source.d.ts +2 -0
  41. package/dist/core/count-recovery/empty-count-source.js +40 -0
  42. package/dist/core/count-recovery/field-bound-lemmas.d.ts +23 -0
  43. package/dist/core/count-recovery/field-bound-lemmas.js +640 -0
  44. package/dist/core/count-recovery/field-case.d.ts +5 -0
  45. package/dist/core/count-recovery/field-case.js +89 -0
  46. package/dist/core/count-recovery/field-demand.d.ts +46 -0
  47. package/dist/core/count-recovery/field-demand.js +47 -0
  48. package/dist/core/count-recovery/field-only.d.ts +3 -0
  49. package/dist/core/count-recovery/field-only.js +18 -0
  50. package/dist/core/count-recovery/fold-path.d.ts +6 -0
  51. package/dist/core/count-recovery/fold-path.js +35 -0
  52. package/dist/core/count-recovery/frame-lemmas.d.ts +9 -0
  53. package/dist/core/count-recovery/frame-lemmas.js +120 -0
  54. package/dist/core/count-recovery/guard-cases.d.ts +12 -0
  55. package/dist/core/count-recovery/guard-cases.js +138 -0
  56. package/dist/core/count-recovery/key-closure.d.ts +14 -0
  57. package/dist/core/count-recovery/key-closure.js +62 -0
  58. package/dist/core/count-recovery/leaf-allowance.d.ts +4 -0
  59. package/dist/core/count-recovery/leaf-allowance.js +7 -0
  60. package/dist/core/count-recovery/lift-count-proxies.d.ts +6 -0
  61. package/dist/core/count-recovery/lift-count-proxies.js +175 -0
  62. package/dist/core/count-recovery/live-dependencies.d.ts +6 -0
  63. package/dist/core/count-recovery/live-dependencies.js +76 -0
  64. package/dist/core/count-recovery/member-inclusions.d.ts +11 -0
  65. package/dist/core/count-recovery/member-inclusions.js +168 -0
  66. package/dist/core/count-recovery/member-premises.d.ts +29 -0
  67. package/dist/core/count-recovery/member-premises.js +114 -0
  68. package/dist/core/count-recovery/natural-cases.d.ts +6 -0
  69. package/dist/core/count-recovery/natural-cases.js +59 -0
  70. package/dist/core/count-recovery/ops.d.ts +6 -0
  71. package/dist/core/count-recovery/ops.js +8 -0
  72. package/dist/core/count-recovery/pre-state-source.d.ts +8 -0
  73. package/dist/core/count-recovery/pre-state-source.js +18 -0
  74. package/dist/core/count-recovery/rebase-path.d.ts +9 -0
  75. package/dist/core/count-recovery/rebase-path.js +70 -0
  76. package/dist/core/count-recovery/rename-proof.d.ts +2 -0
  77. package/dist/core/count-recovery/rename-proof.js +102 -0
  78. package/dist/core/count-recovery/row-cases.d.ts +16 -0
  79. package/dist/core/count-recovery/row-cases.js +291 -0
  80. package/dist/core/count-recovery/scalar-guards.d.ts +7 -0
  81. package/dist/core/count-recovery/scalar-guards.js +291 -0
  82. package/dist/core/count-recovery/source-memo.d.ts +12 -0
  83. package/dist/core/count-recovery/source-memo.js +67 -0
  84. package/dist/core/count-select.d.ts +16 -0
  85. package/dist/core/count-select.js +24 -0
  86. package/dist/core/count-support.d.ts +598 -0
  87. package/dist/core/count-support.js +2080 -0
  88. package/dist/core/count-unions.d.ts +2 -0
  89. package/dist/core/count-unions.js +139 -0
  90. package/dist/core/count-witness-flags.d.ts +9 -0
  91. package/dist/core/count-witness-flags.js +37 -0
  92. package/dist/core/count-write-frames.d.ts +12 -0
  93. package/dist/core/count-write-frames.js +206 -0
  94. package/dist/core/counts.d.ts +20 -2
  95. package/dist/core/counts.js +807 -156
  96. package/dist/core/dsl.d.ts +50 -6
  97. package/dist/core/dsl.js +307 -65
  98. package/dist/core/effect-schema.d.ts +90 -0
  99. package/dist/core/effect-schema.js +500 -0
  100. package/dist/core/effect.d.ts +3 -7
  101. package/dist/core/effect.js +10 -65
  102. package/dist/core/exists.d.ts +1 -1
  103. package/dist/core/exists.js +80 -15
  104. package/dist/core/extract-check.d.ts +7 -1
  105. package/dist/core/extract-check.js +161 -19
  106. package/dist/core/extract-go-check.js +24 -4
  107. package/dist/core/extract-go.d.ts +7 -0
  108. package/dist/core/extract-go.js +29 -2
  109. package/dist/core/extract-read.d.ts +31 -9
  110. package/dist/core/extract-read.js +36 -11
  111. package/dist/core/extract-rs.js +58 -14
  112. package/dist/core/extract-shapes.d.ts +1 -0
  113. package/dist/core/extract-shapes.js +190 -27
  114. package/dist/core/extract-standalone.d.ts +3 -0
  115. package/dist/core/extract-standalone.js +265 -0
  116. package/dist/core/extract.d.ts +1 -0
  117. package/dist/core/extract.js +25 -5
  118. package/dist/core/field-laws.d.ts +2 -0
  119. package/dist/core/field-laws.js +100 -0
  120. package/dist/core/finite-frontiers.d.ts +5 -0
  121. package/dist/core/finite-frontiers.js +116 -0
  122. package/dist/core/finite-houdini.d.ts +52 -0
  123. package/dist/core/finite-houdini.js +460 -0
  124. package/dist/core/finite-model.d.ts +13 -0
  125. package/dist/core/finite-model.js +68 -0
  126. package/dist/core/finite-tiny.d.ts +72 -0
  127. package/dist/core/finite-tiny.js +1052 -0
  128. package/dist/core/infer.d.ts +1 -1
  129. package/dist/core/infer.js +32 -9
  130. package/dist/core/laws.d.ts +2 -1
  131. package/dist/core/laws.js +76 -19
  132. package/dist/core/lemma-cuts.d.ts +38 -0
  133. package/dist/core/lemma-cuts.js +365 -0
  134. package/dist/core/machine.d.ts +39 -2
  135. package/dist/core/machine.js +240 -35
  136. package/dist/core/mutate.d.ts +55 -0
  137. package/dist/core/mutate.js +210 -0
  138. package/dist/core/native-domain.d.ts +6 -0
  139. package/dist/core/native-domain.js +114 -0
  140. package/dist/core/native-law.d.ts +3 -0
  141. package/dist/core/native-law.js +174 -0
  142. package/dist/core/quorum-laws.d.ts +5 -0
  143. package/dist/core/quorum-laws.js +239 -0
  144. package/dist/core/relational.js +10 -2
  145. package/dist/core/relevance.d.ts +4 -0
  146. package/dist/core/relevance.js +79 -0
  147. package/dist/core/rs/Cargo.toml +1 -1
  148. package/dist/core/rs/src/main.rs +458 -9
  149. package/dist/core/runtime-wall.d.ts +3 -0
  150. package/dist/core/runtime-wall.js +4 -0
  151. package/dist/core/sample-step.d.ts +16 -0
  152. package/dist/core/sample-step.js +28 -0
  153. package/dist/core/source-check.d.ts +44 -0
  154. package/dist/core/source-check.js +126 -0
  155. package/dist/core/source-diagnostic.d.ts +1 -0
  156. package/dist/core/source-diagnostic.js +34 -0
  157. package/dist/core/support-budget.d.ts +2 -0
  158. package/dist/core/support-budget.js +6 -0
  159. package/dist/core/system.js +2 -0
  160. package/dist/core/wall.d.ts +6 -0
  161. package/dist/core/wall.js +23 -0
  162. package/dist/core/watch.js +4 -0
  163. package/dist/kernel/cdcl.d.ts +4 -0
  164. package/dist/kernel/cdcl.js +20 -5
  165. package/dist/kernel/kernel.d.ts +10 -0
  166. package/dist/kernel/kernel.js +56 -3
  167. package/dist/kernel/model-sequence.d.ts +2 -2
  168. package/dist/kernel/model-sequence.js +4 -3
  169. package/dist/kernel/model-values.d.ts +2 -0
  170. package/dist/kernel/model-values.js +60 -0
  171. package/dist/kernel/prove.d.ts +10 -0
  172. package/dist/kernel/prove.js +56 -8
  173. package/dist/kernel/prover-rows.d.ts +29 -0
  174. package/dist/kernel/prover-rows.js +114 -0
  175. package/dist/lean-kernel/emit.d.ts +39 -2
  176. package/dist/lean-kernel/emit.js +136 -24
  177. package/dist/lean-kernel/lean-terms.d.ts +1 -0
  178. package/dist/lean-kernel/lean-terms.js +13 -5
  179. package/dist/lean-kernel/library.js +4 -0
  180. package/dist/lean-kernel/qalpha.d.ts +7 -0
  181. package/dist/lean-kernel/qalpha.js +40 -0
  182. package/package.json +5 -1
@@ -1,17 +1,41 @@
1
- import { assumed, checkCountedLaws, countedObligations, mcGoal, scope, substC, substE } from "../kernel/kernel.js";
2
- import { brokenOf, clock, counted, fullRate, grow, modelInstances, wallAt, widen, withWall } from "../kernel/prove.js";
1
+ import { assumed, checkCountedLaws, checkMC, countedObligations, mcGoal, scope, substC, substE } from "../kernel/kernel.js";
2
+ import { brokenOf, clock, counted, fullRate, grow, modelInstances, wallAt, widen, withDeadline, withWall } from "../kernel/prove.js";
3
3
  import { REFUTED, cdclStats } from "../kernel/cdcl.js";
4
4
  import { modelSequence } from "../kernel/model-sequence.js";
5
5
  import { inferLaws } from "./infer.js";
6
+ import { carryCandidates, scanPrefixes } from "./carry.js";
7
+ import { relevantGoals, relevantLaws } from "./relevance.js";
8
+ import { countPoolKey, countSignature, grammarPool, ids, polaritySelection, readTuples, refinementSignature, reservationReadClosure, reservationState, reservePool, prepareSupport, smallSelection, sparseReadInstances, sourceContext, coarseContext, selectedCertificate, chosenView, candidateWork, stableState, UnsupportedCountProposal } from "./count-support.js";
9
+ import { fieldLaws } from "./field-laws.js";
10
+ import { quorumLaws } from "./quorum-laws.js";
11
+ import { countCubes, liftedOneKeyCounts } from "./count-cubes.js";
12
+ import { finiteHoudini } from "./finite-houdini.js";
13
+ import { finiteModelChecker } from "./finite-model.js";
14
+ import { countsForReads, proposeCountFacts } from "./count-facts.js";
15
+ import { completeCountLawInstances } from "./count-completion.js";
16
+ import { rangeInstances, rangeViolations } from "./count-ranges.js";
17
+ import { attemptShare, supportBudget } from "./support-budget.js";
18
+ export { attemptShare, supportBudget } from "./support-budget.js";
19
+ import { proposeCountUnions } from "./count-unions.js";
20
+ import { focusedCountRecoveryEnabled, proveFocusedCounts } from "./count-focus-proof.js";
21
+ import { preferMemberInclusions } from "./count-recovery/member-inclusions.js";
22
+ import { independentCountInstances } from "./count-focused.js";
23
+ import { admitMemberWitnesses, instantiateMemberPremises, memberHints, memberPremiseState } from "./count-recovery/member-premises.js";
6
24
  import { smallOf, trueSmall } from "./exists.js";
25
+ import { WallExpired, checkWall, searchWall } from "./wall.js";
7
26
  import { env } from "./solver.js";
27
+ import { proofOrigins, proposeLemmaCuts } from "./lemma-cuts.js";
28
+ import { countedCertificateHyps, transportCountCertificate } from "./count-cert-transport.js";
8
29
  // (GDP_COUNTS_PROF: where a counted search's time goes, by phase, on stderr at the end; `countsDump.on`, set by research's
9
30
  // profiles: each step goal left unknown or with a model past GDP_COUNTS_DUMP_MIN (300) hypotheses, the first GDP_COUNTS_DUMP_N (3))
10
31
  export const cprof = {};
11
32
  export const countsDump = {};
12
33
  const tally = (k, n = 1) => { cprof[k] = (cprof[k] ?? 0) + n; };
13
34
  const ptime = (k, f) => { const t = performance.now(); try {
14
- return f();
35
+ checkWall(k);
36
+ const out = f();
37
+ checkWall(k);
38
+ return out;
15
39
  }
16
40
  finally {
17
41
  cprof[k] = (cprof[k] ?? 0) + performance.now() - t;
@@ -24,15 +48,19 @@ const v = (name) => ({ op: 'var', name }), k = (value) => ({ op: 'const', value
24
48
  const json = (t) => JSON.stringify(t);
25
49
  const one = k(1), zero = k(0);
26
50
  // Every term t with `get(map, t)` in t0.
27
- function reads(t0, map, out = new Map()) {
51
+ function reads(t0, map, out = new Map(), more) {
28
52
  const go = (x) => {
53
+ if (more && !more())
54
+ return false;
29
55
  if (!x || typeof x !== 'object')
30
- return;
56
+ return true;
31
57
  const o = x;
32
58
  if (o.op === 'get' && map(o.map))
33
59
  out.set(json([o.map, o.key]), [o.map, o.key]);
34
60
  for (const y of Object.values(o))
35
- go(y);
61
+ if (!go(y))
62
+ return false;
63
+ return true;
36
64
  };
37
65
  go(t0);
38
66
  return out;
@@ -41,6 +69,7 @@ const mentions = (t, name) => json(t).includes(`"name":${json(name)}`);
41
69
  // Whether some object within t0 meets p (a condition nested in a term's `if` too).
42
70
  const some = (t0, p) => !!t0 && typeof t0 === 'object' && (p(t0) || Object.values(t0).some(y => some(y, p)));
43
71
  const atoms = (c) => (c.op === 'and' || c.op === 'or' ? c.xs.flatMap(atoms) : c.op === 'not' ? atoms(c.x) : [c]);
72
+ const quorumCandidates = new WeakSet();
44
73
  // --- candidates from the guard's shape -----------------------------------------------------------------------------------
45
74
  export function guardLaws(m) {
46
75
  const counts = {}, laws = [];
@@ -73,6 +102,14 @@ export function guardLaws(m) {
73
102
  }
74
103
  }
75
104
  }
105
+ // Lift row-majority bodies beside the stored-set loop. Their laws are admitted
106
+ // after the old candidate families; merely recognizing a shape trusts nothing.
107
+ const lifted = quorumLaws(m);
108
+ Object.assign(counts, lifted.counts);
109
+ for (const law of lifted.laws) {
110
+ laws.push(law);
111
+ quorumCandidates.add(law);
112
+ }
76
113
  for (const [mp, w] of Object.entries(m.step.maps ?? {})) {
77
114
  // (the written key: a request's value t, or two, t and u, composed N·t + u (a relation's cell): a count of two
78
115
  // parameters, read at the law's N·a + b with b < N)
@@ -197,91 +234,145 @@ export function guardLaws(m) {
197
234
  // The count cells the goal reads (each before the step with its post name's twin), instances over pairs of them with one
198
235
  // bound (a count that doesn't drop, +1 and −1; two that meet, +1, +1 and −1), each with a fresh witness; and the laws and
199
236
  // quantified flags at the witnesses (returned, for the goal's law's instances).
200
- export function certFor(goal, decls, wide = false, most = wide ? 24 : 10) {
201
- const byMap = new Map(decls.map(d => [d.map, d])), last = goal.hyps.at(-1);
202
- // (the conclusion's reads first, then those at a constant or the law's own names, then the rest)
203
- const own = (t) => t.op === 'const' || (t.op === 'var' && json(last).includes(`"name":${json(t.name)}`));
204
- const all0 = [...reads(goal.hyps, mp => byMap.has(mp)).values()], inLast = [...reads(last, mp => byMap.has(mp)).keys()];
237
+ export function certFor(goal, decls, wide = false, most = wide ? 24 : 10, more, structured = true) {
238
+ const tick = more ?? (() => true), byMap = new Map(decls.map(d => [d.map, d])), last = goal.hyps.at(-1), lastText = json(last);
239
+ const own = (t) => t.op === 'const' || (t.op === 'var' && lastText.includes(`"name":${json(t.name)}`));
240
+ const all0 = [...reads(goal.hyps, mp => byMap.has(mp), new Map(), more).values()], inLast = [...reads(last, mp => byMap.has(mp), new Map(), more).keys()];
205
241
  const rank = ([mp, t]) => (inLast.includes(json([mp, t])) ? 0 : own(t) ? 1 : 2);
206
242
  const rs = all0.sort((x, y) => rank(x) - rank(y));
207
- // (each read after the step beside its twin before it, when the goal declares both)
208
- for (const [mp, t] of [...rs])
243
+ for (const [mp, t] of [...rs]) {
244
+ if (!tick())
245
+ break;
209
246
  if (mp.endsWith('#') && byMap.has(mp.slice(0, -1)) && !rs.some(([m2, t2]) => m2 === mp.slice(0, -1) && json(t2) === json(t)))
210
247
  rs.push([mp.slice(0, -1), t]);
211
- // (a count whose bound and body don't read its key is one number at every key: read once, at its first-ranked key)
248
+ }
212
249
  const once = new Set(), keyless = (mp) => { const d = byMap.get(mp); return !mentions([d.below, d.body], d.j); };
213
250
  const rs1 = rs.filter(([mp]) => !keyless(mp) || (!once.has(mp) && !!once.add(mp)));
214
- const named = rs1.map(([mp, t], i) => [`r$${i}`, mp, t]);
215
- const bound = (r) => json(byMap.get(r[1]).below);
216
- const insts = [], wits = [];
217
- const add = (terms, unit, below) => { const w = `w$${insts.length}`; wits.push(w); insts.push({ wit: w, below, terms, unit }); };
218
- // first: a count after the step at least each other one (it doesn't drop; what the step adds); then two counts before it
219
- // that meet, the first of the pair one the conclusion or the law's own names read; then the rest at most another
251
+ const named = rs1.map(([mp, t], i) => ['r' + '$' + i, mp, t]), bound = (r) => json(byMap.get(r[1]).below);
252
+ const insts = [], wits = [], cap = most, initialCap = wide ? Math.min(10, cap) : cap;
253
+ const add = (terms, unit, below) => { const w = 'w' + '$' + insts.length; wits.push(w); insts.push({ wit: w, below, terms, unit }); };
220
254
  const post = (r) => r[1].endsWith('#'), ranked = (r) => rank([r[1], r[2]]) <= 1;
221
- for (const c of named)
222
- if (post(c))
223
- for (const a of named)
224
- if (a !== c && !post(a) && bound(a) === bound(c))
225
- add([[1, a[0]], [-1, c[0]]], 0, byMap.get(c[1]).below);
226
- for (const [i, a] of named.entries())
227
- for (const [j, c] of named.entries())
228
- if (i < j && (ranked(a) || ranked(c)) && bound(a) === bound(c) && !post(a) && !post(c))
229
- add([[1, a[0]], [1, c[0]]], -1, byMap.get(a[1]).below);
230
- for (const [i, a] of named.entries())
231
- for (const [j, c] of named.entries())
232
- if (i < j && !(ranked(a) || ranked(c)) && bound(a) === bound(c) && !post(a) && !post(c))
233
- add([[1, a[0]], [1, c[0]]], -1, byMap.get(a[1]).below);
234
- // (a count after the step, the conclusion's, at least a request's count less another: a set's members all in it but
235
- // those a guard's count of the rest finds, |Q| ≤ missing + votes)
236
- for (const c of named)
237
- if (post(c) && rank([c[1], c[2]]) === 0)
238
- for (const a of named)
239
- for (const d of named)
240
- if (a !== d && !post(a) && !post(d) && keyless(a[1]) && keyless(d[1]) && bound(a) === bound(c) && bound(d) === bound(c))
241
- add([[1, a[0]], [-1, d[0]], [-1, c[0]]], 0, byMap.get(c[1]).below);
242
- // (wide, asked by a model the instances above leave: every count at most each other one of its bound, either way, and
243
- // each positive only where a key is in it; a count read with no partner is then tied to its cells at a witness)
244
- // (`most`: the instances kept, 24 widened; a lazy goal's pool takes many more, as only those a model breaks are asked)
245
- const cap = most;
255
+ // Stop enumeration as soon as the requested prefix is complete. Later entries
256
+ // were sliced away before too; the order and contents of completed prefixes stay exact.
257
+ initial: {
258
+ for (const c of named)
259
+ if (post(c))
260
+ for (const a of named) {
261
+ if ((!!more && insts.length >= initialCap) || !tick())
262
+ break initial;
263
+ if (a !== c && !post(a) && bound(a) === bound(c))
264
+ add([[1, a[0]], [-1, c[0]]], 0, byMap.get(c[1]).below);
265
+ }
266
+ for (const [i, a] of named.entries())
267
+ for (const [j, c] of named.entries()) {
268
+ if ((!!more && insts.length >= initialCap) || !tick())
269
+ break initial;
270
+ if (i < j && (ranked(a) || ranked(c)) && bound(a) === bound(c) && !post(a) && !post(c))
271
+ add([[1, a[0]], [1, c[0]]], -1, byMap.get(a[1]).below);
272
+ }
273
+ for (const [i, a] of named.entries())
274
+ for (const [j, c] of named.entries()) {
275
+ if ((!!more && insts.length >= initialCap) || !tick())
276
+ break initial;
277
+ if (i < j && !(ranked(a) || ranked(c)) && bound(a) === bound(c) && !post(a) && !post(c))
278
+ add([[1, a[0]], [1, c[0]]], -1, byMap.get(a[1]).below);
279
+ }
280
+ for (const c of named)
281
+ if (post(c) && rank([c[1], c[2]]) === 0)
282
+ for (const a of named)
283
+ for (const d of named) {
284
+ if ((!!more && insts.length >= initialCap) || !tick())
285
+ break initial;
286
+ if (a !== d && !post(a) && !post(d) && keyless(a[1]) && keyless(d[1]) && bound(a) === bound(c) && bound(d) === bound(c))
287
+ add([[1, a[0]], [-1, d[0]], [-1, c[0]]], 0, byMap.get(c[1]).below);
288
+ }
289
+ }
246
290
  if (wide) {
247
- insts.splice(10), wits.splice(10);
248
- for (const a of named)
249
- for (const c of named)
291
+ insts.splice(10);
292
+ wits.splice(10);
293
+ pairs: for (const a of named)
294
+ for (const c of named) {
295
+ if ((!!more && insts.length >= cap) || !tick())
296
+ break pairs;
250
297
  if (a !== c && bound(a) === bound(c) && !(post(c) && !post(a)))
251
298
  add([[1, a[0]], [-1, c[0]]], 0, byMap.get(a[1]).below);
252
- for (const a of named)
299
+ }
300
+ for (const a of named) {
301
+ if ((!!more && insts.length >= cap) || !tick())
302
+ break;
253
303
  add([[1, a[0]]], 0, byMap.get(a[1]).below);
254
- // (a lazy pool's further instances: each count at most its bound, and every two of a bound that meet)
304
+ }
255
305
  if (cap > 24) {
256
- for (const a of named)
306
+ for (const a of named) {
307
+ if ((!!more && insts.length >= cap) || !tick())
308
+ break;
257
309
  add([[1, a[0]]], -1, byMap.get(a[1]).below);
310
+ }
258
311
  const had = new Set(insts.map(i => json([i.terms, i.unit])));
259
- for (const [i, a] of named.entries())
260
- for (const [j, c] of named.entries())
312
+ meets: for (const [i, a] of named.entries())
313
+ for (const [j, c] of named.entries()) {
314
+ if ((!!more && insts.length >= cap) || !tick())
315
+ break meets;
261
316
  if (i < j && bound(a) === bound(c) && post(a) === post(c) && !had.has(json([[[1, a[0]], [1, c[0]]], -1])))
262
317
  add([[1, a[0]], [1, c[0]]], -1, byMap.get(a[1]).below);
318
+ }
319
+ }
320
+ // Structured identities supplement the legacy pool; they must not displace
321
+ // its witness prefix at the same cap. Both generators remain available on
322
+ // expansion; every proposal is checked as an ordinary witness certificate.
323
+ // Do not construct a tail that the unchanged cap would immediately discard.
324
+ const cs = structured && insts.length < cap ? countsForReads(decls, named) : undefined;
325
+ if (cs && tick()) {
326
+ const facts = proposeCountFacts(cs, goal, { maxFacts: Math.min(cap, 256), reserved: wits });
327
+ for (const q of facts.insts) {
328
+ if ((!!more && insts.length >= cap) || !tick())
329
+ break;
330
+ if (q.terms.length >= 3)
331
+ add(q.terms, q.unit, q.below);
332
+ }
333
+ const heads = named.filter(r => ranked(r)).sort((a, b) => Number(post(b)) - Number(post(a)));
334
+ const carried = named.filter(r => !post(r) && keyless(r[1]));
335
+ const pairs = heads.flatMap(a => carried.filter(b => b !== a && bound(a) === bound(b)).map(b => [a[0], b[0]]));
336
+ for (const q of proposeCountUnions(cs, pairs, Math.min(cap, 128))) {
337
+ if ((!!more && insts.length >= cap) || !tick())
338
+ break;
339
+ add(q.terms, q.unit, q.below);
340
+ }
263
341
  }
264
342
  }
265
- // (wide: each count picked at the keys the goal reads the maps its body reads at its key and its instances' witnesses:
266
- // at least its body there, at every two of them and at all of them)
267
343
  const picks = [];
344
+ // A counted member can be one component of a tuple/packed key, not only
345
+ // the whole map key. These are candidate naturals, never inverse-function
346
+ // axioms: mcGoal/checkMC still check the count body at every picked key.
347
+ const memberKeys = (pattern, term, key) => {
348
+ if (pattern.op === 'var')
349
+ return pattern.name === key ? [term] : [];
350
+ if (pattern.op !== term.op)
351
+ return [];
352
+ const p = pattern, t = term;
353
+ return ['a', 'b', 'key', 'then', 'else'].flatMap(k => p[k] && t[k] ? memberKeys(p[k], t[k], key) : []);
354
+ };
268
355
  if (wide)
269
356
  for (const r of named) {
270
- const d = byMap.get(r[1]), at = [...reads(d.body, () => true).values()].filter(([, key]) => json(key) === json(v(d.key))).map(([mp]) => mp);
357
+ if (!tick())
358
+ break;
359
+ const d = byMap.get(r[1]), at = [...reads(d.body, () => true, new Map(), more).values()].filter(([, key]) => mentions(key, d.key));
271
360
  if (!at.length)
272
361
  continue;
273
362
  // (the key terms the goal reads those maps at, and the witnesses of the instances that name this count: a member the
274
363
  // counting lemma found is a key too; three of each first, six at most)
275
- const gs = [...new Map([...reads(goal.hyps, mp => at.includes(mp)).values()].map(([, t]) => [json(t), t])).values()].filter(t => !mentions(t, d.key));
364
+ const candidates = [...reads(goal.hyps, mp => at.some(([p]) => p === mp), new Map(), more).values()].flatMap(([mp, t]) => at.filter(([p]) => p === mp).flatMap(([, pattern]) => memberKeys(pattern, t, d.key)));
365
+ const gs = [...new Map(candidates.map(t => [json(t), t])).values()].filter(t => !mentions(t, d.key));
276
366
  const ws = insts.slice(0, cap).filter(i => i.terms.some(([, x]) => x === r[0])).map(i => v(i.wit)), ts0 = [...gs.slice(0, 3), ...ws.slice(0, 3), ...gs.slice(3), ...ws.slice(3)];
277
367
  const ts = [...new Map(ts0.map(t => [json(t), t])).values()].slice(0, 6);
368
+ for (const t of ts)
369
+ picks.push([r[0], [t]]);
278
370
  for (let i = 0; i < ts.length; i++)
279
371
  for (let j = i + 1; j < ts.length; j++)
280
372
  picks.push([r[0], [ts[i], ts[j]]]);
281
373
  if (ts.length > 2)
282
374
  picks.push([r[0], ts]);
283
375
  }
284
- // (loose: a read no instance among the first ten names, which only widening ties to its cells)
285
376
  const loose = named.some(r => !insts.slice(0, 10).some(i => i.terms.some(([, x]) => x === r[0])));
286
377
  return { reads: named, insts: insts.slice(0, cap), wits: wits.slice(0, cap), picks, loose };
287
378
  }
@@ -290,7 +381,8 @@ export function certFor(goal, decls, wide = false, most = wide ? 24 : 10) {
290
381
  // small instances reach; the guards' count comparisons (guardLaws, `guarded`); one key a row; the engine's minimal ∀
291
382
  // cubes of at most two literals (core/infer.ts's `cubes`, read off these small states, within a quarter of the search's
292
383
  // budget `ms`, 15 s at most), its template `shapes` (the caller's laws, or an ∃ law's frame), each guard `u < param` loosened where a caller reads u with no param bound.
293
- export function candidates(src, m, caller, shapes, guarded, ms, until) {
384
+ export function candidates(src, m, caller, shapes, guarded, ms, until, support = new Set()) {
385
+ const source = 'machine' in src ? src.machine : src;
294
386
  const states = ptime('small', () => smallOf(m));
295
387
  // (a law of the state only: one the kernel's scope refuses, reading an input or a count of the request (a guard's
296
388
  // comparison with a second request count), has no value at a state, and is not proposed)
@@ -343,7 +435,9 @@ export function candidates(src, m, caller, shapes, guarded, ms, until) {
343
435
  const w = { ...c, name: name === c.name ? `${c.name} (any ${shown.join(', ')})` : name, holds: { op: 'or', xs: c.holds.xs.map(d => (d.op === 'not' ? { op: 'not', x: { op: 'and', xs: conjs(d.x).filter(keep) } } : d)) } };
344
436
  return trueAll(w) ? w : c;
345
437
  };
346
- const cubes = cubes0.map(loosened);
438
+ const cubes = cubes0.map(loosened), fields = fieldLaws(m, false);
439
+ const lifted = guarded.filter(l => quorumCandidates.has(l)), ordinary = guarded.filter(l => !quorumCandidates.has(l));
440
+ const newFields = fieldLaws(m).slice(fields.length, fields.length + Math.max(0, 32 - lifted.length));
347
441
  if (env.GDP_COUNTS_TRACE)
348
442
  console.error(`counts: small ${states.map(({ sts }) => sts.length).join('/')}; cubes ${cubes.length} in ${Math.round(clock() - t1)} ms: ${cubes.map(l => l.name).join('; ')}`);
349
443
  // (a candidate whose every conjunct a law before it states, its keys named apart by place, is not proposed again: a
@@ -355,13 +449,61 @@ export function candidates(src, m, caller, shapes, guarded, ms, until) {
355
449
  for (const l of caller)
356
450
  for (const q of parts(l))
357
451
  said.add(q);
358
- const out = ptime('filter', () => [...kinds, ...guarded, ...rowLaws, ...cubes].filter(l => { const ps = parts(l); if (ps.every(q => said.has(q)) || !trueAll(l))
452
+ const prefixes = scanPrefixes(m, [...caller, ...kinds, ...guarded, ...rowLaws, ...cubes]);
453
+ const admit = (l) => { const ps = parts(l); if (ps.every(q => said.has(q)) || !trueAll(l))
359
454
  return false; for (const q of ps)
360
- said.add(q); return true; }));
455
+ said.add(q); return true; };
456
+ let out = ptime('filter', () => [...kinds, ...ordinary, ...rowLaws, ...fields, ...prefixes, ...cubes].filter(admit));
457
+ const carried = carryCandidates(m, [...caller, ...kinds, ...guarded, ...rowLaws, ...cubes]);
458
+ out.push(...ptime('filter', () => carried.filter(admit)));
459
+ out.push(...ptime('quorumFilter', () => [...lifted, ...newFields].filter(admit)));
460
+ if (lifted.length) {
461
+ // Counts used only by rejected liftings must not spawn another family.
462
+ const liftedCounts = new Set([...reads([...caller, ...out], mp => !!m.counts?.[mp]).values()].map(([mp]) => mp));
463
+ for (const name of liftedCounts)
464
+ for (const [mp] of reads(m.counts[name].body, () => true).values())
465
+ if (m.counts?.[mp])
466
+ liftedCounts.add(mp);
467
+ if (liftedOneKeyCounts(source, m).some(name => liftedCounts.has(name))) {
468
+ out.push(...ptime('countCubes', () => countCubes(source, m, states, liftedCounts).filter(admit)));
469
+ out = ptime('finiteHoudini', () => finiteHoudini(source, m, caller, out, states, {
470
+ onFinish: row => { if (env.GDP_COUNTS_TRACE)
471
+ console.error(`counts: finite result ${JSON.stringify(row)}`); },
472
+ onDrop: d => { if (env.GDP_COUNTS_TRACE)
473
+ console.error(`counts: finite drop ${d.round} ${d.law.name}`); },
474
+ onRound: row => { if (env.GDP_COUNTS_TRACE)
475
+ console.error(`counts: finite Houdini ${JSON.stringify(row)}`); },
476
+ }));
477
+ }
478
+ }
479
+ // A rejected proposal must not enlarge every later counted goal. Retain only
480
+ // lifted counts read by an admitted law (and their transitive dependencies).
481
+ const proposed = new Set([...reads(lifted, mp => !!m.counts?.[mp]).values()].map(([mp]) => mp));
482
+ const used = new Set([...reads([...caller, ...out], () => true).values()].map(([mp]) => mp));
483
+ for (const name of used)
484
+ if (m.counts?.[name])
485
+ for (const [mp] of reads(m.counts[name].body, () => true).values())
486
+ used.add(mp);
487
+ for (const name of proposed)
488
+ if (!used.has(name))
489
+ delete m.counts[name];
490
+ for (const l of out)
491
+ if (prefixes.includes(l) || carried.includes(l))
492
+ support.add(l);
361
493
  if (env.GDP_COUNTS_TRACE)
362
- console.error(`counts: ${kinds.length + guarded.length + rowLaws.length + cubes.length - out.length} candidates said before or false on the small instances`);
494
+ console.error(`counts: ${kinds.length + guarded.length + rowLaws.length + fields.length + prefixes.length + carried.length + cubes.length - out.length} candidates said before or false on the small instances`);
363
495
  return out;
364
496
  }
497
+ // Recovery proposals must not consume a successful ordinary attempt's allowance.
498
+ // A deferred proposal keeps the latest warmed context, but never extends its deadline.
499
+ export function withDeferredCountRecovery(until, attempt, ready = () => true) {
500
+ let recover;
501
+ const ordinary = attempt(next => { recover = next; });
502
+ if ('proof' in ordinary || ordinary.refuted === true || !recover || !ready() || clock() >= until)
503
+ return ordinary;
504
+ const proof = recover();
505
+ return proof === undefined ? ordinary : { proof };
506
+ }
365
507
  export function cone(m, set, attempt, until, houdini = false) {
366
508
  const kept = new Map(), inCone = (l) => kept.has(l.name), tried = new Map(), times = new Map(), asked = new Set(), slow = new Set();
367
509
  const stopAt = until - (until - clock()) / 3, brief = (stopAt - clock()) / Math.max(1, set.length);
@@ -411,16 +553,53 @@ export function cone(m, set, attempt, until, houdini = false) {
411
553
  while (tier(2) && clock() < stopAt);
412
554
  return kept;
413
555
  }
556
+ // --- the counted search ----------------------------------------------------------------------------------------------
557
+ // Scheduling only. Candidate membership never authorizes an assumption or a result.
558
+ export const activeSupport = (set, support) => set.some(l => support.has(l));
559
+ // Count-specific scheduling needs count or global-state context, not merely a
560
+ // primitive pointwise implication. Otherwise preserve the ordinary family first.
561
+ export function countSupportContext(m, caller, set, support) {
562
+ if (!activeSupport(set, support) || set.some(l => support.has(l) && (reads(l.holds, map => !!m.counts?.[map]).size || !l.forall && some(l.holds, node => node.op === 'var' && typeof node.name === 'string' && Object.hasOwn(m.state, node.name) && !l.some?.includes(node.name)))))
563
+ return { laws: set, support };
564
+ return { laws: set.filter(l => caller.includes(l) || !support.has(l)), support: new Set() };
565
+ }
566
+ export function supportOrder(set, caller, support, forModels = false) {
567
+ if (forModels && !activeSupport(set, support))
568
+ return set;
569
+ if (!activeSupport(set, support))
570
+ return [...set.filter(l => !caller.includes(l)), ...set.filter(l => caller.includes(l))];
571
+ return [...set.filter(l => support.has(l) && !caller.includes(l)), ...set.filter(l => caller.includes(l)), ...set.filter(l => !support.has(l) && !caller.includes(l))];
572
+ }
414
573
  // On the counted clock (kernel/prove.ts's `counted`, the cost model's work at fullRate a millisecond), as the engine's
415
- // search is: what a budget lets it try, and so its verdict, is the same on a slow or shared machine as on a fast one; the
416
- // wall a stop only at twice the budget. The small instances (exists.ts's smallOf) are read before the wall starts: their
417
- // search is bounded by its own count of steps, on neither clock, and took 3.6 to 5.2 s of an 8 s budget's 16 s wall on
418
- // a boat VM (exists.test.ts's two counts), so a shared VM crossed the wall before the search began and left every goal
419
- // unknown (2 runs in 4 on main; 4 in 4 beside three busy loops).
574
+ // search is: counted fuel and ordering are unchanged up to the wall cutoff. The
575
+ // wall is an independent hard ceiling, including sampling and generation. A slow
576
+ // machine may stop earlier on the same counted-work prefix, never get extra time.
577
+ // The ordinary family gets its complete existing path first. Structured
578
+ // witness families are retried only after failure, under the same absolute
579
+ // deadline and counted fuel; no generated family is removed.
580
+ function structuredFallback(until, attempt) {
581
+ const ordinary = attempt(false);
582
+ if (ordinary.proven || clock() >= until)
583
+ return ordinary;
584
+ checkWall('structured fallback');
585
+ countsDump.on?.({ phase: 'structured-family-expansion' });
586
+ return attempt(true);
587
+ }
420
588
  export function searchCounted(m0, caller, ms = 60_000) {
421
- const g = guardLaws(m0), m = { ...m0, counts: { ...m0.counts, ...g.counts } };
422
- ptime('small', () => smallOf(m));
423
- const run = () => withWall(performance.now() + 2 * ms, () => counted(fullRate, () => searchCounted0(m0, g, m, caller, ms), true));
589
+ let m = m0;
590
+ const run = () => withWall(searchWall(ms), () => {
591
+ try {
592
+ const g = ptime('guards', () => guardLaws(m0));
593
+ m = { ...m0, counts: { ...m0.counts, ...g.counts } };
594
+ ptime('small', () => smallOf(m, m0));
595
+ return counted(fullRate, () => searchCounted0(m0, g, m, caller, ms), true);
596
+ }
597
+ catch (e) {
598
+ if (!(e instanceof WallExpired))
599
+ throw e;
600
+ return { proven: false, laws: caller, m, why: e.message };
601
+ }
602
+ });
424
603
  if (!env.GDP_COUNTS_PROF)
425
604
  return run();
426
605
  cdclStats.on = true;
@@ -434,9 +613,208 @@ function searchCounted0(m0, g, m, caller, ms) {
434
613
  return { proven: false, laws: caller, m, why: clock() < until ? 'a law fails on the small instances' : 'time' };
435
614
  const t1 = clock();
436
615
  // (GDP_COUNTS_GIVEN=1, research's: the callers alone, no candidate: whether a set written whole goes through)
437
- let set = env.GDP_COUNTS_GIVEN === '1' ? [...caller] : [...caller, ...candidates(m0, m, caller, caller, g.laws, ms, until)];
616
+ const support = new Set();
617
+ let set = env.GDP_COUNTS_GIVEN === '1' ? [...caller] : [...caller, ...candidates(m0, m, caller, caller, g.laws, ms, until, support)];
618
+ countsDump.on?.({ phase: 'candidates', machine: m, laws: set });
438
619
  if (env.GDP_COUNTS_TRACE)
439
620
  console.error(`counts: candidates at ${Math.round(clock() - t1)} ms: ${set.map(l => l.name).join('; ')}`);
621
+ const context = countSupportContext(m, caller, set, support);
622
+ return structuredFallback(until, structured => {
623
+ const result = admitCountedFamilyOnce(m, caller, context.laws, context.support, until, structured);
624
+ // Preserve full-context fallback before trying extra witness families.
625
+ return result.proven || context.laws.length === set.length || clock() >= until ? result : admitCountedFamilyOnce(m, caller, set, context.support, until, structured);
626
+ });
627
+ }
628
+ // Candidate scheduling only. Every returned family still goes through finish.
629
+ export function admitCountedFamily(m, caller, initial, support, until) {
630
+ return structuredFallback(until, structured => admitCountedFamilyOnce(m, caller, initial, support, until, structured));
631
+ }
632
+ function admitCountedFamilyOnce(m, caller, initial, support, until, structured) {
633
+ const previous = proofOrigins.enabled;
634
+ if (env.GDP_COUNT_LEMMA_CUTS === '1')
635
+ proofOrigins.enabled = true;
636
+ try {
637
+ return admitCountedFamily0(m, caller, initial, support, until, structured);
638
+ }
639
+ finally {
640
+ proofOrigins.enabled = previous;
641
+ }
642
+ }
643
+ function admitCountedFamily0(m, caller, initial, support, until, structured) {
644
+ if (!caller.every(l => initial.includes(l)))
645
+ return { proven: false, laws: initial, m, why: 'missing caller' };
646
+ let set = initial.slice();
647
+ const attempts = countedAttempts(m, caller, support, until, structured), traced = attempts.traced;
648
+ const isCount = (mp) => !!m.counts?.[mp];
649
+ // Prove the proposed set together. A preliminary cone reproved many helpers in
650
+ // several smaller contexts before asking these same induction goals. Houdini
651
+ // drops failed helpers and carries proofs whose instantiated support survives.
652
+ // Every returned set still passes checkCountedLaws, including all caller laws.
653
+ const finish = (ls, proof) => {
654
+ let proposed = proof;
655
+ if (env.GDP_COUNT_LEMMA_CUTS === '1') {
656
+ // This pass performs no search work. Reuse the enclosing wall deadline; outside one,
657
+ // conservatively cap its wall time by the remaining counted allowance. Neither budget is extended.
658
+ const wall = wallAt(), end = Number.isFinite(wall) ? wall : performance.now() + Math.max(0, until - clock());
659
+ for (const { goal, decls } of countedObligations(m, ls, proof.instances)) {
660
+ if (performance.now() >= end)
661
+ break;
662
+ const cert = proof.certs[goal.name];
663
+ if (!cert || cert.lemmas?.length)
664
+ continue;
665
+ const expanded = mcGoal(goal.hyps, decls, cert);
666
+ const shared = expanded && proposeLemmaCuts(expanded, cert.tree, { until: end });
667
+ if (shared)
668
+ proposed = { ...proposed, certs: { ...proposed.certs, [goal.name]: { ...cert, tree: shared.tree, lemmas: shared.lemmas } } };
669
+ }
670
+ }
671
+ if (proposed !== proof && ptime('kernel', () => checkCountedLaws(m, ls, proposed)))
672
+ proof = proposed;
673
+ else if (!ptime('kernel', () => checkCountedLaws(m, ls, proof)))
674
+ return { proven: false, laws: ls, m, why: 'the kernel refused the set' };
675
+ // Output-only observation, after the unchanged checker accepts every obligation.
676
+ countsDump.on?.({ phase: 'closed-family', machine: m, laws: ls, proof, checked: true });
677
+ return { proven: true, laws: ls, m, proof };
678
+ };
679
+ const join = (kept = new Map()) => {
680
+ const keptProof = () => ({ instances: Object.fromEntries([...kept].map(([n, pr]) => [n, pr.instances])), certs: Object.assign({}, ...[...kept.values()].map(pr => pr.certs)) });
681
+ if (caller.every(l => kept.has(l.name)))
682
+ return finish(set.filter(l => kept.has(l.name)), keptProof());
683
+ // Each untried law gets an even share of what remains now, not what
684
+ // remained at round entry. Cheap proofs return their underspend to the pool.
685
+ let carried = new Map();
686
+ attempts.houdini = true;
687
+ for (let round = 0; clock() < until; round++) {
688
+ const { instances, certs } = keptProof();
689
+ const failed = new Set(), proofs = new Map();
690
+ const pending = new Set(set.filter(l => !kept.has(l.name) && !carried.has(l.name)).map(l => l.name));
691
+ // Structural supports first; no-support scheduling is unchanged.
692
+ for (const law of supportOrder(set, caller, support)) {
693
+ checkWall('Houdini round');
694
+ if (clock() > until)
695
+ return { proven: false, laws: set, m, why: 'time' };
696
+ if (kept.has(law.name))
697
+ continue;
698
+ const was = carried.get(law.name);
699
+ const share = attemptShare(until - clock(), pending);
700
+ pending.delete(law.name);
701
+ const structural = support.has(law) && !caller.includes(law);
702
+ const boundedSupport = activeSupport(set, support);
703
+ const allotted = supportBudget(until - clock(), share, boundedSupport && caller.includes(law), structural);
704
+ const supportUntil = Math.min(until, clock() + (boundedSupport ? Math.min(allotted, 5_000) : allotted)), supportWall = performance.now() + 4_800;
705
+ const ask = (pass) => {
706
+ const ms = Math.min(allotted, Math.max(0, (boundedSupport ? supportUntil : until) - clock()));
707
+ return boundedSupport ? withWall(supportWall, () => withDeadline(supportUntil, () => traced(law, set, pass, ms))) : traced(law, set, pass, ms);
708
+ };
709
+ const countFirst = (env.GDP_COUNTS_COUNT_FIRST === '1' || boundedSupport && env.GDP_COUNTS_COUNT_FIRST !== '0') && (reads(law.holds, isCount).size > 0 || boundedSupport && !!law.keys?.length);
710
+ let r = was ? { proof: was } : ask(countFirst ? 1 : 0);
711
+ if (!('proof' in r) && !r.refuted && (countFirst || attempts.counted))
712
+ r = ask(countFirst ? 0 : 1);
713
+ if (!('proof' in r)) {
714
+ failed.add(law.name);
715
+ continue;
716
+ }
717
+ proofs.set(law.name, r.proof);
718
+ instances[law.name] = r.proof.instances;
719
+ Object.assign(certs, r.proof.certs);
720
+ }
721
+ if (env.GDP_COUNTS_TRACE)
722
+ console.error(`counts: round ${round}: ${set.length} laws, ${kept.size} kept, ${carried.size} carried, failed ${[...failed].join('; ').slice(0, 600)}`);
723
+ if (!failed.size)
724
+ return finish(set, { instances, certs });
725
+ const next = set.filter(l => !failed.has(l.name) || caller.includes(l));
726
+ // (only callers fail: drop nothing more, give up)
727
+ if (next.length === set.length)
728
+ return { proven: false, laws: set, m, why: `not proven: ${[...failed].join(', ')}` };
729
+ // (a proof that assumes no law dropped at any key is one over the rest: its goals are the same; the kernel checks all)
730
+ const dropped = set.filter(l => !next.includes(l));
731
+ carried = new Map([...proofs].filter(([, pr]) => dropped.every(d => d.forall && !pr.instances[d.name]?.length)));
732
+ set = next;
733
+ }
734
+ return { proven: false, laws: set, m, why: 'time' };
735
+ };
736
+ const dependencies = (owner, proof, context) => {
737
+ const conservative = () => new Set(context.filter(l => !l.forall || proof.instances[l.name]?.length).map(l => l.name)), used = new Set();
738
+ for (const { goal, decls } of countedObligations(m, context, { [owner.name]: proof.instances }, context.indexOf(owner))) {
739
+ const cert = proof.certs[goal.name];
740
+ if (!cert)
741
+ return conservative();
742
+ const expanded = mcGoal(goal.hyps, decls, cert), refs = expanded && countedCertificateHyps(expanded, cert);
743
+ if (!refs)
744
+ return conservative();
745
+ for (const index of refs)
746
+ if (index < goal.hyps.length)
747
+ used.add(json(goal.hyps[index]));
748
+ }
749
+ return new Set(context.filter(l => assumed([l], proof.instances).some(h => used.has(json(h)))).map(l => l.name));
750
+ };
751
+ const demand = () => {
752
+ const known = new Map();
753
+ attempts.houdini = true;
754
+ while (clock() < until) {
755
+ if (!activeSupport(set, support))
756
+ return join();
757
+ const required = new Set(caller.map(l => l.name)), available = new Set(set.map(l => l.name));
758
+ for (const name of required) {
759
+ const saved = known.get(name);
760
+ if (saved)
761
+ for (const dep of saved.deps)
762
+ if (available.has(dep))
763
+ required.add(dep);
764
+ }
765
+ const law = supportOrder(set, caller, support).find(l => required.has(l.name) && !known.has(l.name));
766
+ if (!law) {
767
+ const kept = set.filter(l => required.has(l.name)), instances = {}, certs = {};
768
+ for (const l of kept) {
769
+ const saved = known.get(l.name);
770
+ instances[l.name] = saved.proof.instances;
771
+ const src = countedObligations(m, saved.context, { [l.name]: saved.proof.instances }, saved.context.indexOf(l)), dst = countedObligations(m, kept, { [l.name]: saved.proof.instances }, kept.indexOf(l));
772
+ for (let i = 0; i < dst.length; i++) {
773
+ const cert = saved.proof.certs[src[i].goal.name];
774
+ if (!cert)
775
+ return join();
776
+ const a = mcGoal(src[i].goal.hyps, src[i].decls, cert), b = mcGoal(dst[i].goal.hyps, dst[i].decls, cert), lifted = a && b && transportCountCertificate(a, b, cert, wallAt());
777
+ if (!lifted)
778
+ return join();
779
+ certs[dst[i].goal.name] = lifted;
780
+ }
781
+ }
782
+ return finish(kept, { instances, certs });
783
+ }
784
+ const remaining = until - clock(), share = remaining / Math.max(1, set.length - known.size), allotted = supportBudget(remaining, share, caller.includes(law), support.has(law) && !caller.includes(law)), stop = Math.min(until, clock() + Math.min(allotted, 5000)), wall = performance.now() + 4800;
785
+ const countFirst = env.GDP_COUNTS_COUNT_FIRST !== '0' && (reads(law.holds, isCount).size > 0 || !!law.keys?.length);
786
+ const ask = (context) => withWall(wall, () => withDeadline(stop, () => {
787
+ const pass = countFirst ? 1 : 0;
788
+ let result = traced(law, context, pass, Math.min(allotted, Math.max(0, stop - clock())));
789
+ if (!('proof' in result) && !result.refuted && (countFirst || attempts.counted) && clock() < stop)
790
+ result = traced(law, context, pass ? 0 : 1, Math.min(allotted, Math.max(0, stop - clock())));
791
+ return result;
792
+ }));
793
+ let context = coarseContext(m, set, [...caller, law], support), result = ask(context);
794
+ if (!('proof' in result) && context.length < set.length && clock() < stop) {
795
+ context = set;
796
+ result = ask(context);
797
+ }
798
+ countsDump.on?.({ phase: 'demand-attempt', law: law.name, context: context.length, required: required.size, known: known.size, outcome: 'proof' in result ? 'proof' : result.stuck });
799
+ if ('proof' in result) {
800
+ known.set(law.name, { proof: result.proof, context: context.slice(), deps: dependencies(law, result.proof, context) });
801
+ continue;
802
+ }
803
+ if (caller.includes(law))
804
+ return join();
805
+ set = set.filter(l => l !== law);
806
+ for (const [name, saved] of known)
807
+ if (saved.deps.has(law.name))
808
+ known.delete(name);
809
+ }
810
+ return { proven: false, laws: set, m, why: 'time' };
811
+ };
812
+ return activeSupport(set, support) ? demand() : join();
813
+ }
814
+ // The production attempt also serves the fixed-family research replay. Candidate
815
+ // generation and scheduling stay outside; inference, selection, reservation and
816
+ // all budget checks have exactly one implementation.
817
+ export function countedAttempts(m, caller, support, until, structured = true) {
440
818
  // (the law's own names and the request's values that key a map: an action's value keys none)
441
819
  const keys0 = [...[...reads([m.step, m.assume ?? null], () => true).values()].map(([, key]) => key), ...Object.values(m.step.maps ?? {}).flatMap(w => ('each' in w ? [] : [w.key]))];
442
820
  const keyed = m.inputs.filter(i => keys0.some(key => mentions(key, i))).map(v);
@@ -455,46 +833,200 @@ function searchCounted0(m0, g, m, caller, ms) {
455
833
  // Cone tiers and Houdini may ask the same law again with more instances. Keep a
456
834
  // bounded set of sessions; each independently resets unless its hypotheses are
457
835
  // still present verbatim. This reuses work, never a verdict from a weaker goal.
458
- const decisions = new Map();
459
- const attempt = (law, ls, pass, ms) => {
836
+ const decisions = new Map(), focusEnabled = focusedCountRecoveryEnabled(m);
837
+ // Scheduling history only, never a cached verdict. A different family must
838
+ // earn its own ordinary attempts before using the finite recovery search.
839
+ const plainFailures = new WeakMap();
840
+ let finite;
841
+ const ordinaryAttempt = (law, ls, pass, ms, attemptEnd, defer) => {
460
842
  // A cached model can return before the no-count optimization below. A helper
461
843
  // without count reads must not suppress the next law's counting-lemma pass.
462
844
  if (!pass)
463
845
  counted = true;
464
846
  const ts = terms(law), id = `${pass} ${law.name}`, cti = models.get(id);
847
+ const supported = ls.some(l => support.has(l)), modelLaws = supportOrder(ls, caller, support, true);
848
+ let memberState;
849
+ const members = () => memberState ??= memberPremiseState([m, ls]);
850
+ // A source predicate may be instantiated at a count witness, but no
851
+ // count-read key may depend on that same witness (checkMC freshness).
852
+ const independent = (before, next, wits = []) => {
853
+ if (!next)
854
+ return undefined;
855
+ const blocked = [...memberState?.witnesses.values() ?? [], ...cti?.wits ?? []];
856
+ return blocked.length ? independentCountInstances(m, modelLaws, before, next, [...blocked, ...wits]) : next;
857
+ };
858
+ // Try ordinary counted reasoning before finite recovery when the plain
859
+ // pass needs counts. Keep the no-count fallback and the existing wide-pool
860
+ // recovery, using only the current attempt's remaining allowance.
861
+ if (focusEnabled && m.inputMaps?.length && !reads(law.holds, isCount).size && (!pass || plainFailures.get(law)?.has(ls))) {
862
+ defer(() => ptime('focused', () => proveFocusedCounts(m, ls, law, {}, Math.min(attemptEnd, clock() + Math.min(ms, 5000)), (g, ds) => certFor(g, ds, true, pool, undefined, structured))));
863
+ }
465
864
  // (the model broken: the attempt starts at the instances it asks for, its last attempt's and the tuples the new laws
466
865
  // break it at, where the rounds of models would lead it again)
467
866
  let seed;
867
+ const refuted = (gg, w, instances) => {
868
+ const completion = (finite ??= finiteModelChecker(m))(ls, law, w, () => clock() >= attemptEnd);
869
+ countsDump.on?.({ phase: 'finite-model', law: law.name, pass, completion });
870
+ if (env.GDP_COUNTS_DUMP_ALL_PASSES === '1')
871
+ countsDump.on?.({ phase: completion.genuine ? 'final-sat' : 'uncertified-model', stuck: completion.genuine || !pass ? 'sat' : 'unknown', law: law.name, pass, machine: m, laws: ls, goal: gg, witness: w, at: instances });
872
+ models.set(id, { gg, w, at: instances, ls: new Set(ls.map(l => l.name)), wits: [...memberState?.witnesses.values() ?? [], ...cti?.wits ?? []] });
873
+ return completion.genuine ? { stuck: 'sat', refuted: true } : { stuck: pass ? 'unknown' : 'sat' };
874
+ };
468
875
  // (not where the attempt may widen: its narrow model is no model of the widened goal)
469
- if (cti && !(houdini && caller.some(l => l.name === law.name) && !widened.has(law.name)) && !ls.some(l => !cti.ls.has(l.name) && reads(l.holds, isCount).size)) {
876
+ if (cti && !(supported && pass) && !(houdini && caller.some(l => l.name === law.name) && !widened.has(law.name)) && !ls.some(l => !cti.ls.has(l.name) && reads(l.holds, isCount).size)) {
470
877
  const at0 = Object.fromEntries(Object.entries(cti.at).filter(([n]) => n.startsWith('?') || ls.some(l => l.name === n)));
471
- if (!(seed = ptime('mbqi', () => modelInstances(m, ls, at0, cti.gg, cti.w))))
472
- return { stuck: 'sat' };
878
+ if (!(seed = ptime('mbqi', () => independent(at0, modelInstances(m, modelLaws, at0, cti.gg, cti.w)))))
879
+ return refuted(cti.gg, cti.w, cti.at);
473
880
  }
474
- const refuted = (gg, w) => { models.set(id, { gg, w, at, ls: new Set(ls.map(l => l.name)) }); return { stuck: 'sat' }; };
475
- let at = seed ?? Object.fromEntries(Object.entries(m.step.flags ?? {}).flatMap(([f, q]) => (q.op === 'all' && !q.keys?.length ? [[`?${f}`, ts]] : [])));
881
+ // Supported obligations seed quantified flags only at demanded source terms.
882
+ // Ordinary MBQI remains the fallback; arbitrary inputs are not initial witnesses.
883
+ let at = seed ?? (supported ? {} : Object.fromEntries(Object.entries(m.step.flags ?? {}).flatMap(([f, q]) => (q.op === 'all' && !q.keys?.length ? [[`?${f}`, ts]] : []))));
476
884
  const obligations = (i) => ptime('encode', () => countedObligations(m, ls, { [law.name]: i }, ls.indexOf(law)));
477
885
  // (`wide`: the count instances widened once, where a model is left that the narrow ones and the laws don't refute, for
478
886
  // a caller's law or where a read is in none of them: the cone's many refuted candidates keep the narrow ones)
887
+ // Source-only proposals share one 64-tuple/4-per-source budget for this attempt.
888
+ // The ordinary MBQI path remains available and is unchanged without support.
889
+ const generation = candidateWork();
890
+ let seedCount = 0;
891
+ let sourceMaps = new Set();
892
+ if (supported) {
893
+ const prepared = prepareSupport(m, ls, law, at, pass, generation);
894
+ at = prepared.at;
895
+ seedCount = prepared.seedCount;
896
+ sourceMaps = prepared.sourceMaps;
897
+ }
479
898
  let wide = false;
480
899
  const isCaller = houdini && caller.some(l => l.name === law.name);
481
900
  // (lazy (CEGAR): the goal carries the counting lemma's instances and picks some model of it broke, of all certFor
482
901
  // proposes: each model read against the rest, as a state, and those it breaks added, until a model breaks none; an
483
902
  // instance by the reads it names, a pick by its read and terms, so the choice outlives the goal's rebuilds)
484
903
  const chosen = new Set();
485
- const build = () => obligations(at).map(({ goal, decls }) => {
486
- const full = pass ? certFor(goal, decls, wide, wide && lazyMode !== '0' ? pool : undefined) : none;
487
- if (!pass || lazyMode === '0' || (lazyMode === 'wide' && !wide))
488
- return { goal, decls, c: full, gg: ptime('encode', () => mcGoal(goal.hyps, decls, full)), pool: undefined };
904
+ const selections = new Map();
905
+ const poolCache = new Map();
906
+ const memberSources = new Map();
907
+ // Demand-driven ranges (Fable b89dd77a / Lane B): retain a goal's demand
908
+ // across rebuilds, without crowding out ordinary member inclusions.
909
+ // Every proposed range remains an ordinary kernel-checked count instance.
910
+ const rangeWanted = new Map();
911
+ const withRanges = (goal, decls, c, all) => {
912
+ const wanted = rangeWanted.get(goal.name);
913
+ if (!pass || !wanted?.size)
914
+ return c;
915
+ const taken = new Set([...all.map(r => r[0]), ...c.insts.map(i => i.wit), ...m.params, ...m.inputs, ...Object.keys(m.state)]);
916
+ const ranges = rangeInstances(decls, all.filter(r => wanted.has(r[0])), taken, c.insts);
917
+ if (!ranges.length)
918
+ return c;
919
+ const have = new Set(c.reads.map(r => r[0])), named = new Set(ranges.map(i => i.terms[0][1]));
920
+ const reads = [...c.reads, ...all.filter(r => !have.has(r[0]) && named.has(r[0]))];
921
+ return { ...c, reads, insts: [...c.insts, ...ranges], ...(c.wits ? { wits: [...c.wits, ...ranges.map(i => i.wit)] } : {}) };
922
+ };
923
+ // (a model that puts a read's count above its bound: those reads' ranges wanted from now on; whether any is new)
924
+ const wantRanges = (goal, decls, all, w) => {
925
+ let set = rangeWanted.get(goal.name);
926
+ if (!set)
927
+ rangeWanted.set(goal.name, (set = new Set()));
928
+ let grew = false;
929
+ for (const read of rangeViolations(decls, all, w))
930
+ if (!set.has(read[0])) {
931
+ set.add(read[0]);
932
+ grew = true;
933
+ }
934
+ return grew;
935
+ };
936
+ const rawBuild = () => obligations(at).map(({ goal, decls }) => {
937
+ if (pass && supported && lazyMode === 'wide') {
938
+ if (generation.state.deadline || performance.now() >= wallAt())
939
+ throw new UnsupportedCountProposal('reservation deadline');
940
+ let selection = selections.get(goal.name);
941
+ const reservation = selection && reservationReadClosure(goal, decls, selection.previous, selection.decls, selection.chosen, [...m.params, ...m.inputs, ...Object.keys(m.state)]);
942
+ // Primitive PRE instances cannot introduce another count read. Reuse
943
+ // the proposal pool while only those instances grow; retained picks
944
+ // are still reified against this goal, and additional picks may wait
945
+ // for failure-driven widening. This caches proposals, never a proof.
946
+ const key = countPoolKey(goal, decls);
947
+ const cached = poolCache.get(goal.name);
948
+ const pool0 = cached?.key === key ? cached.value : grammarPool(goal, decls, pool, generation, structured, m);
949
+ if (cached?.key !== key)
950
+ poolCache.set(goal.name, { key, value: pool0 });
951
+ if (!selection) {
952
+ const ordinary = readTuples(goal.hyps.at(-1), generation.tick).some(([mp]) => mp.endsWith('#') && decls.some(d => d.map === mp))
953
+ ? polaritySelection(goal, decls, pool0, generation, sourceMaps).pick
954
+ : smallSelection(goal, decls, pool0.full, readTuples(law.holds, generation.tick).map(([, key]) => key), none, generation);
955
+ const pick = preferMemberInclusions(m, decls, pool0.full, ordinary, 10, generation.tick);
956
+ selection = { chosen: new Set(ids(pick)), cap: Math.min(10, pick.insts.length + 2), previous: pick, decls, reserve: reservationState(goal, [m, ls, goal], pool), stable: stableState([m, ls, goal]) };
957
+ selections.set(goal.name, selection);
958
+ }
959
+ const full = reservePool(goal, decls, pool0, selection.previous, selection.decls, selection.chosen, selection.reserve, pool, reservation).full;
960
+ const keys = ids(full), lazyRoom = selection.chosen.size < selection.cap;
961
+ const view = chosenView(full, selection.chosen, selection.cap);
962
+ const c = withRanges(goal, decls, selectedCertificate(goal, decls, view, selection.stable, lazyRoom), full.reads);
963
+ const gg = mcGoal(goal.hyps, decls, c), fg = lazyRoom ? mcGoal(goal.hyps, decls, full) : undefined;
964
+ selection.previous = full;
965
+ selection.decls = decls;
966
+ memberSources.set(goal.name, memberHints(m, decls, c, generation.tick));
967
+ return { goal, decls, c, gg, all: full.reads, pool: fg ? { fg, keys, wits: [...full.picks.map(() => undefined), ...full.insts.map(i => i.wit)], chosen: selection.chosen, cap: selection.cap } : undefined };
968
+ }
969
+ let full = pass ? certFor(goal, decls, wide, wide && lazyMode !== '0' ? pool : undefined, undefined, structured) : none;
970
+ if (pass && m.inputMaps?.length && lazyMode !== '0') {
971
+ const proposed = admitMemberWitnesses(m, decls, full, members(), wide ? pool : 10, generation.tick);
972
+ full = proposed.cert;
973
+ memberSources.set(goal.name, proposed.hints);
974
+ }
975
+ if (!pass || lazyMode === '0' || (lazyMode === 'wide' && !wide)) {
976
+ const c0 = withRanges(goal, decls, full, full.reads);
977
+ return { goal, decls, c: c0, gg: ptime('encode', () => mcGoal(goal.hyps, decls, c0)), all: full.reads, pool: undefined };
978
+ }
489
979
  const rd = new Map(full.reads.map(r => [r[0], json([r[1], r[2]])]));
490
980
  const keys = [...full.picks.map(q => `p${json([rd.get(q[0]), q[1]])}`), ...full.insts.map(i => `i${json([i.terms.map(([z, x]) => [z, rd.get(x)]), i.unit, i.below])}`)];
491
- if (lazyMode === 'wide')
492
- for (const q of keys.slice(full.picks.length, full.picks.length + 10))
493
- chosen.add(q);
494
- const c = { ...full, picks: full.picks.filter((_, j) => chosen.has(keys[j])), insts: full.insts.filter((_, j) => chosen.has(keys[j + full.picks.length])) };
981
+ if (lazyMode === 'wide') {
982
+ const prefix = { ...full, picks: [], insts: full.insts.slice(0, 10) };
983
+ const initial = memberSources.get(goal.name)?.length ? prefix : preferMemberInclusions(m, decls, full, prefix, 10, generation.tick);
984
+ for (const inst of initial.insts)
985
+ chosen.add(keys[full.picks.length + full.insts.indexOf(inst)]);
986
+ }
987
+ const c = withRanges(goal, decls, { ...full, picks: full.picks.filter((_, j) => chosen.has(keys[j])), insts: full.insts.filter((_, j) => chosen.has(keys[j + full.picks.length])) }, full.reads);
495
988
  const fg = ptime('encode', () => mcGoal(goal.hyps, decls, full));
496
- return { goal, decls, c, gg: ptime('encode', () => mcGoal(goal.hyps, decls, c)), pool: fg && keys.length ? { fg, keys, wits: [...full.picks.map(() => undefined), ...full.insts.map(i => i.wit)] } : undefined };
989
+ return { goal, decls, c, gg: ptime('encode', () => mcGoal(goal.hyps, decls, c)), all: full.reads, pool: fg && keys.length ? { fg, keys, wits: [...full.picks.map(() => undefined), ...full.insts.map(i => i.wit)] } : undefined };
497
990
  });
991
+ let lastSignature = '';
992
+ const build = () => {
993
+ let built = rawBuild();
994
+ if (pass)
995
+ while (seedCount < 64 && clock() < attemptEnd) {
996
+ const step = built.at(-1), hints = step && memberSources.get(step.goal.name);
997
+ if (!step || !hints?.length)
998
+ break;
999
+ // Seed declaration-backed member flags first. Scalar law tuples stay
1000
+ // model-driven rather than crowding the initial goal with field bridges.
1001
+ const seeded = instantiateMemberPremises(m, [], at, step.decls, hints, members(), 64 - seedCount, generation.tick);
1002
+ if (!seeded.added.length)
1003
+ break;
1004
+ at = seeded.at;
1005
+ seedCount += seeded.added.length;
1006
+ countsDump.on?.({ phase: 'member-premises', law: law.name, goal: step.goal.name, pass, added: seeded.added });
1007
+ built = rawBuild();
1008
+ }
1009
+ if (pass && supported)
1010
+ while (seedCount < 64 && clock() < attemptEnd) {
1011
+ const step = built.at(-1);
1012
+ if (!step?.gg)
1013
+ break;
1014
+ const signature = refinementSignature(step.gg, step.c);
1015
+ if (signature === lastSignature)
1016
+ break;
1017
+ lastSignature = signature;
1018
+ const seeds = sparseReadInstances(m, ls.filter(l => l === law || !reads(l.holds, isCount).size), law, at, step.gg, step.c, 64 - seedCount, step.goal.hyps.at(-1), step.decls, sourceMaps, step.goal.hyps.slice(0, -1), generation);
1019
+ if (!seeds.added.length)
1020
+ break;
1021
+ const previous = countSignature(step.c);
1022
+ at = seeds.at;
1023
+ seedCount += seeds.added.length;
1024
+ built = rawBuild();
1025
+ if (countSignature(built.at(-1).c) !== previous && !seeds.summary.foundationBarrier)
1026
+ break;
1027
+ }
1028
+ return built;
1029
+ };
498
1030
  // (the pool's hypotheses a model breaks, chosen; whether there were any)
499
1031
  // (`strict`, where nothing else is broken or asked: the cells it leaves out at their start alone, as a model whose
500
1032
  // completion meets an instance may still meet it only at a witness some law then breaks)
@@ -503,7 +1035,7 @@ function searchCounted0(m0, g, m, caller, ms) {
503
1035
  return false;
504
1036
  // (broken where no completion of the model meets it: the cells it leaves out at their start, at 1, or one map's
505
1037
  // flipped from either, and an instance's witness at each value below 16)
506
- const { fg, keys, wits } = b.pool, base = fg.hyps.length - keys.length, ids = keys.flatMap((q, j) => (chosen.has(q) ? [] : [base + j])), judge = brokenOf(fg);
1038
+ const { fg, keys, wits } = b.pool, active = b.pool.chosen ?? chosen, base = fg.hyps.length - keys.length, ids = keys.flatMap((q, j) => (active.has(q) ? [] : [base + j])), judge = brokenOf(fg);
507
1039
  let bad = ids.length ? judge(w, ids) : [];
508
1040
  const mps = [...new Set(bad.flatMap(i => [...reads(fg.hyps[i], () => true).values()].map(([mp]) => mp)))], one1 = Object.fromEntries(mps.map(mp => [mp, 1]));
509
1041
  for (const d of strict ? [undefined] : [undefined, one1, ...mps.map(mp => ({ [mp]: 1 })), ...mps.map(mp => ({ ...one1, [mp]: 0 }))])
@@ -517,21 +1049,54 @@ function searchCounted0(m0, g, m, caller, ms) {
517
1049
  const still = new Set(judge(w2, bad, false, d));
518
1050
  bad = bad.filter(i => still.has(i));
519
1051
  }
1052
+ if (b.pool.cap !== undefined) {
1053
+ const seen = new Set();
1054
+ bad = bad.filter(i => { const key = keys[i - base]; if (seen.has(key))
1055
+ return false; seen.add(key); return true; }).slice(0, Math.max(0, b.pool.cap - active.size));
1056
+ }
520
1057
  for (const i of bad)
521
- chosen.add(keys[i - base]);
1058
+ active.add(keys[i - base]);
522
1059
  tally('#lazy', bad.length);
523
1060
  return bad.length > 0;
524
1061
  });
1062
+ // Complete only assumptions about count maps the requested law reads.
1063
+ // Unrelated count laws keep their ordinary demand-driven instantiation.
1064
+ const completionMaps = new Set([...reads(law.holds, isCount).values()].map(([map]) => map));
1065
+ let countCompleted = false;
1066
+ const completeCounts = () => {
1067
+ if (!pass || countCompleted || !completionMaps.size)
1068
+ return false;
1069
+ countCompleted = true;
1070
+ const completion = completeCountLawInstances(modelLaws, at, ts, l => reads(l.holds, map => completionMaps.has(map)).size > 0, generation.tick);
1071
+ if (!completion.added.length)
1072
+ return false;
1073
+ at = completion.at;
1074
+ tally('#count-completion', completion.added.length);
1075
+ countsDump.on?.({ law: law.name, pass, phase: 'count-completion', added: completion.added });
1076
+ return true;
1077
+ };
1078
+ // A single-key clause mixing field and count reads can need count premises now.
1079
+ // Concrete goals and isolated or multi-key count targets stay sparse-first:
1080
+ // speculative self-instances can crowd out an already easy proof.
1081
+ if (pass && law.forall && !law.keys?.length && completionMaps.size &&
1082
+ reads(law.holds, map => !isCount(map)).size && [...completionMaps].every(map => !m.counts[map].lo) &&
1083
+ modelLaws.some(other => other.name !== law.name && reads(other.holds, map => completionMaps.has(map)).size))
1084
+ completeCounts();
1085
+ // Stuck-model paths retain the same bounded completion and attempt allowance.
525
1086
  let built = build();
1087
+ const observe = (b, phase, witness) => {
1088
+ if (countsDump.on)
1089
+ countsDump.on({ law: law.name, goal: b.goal.name, pass, phase, generation: { ...generation.state }, machine: m, laws: ls, rawGoal: b.goal, decls: b.decls, instances: at, certificateRequest: b.c, hyps: b.gg?.hyps, witness, seedCount });
1090
+ };
526
1091
  let decideStep = decisions.get(id);
527
1092
  if (!decideStep) {
528
1093
  if (decisions.size >= 64)
529
1094
  decisions.delete(decisions.keys().next().value);
530
1095
  decisions.set(id, (decideStep = modelSequence()));
531
1096
  }
532
- const t0 = clock(), more = () => clock() - t0 <= Math.max(ms, 1_000);
1097
+ const more = () => clock() < attemptEnd;
533
1098
  // The step goal decided first by the CDCL search for a model (its phases the simplex's point: a model is met where the
534
- // tree search would split on), within 2·ms (5 s at most):
1099
+ // tree search would split on), within the attempt's remaining allowance:
535
1100
  // - refuted: the law's instances cut to those its core reads, and the core's hypotheses grown on their own first,
536
1101
  // the tree widened to the goal;
537
1102
  // - a model: the instances it asks for (kernel/prove.ts's modelInstances, MBQI: a law or quantified flag broken at a
@@ -539,39 +1104,85 @@ function searchCounted0(m0, g, m, caller, ms) {
539
1104
  // up at once (no tree to grow); the rounds within the attempt's time (a second at least, as the kernel's
540
1105
  // withModels gives its later rounds), past which the goal is unknown;
541
1106
  // - unknown: the goals grown as they are.
1107
+ let preflighted = false;
542
1108
  for (;;) {
1109
+ checkWall('counted refinement');
1110
+ if (!more())
1111
+ return { stuck: 'unknown' };
543
1112
  let part;
1113
+ let direct;
544
1114
  for (;;) {
1115
+ checkWall('counted model loop');
1116
+ if (!more())
1117
+ return { stuck: 'unknown' };
545
1118
  const step = built.at(-1);
546
1119
  if (!step?.gg)
547
1120
  break;
548
- const q = ptime('decide', () => decideStep(step.gg, Math.min(until, clock() + Math.min(2 * ms, 5_000))));
549
- if (!('tree' in q) && q.why === REFUTED && q.core) {
1121
+ if (supported && !preflighted && !step.c.insts.length) {
1122
+ preflighted = true;
1123
+ const directSmall = step.gg.hyps.length <= 64, small = directSmall ? step.gg : relevantGoals(step.gg)[0] ?? step.gg, end = Math.min(attemptEnd, clock() + (directSmall ? ms : ms / 6));
1124
+ // Small already-reified goals use direct tree search before model
1125
+ // construction; neither branch may outlive the original attempt. A subset model
1126
+ // says nothing about the whole goal; only a widened tree is reusable.
1127
+ const tree = ptime('preflight', () => withDeadline(end, () => {
1128
+ const quick = grow(small, new Map(), { nodes: 0, until: end });
1129
+ return 'tree' in quick ? widen(small, step.gg, quick.tree) : undefined;
1130
+ }));
1131
+ observe(step, tree ? 'preflight-proven' : 'preflight-miss');
1132
+ if (tree) {
1133
+ direct = { gg: step.gg, tree };
1134
+ break;
1135
+ }
1136
+ }
1137
+ observe(step, 'query');
1138
+ const q0 = clock(), q = ptime('decide', () => decideStep(step.gg, attemptEnd));
1139
+ observe(step, 'decision:' + ('tree' in q ? 'tree' : q.why === REFUTED ? 'refuted' : q.stuck));
1140
+ if (env.GDP_COUNTS_TRACE?.includes('2'))
1141
+ console.error(`counts: decide ${pass} ${step.goal.name}: ${'tree' in q ? 'proven' : q.stuck} ${step.gg.hyps.length} hyps ${Math.round(clock() - q0)} ms`);
1142
+ if ('tree' in q) {
1143
+ direct = { gg: step.gg, tree: q.tree };
1144
+ break;
1145
+ }
1146
+ if (q.why === REFUTED && q.core) {
550
1147
  const gg = step.gg, last = gg.hyps.length - 1, used = new Set(q.core.map(h => json(gg.hyps[h]))), cut = {};
551
1148
  for (const [name, ts2] of Object.entries(at)) {
552
1149
  const l = ls.find(x => x.name === name), n = l ? 1 + (l.keys?.length ?? 0) : 0;
553
1150
  cut[name] = !l ? ts2 : Array.from({ length: ts2.length / n }, (_, t) => ts2.slice(t * n, t * n + n)).filter(t => used.has(json(assumed([l], { [name]: t })[0]))).flat();
554
1151
  }
555
1152
  at = cut;
556
- built = obligations(at).map(({ goal, decls }, j) => ({ goal, decls, c: built[j].c, gg: mcGoal(goal.hyps, decls, built[j].c), pool: built[j].pool }));
1153
+ // Replay changes the goal, not its proposal pool or complete read set.
1154
+ const beforeReplay = built;
1155
+ built = obligations(at).map(({ goal, decls }, j) => ({ ...built[j], goal, decls, gg: mcGoal(goal.hyps, decls, built[j].c) }));
1156
+ countsDump.on?.({ phase: 'core-replay', law: law.name, pass,
1157
+ readCount: beforeReplay.at(-1).all.length,
1158
+ readsRetained: built.every((b, j) => b.all === beforeReplay[j].all),
1159
+ poolsRetained: built.every((b, j) => b.pool === beforeReplay[j].pool),
1160
+ certificatesRetained: built.every((b, j) => b.c === beforeReplay[j].c) });
557
1161
  part = { gg: built.at(-1).gg, core: { name: gg.name, hyps: (q.core.includes(last) ? q.core : [...q.core, last]).map(h => gg.hyps[h]) } };
558
1162
  break;
559
1163
  }
560
- if ('tree' in q || q.stuck !== 'sat' || !q.witness)
1164
+ if (q.stuck !== 'sat' || !q.witness)
561
1165
  break;
1166
+ observe(step, 'model', q.witness);
562
1167
  if (!more())
563
1168
  return { stuck: 'unknown' };
564
- const asked = ptime('mbqi', () => modelInstances(m, ls, at, step.gg, q.witness)), lz = breaks(step, q.witness) || (!asked && breaks(step, q.witness, true));
1169
+ const asked = ptime('mbqi', () => independent(at, modelInstances(m, modelLaws, at, step.gg, q.witness), step.c.insts.map(i => i.wit))), lz = breaks(step, q.witness) || (!asked && breaks(step, q.witness, true));
565
1170
  tally('#rounds');
566
1171
  tally('#hyps', step.gg.hyps.length);
567
- if (lz && !asked) {
1172
+ // (a model with a count above its bound: that count's range instance from now on, the goal made again)
1173
+ const ranged = pass && wantRanges(step.goal, step.decls, step.all, q.witness);
1174
+ if ((lz || ranged) && !asked) {
568
1175
  built = build();
569
1176
  continue;
570
1177
  }
571
1178
  if (!asked) {
572
- if (countsDump.on && pass && dumped < Number(env.GDP_COUNTS_DUMP_N ?? 3)) {
1179
+ if (completeCounts()) {
1180
+ built = build();
1181
+ continue;
1182
+ }
1183
+ if (countsDump.on && (pass || env.GDP_COUNTS_DUMP_ALL_PASSES === '1') && dumped < Number(env.GDP_COUNTS_DUMP_N ?? 3)) {
573
1184
  dumped++;
574
- countsDump.on({ law: law.name, goal: step.goal.name, ls: ls.map(l => l.name), stuck: 'sat', witness: q.witness, reads: step.c.reads, insts: step.c.insts, hyps: step.gg.hyps });
1185
+ countsDump.on({ law: law.name, goal: step.goal.name, ls: ls.map(l => l.name), stuck: 'sat', witness: q.witness, reads: step.c.reads, insts: step.c.insts, hyps: step.gg.hyps, base: step.goal, decls: step.decls, cert: step.c, at, laws: ls, wide, pass });
575
1186
  }
576
1187
  if (pass && !wide && houdini && 'loose' in step.c && (step.c.loose || isCaller) && more()) {
577
1188
  wide = true;
@@ -579,38 +1190,52 @@ function searchCounted0(m0, g, m, caller, ms) {
579
1190
  built = build();
580
1191
  continue;
581
1192
  }
582
- return refuted(step.gg, q.witness);
1193
+ return refuted(step.gg, q.witness, at);
583
1194
  }
584
1195
  at = asked;
585
1196
  built = build();
586
1197
  }
1198
+ // A wide pool can obscure a short subset proof. Retry only ordinary
1199
+ // witness-bearing certificates with the warmed law instances; the final
1200
+ // checkCountedLaws gate is unchanged; the same bounded finite-input default applies.
1201
+ if (pass && wide && focusEnabled && clock() < attemptEnd) {
1202
+ defer(() => ptime('focused', () => proveFocusedCounts(m, ls, law, at, Math.min(attemptEnd, clock() + Math.min(ms, 5000)), (g, ds) => certFor(g, ds, true, pool, undefined, structured))));
1203
+ }
587
1204
  // (whether a goal reads a count: if none does, pass 1's goals are pass 0's)
588
1205
  if (!pass)
589
1206
  counted = built.some(b => certFor(b.goal, b.decls).reads.length);
590
1207
  const certs = {};
591
1208
  let again = false;
592
- for (const { goal, c, gg } of built) {
1209
+ for (const { goal, decls, c, gg } of built) {
593
1210
  const t0 = clock(), viaPart = gg && part?.gg === gg ? ptime('part', () => {
594
- const o1 = grow(part.core, new Map(), { nodes: 0, until: Math.min(until, clock() + Math.max(ms, 2_000)) }), w = 'tree' in o1 ? widen(part.core, gg, o1.tree) : undefined;
1211
+ const o1 = grow(part.core, new Map(), { nodes: 0, until: attemptEnd }), w = 'tree' in o1 ? widen(part.core, gg, o1.tree) : undefined;
595
1212
  return w ? { tree: w, nodes: 0 } : undefined;
596
1213
  }) : undefined;
597
- const o = viaPart ?? (gg && ptime(`grow${(gg.hyps.length > 300 ? '>300' : '')}`, () => grow(gg, new Map(), { nodes: 0, until: Math.min(until, clock() + ms) })));
1214
+ const o = (direct && direct.gg === gg ? { tree: direct.tree, nodes: 0 } : undefined) ?? viaPart ?? (gg && ptime(`grow${(gg.hyps.length > 300 ? '>300' : '')}`, () => grow(gg, new Map(), { nodes: 0, until: attemptEnd })));
1215
+ if (gg && o && !('tree' in o))
1216
+ observe(built.find(b => b.gg === gg), o.stuck, 'witness' in o ? o.witness : undefined);
598
1217
  if (countsDump.on && gg && o && !('tree' in o) && gg.hyps.length > Number(env.GDP_COUNTS_DUMP_MIN ?? 300) && dumped < Number(env.GDP_COUNTS_DUMP_N ?? 3)) {
599
1218
  dumped++;
600
- countsDump.on({ law: law.name, goal: goal.name, ls: ls.map(l => l.name), stuck: o.stuck, hyps: gg.hyps });
1219
+ countsDump.on({ law: law.name, goal: goal.name, ls: ls.map(l => l.name), stuck: o.stuck, hyps: gg.hyps, base: goal, decls, cert: c, at, laws: ls, wide, pass, ...('witness' in o ? { witness: o.witness } : {}) });
601
1220
  }
602
1221
  if (env.GDP_COUNTS_TRACE?.includes('2'))
603
1222
  console.error(`counts: ${ls.length === 1 ? 'alone' : `with ${ls.length}`} ${pass} ${goal.name}: ${o && 'tree' in o ? 'proven' : gg ? o.stuck : 'no read'} ${gg?.hyps.length ?? 0} hyps (insts ${'insts' in c ? c.insts.length : 0} picks ${'picks' in c ? c.picks.length : 0}${wide ? ' wide' : ''}${built.find(b => b.gg === gg)?.pool ? ` of ${built.find(b => b.gg === gg).pool.keys.length}` : ''}) ${Math.round(clock() - t0)} ms`);
604
1223
  // (the tree search's model of the step goal: the instances it asks for, as the CDCL search's, and the goals again)
605
1224
  if (gg && o && !('tree' in o) && o.stuck === 'sat' && o.witness && gg === built.at(-1).gg && more()) {
606
- const asked = ptime('mbqi', () => modelInstances(m, ls, at, gg, o.witness)), lz = breaks(built.at(-1), o.witness) || (!asked && breaks(built.at(-1), o.witness, true));
607
- if (asked || lz) {
1225
+ const last = built.at(-1), asked = ptime('mbqi', () => independent(at, modelInstances(m, modelLaws, at, gg, o.witness), c.insts.map(i => i.wit))), lz = breaks(last, o.witness) || (!asked && breaks(last, o.witness, true));
1226
+ const ranged = pass && wantRanges(last.goal, last.decls, last.all, o.witness);
1227
+ if (asked || lz || ranged) {
608
1228
  if (asked)
609
1229
  at = asked;
610
1230
  built = build();
611
1231
  again = true;
612
1232
  break;
613
1233
  }
1234
+ if (completeCounts()) {
1235
+ built = build();
1236
+ again = true;
1237
+ break;
1238
+ }
614
1239
  }
615
1240
  if (gg && o && !('tree' in o) && o.stuck === 'sat' && o.witness && gg === built.at(-1).gg && pass && !wide && houdini && 'loose' in c && (c.loose || isCaller) && more()) {
616
1241
  wide = true;
@@ -620,7 +1245,7 @@ function searchCounted0(m0, g, m, caller, ms) {
620
1245
  break;
621
1246
  }
622
1247
  if (gg && o && !('tree' in o) && o.stuck === 'sat' && o.witness && gg === built.at(-1).gg)
623
- return refuted(gg, o.witness);
1248
+ return refuted(gg, o.witness, at);
624
1249
  if (!o || !('tree' in o))
625
1250
  return { stuck: gg ? o.stuck ?? '' : '' };
626
1251
  certs[goal.name] = { reads: c.reads, insts: c.insts, tree: o.tree, ...('picks' in c && c.picks.length ? { picks: c.picks } : {}) };
@@ -629,59 +1254,85 @@ function searchCounted0(m0, g, m, caller, ms) {
629
1254
  return { proof: { instances: at, certs } };
630
1255
  }
631
1256
  };
632
- const traced = (law, ls, pass, ms) => {
633
- const t0 = clock(), w0 = performance.now(), p0 = { ...cprof }, r = attempt(law, ls, pass, ms);
634
- if (env.GDP_COUNTS_TRACE?.includes('3'))
635
- console.error(`counts: try ${law.name.slice(0, 50)} | ls ${ls.length} pass ${pass} ms ${Math.round(ms)} took ${Math.round(clock() - t0)} wall ${Math.round(performance.now() - w0)} [${Object.entries(cprof).filter(([k2, x]) => x - (p0[k2] ?? 0) >= 1).map(([k2, x]) => `${k2} ${Math.round(x - (p0[k2] ?? 0))}`).join(' ')}] -> ${'proof' in r ? 'kept' : r.stuck}`);
636
- return r;
1257
+ const attempt = (law, ls, pass, ms) => {
1258
+ const end = Math.min(until, clock() + ms);
1259
+ const result = withDeadline(end, () => withDeferredCountRecovery(end, defer => ordinaryAttempt(law, ls, pass, ms, end, defer), () => !!pass || !counted));
1260
+ if (!pass) {
1261
+ const failures = plainFailures.get(law) ?? new WeakSet();
1262
+ if (!('proof' in result) && !result.refuted)
1263
+ failures.add(ls);
1264
+ else
1265
+ failures.delete(ls);
1266
+ plainFailures.set(law, failures);
1267
+ }
1268
+ return result;
637
1269
  };
638
- // Prove the proposed set together. A preliminary cone reproved many helpers in
639
- // several smaller contexts before asking these same induction goals. Houdini
640
- // drops failed helpers and carries proofs whose instantiated support survives.
641
- // Every returned set still passes checkCountedLaws, including all caller laws.
642
- const finish = (ls, proof) => (ptime('kernel', () => checkCountedLaws(m, ls, proof)) ? { proven: true, laws: ls, m, proof } : { proven: false, laws: ls, m, why: 'the kernel refused the set' });
643
- const join = (kept = new Map()) => {
644
- const keptProof = () => ({ instances: Object.fromEntries([...kept].map(([n, pr]) => [n, pr.instances])), certs: Object.assign({}, ...[...kept.values()].map(pr => pr.certs)) });
645
- if (caller.every(l => kept.has(l.name)))
646
- return finish(set.filter(l => kept.has(l.name)), keptProof());
647
- // (each law without a carried proof an even share of what is left a round)
648
- let carried = new Map();
649
- houdini = true;
650
- for (let round = 0; clock() < until; round++) {
651
- const { instances, certs } = keptProof();
652
- const failed = new Set(), proofs = new Map(), share = (until - clock()) / Math.max(1, set.filter(l => !kept.has(l.name) && !carried.has(l.name)).length);
653
- // (the callers last, so they meet every support kept so far)
654
- for (const law of [...set.filter(l => !caller.includes(l)), ...set.filter(l => caller.includes(l))]) {
655
- if (clock() > until)
656
- return { proven: false, laws: set, m, why: 'time' };
657
- if (kept.has(law.name))
1270
+ const traced = (law, ls, pass, ms) => {
1271
+ const t0 = clock(), w0 = performance.now(), p0 = { ...cprof };
1272
+ let r;
1273
+ try {
1274
+ const end = Math.min(until, clock() + ms);
1275
+ // Probe only strict subsets, within the existing attempt's allowance. A
1276
+ // subset model is not a verdict: failure always widens to the full set.
1277
+ // Kept certificates must be lifted to that full set's exact row layout.
1278
+ const focused = pass && ls.some(l => support.has(l)) && (reads(law.holds, isCount).size || !caller.includes(law) && !!law.keys?.length) ? sourceContext(m, ls, law, support) : ls;
1279
+ const contexts = [...(focused.length < ls.length ? [{ local: focused, fraction: 1, kind: 'source-context' }] : []), ...(env.GDP_COUNTS_RELEVANCE === '1' ? relevantLaws(m, ls, law, support).map(local => ({ local, fraction: 1 / 6, kind: 'relevance' })) : [])];
1280
+ for (const { local, fraction, kind } of contexts) {
1281
+ const slice = Math.max(0, Math.min(ms * fraction, end - clock()));
1282
+ if (!slice)
1283
+ break;
1284
+ let probe;
1285
+ try {
1286
+ probe = withDeadline(clock() + slice, () => attempt(law, local, pass, slice));
1287
+ }
1288
+ catch (error) {
1289
+ if (!(error instanceof UnsupportedCountProposal))
1290
+ throw error;
658
1291
  continue;
659
- const was = carried.get(law.name);
660
- let r = was ? { proof: was } : traced(law, set, 0, share);
661
- if (!('proof' in r) && counted)
662
- r = traced(law, set, 1, share);
663
- if (!('proof' in r)) {
664
- failed.add(law.name);
1292
+ }
1293
+ if (!('proof' in probe))
665
1294
  continue;
1295
+ const localGoals = countedObligations(m, local, { [law.name]: probe.proof.instances }, local.indexOf(law));
1296
+ const wholeGoals = countedObligations(m, ls, { [law.name]: probe.proof.instances }, ls.indexOf(law));
1297
+ const certs = {};
1298
+ let complete = true;
1299
+ for (let i = 0; i < wholeGoals.length; i++) {
1300
+ const part = localGoals[i], whole = wholeGoals[i], c = probe.proof.certs[part.goal.name];
1301
+ if (!c) {
1302
+ complete = false;
1303
+ break;
1304
+ }
1305
+ const pg = mcGoal(part.goal.hyps, part.decls, c), wg = mcGoal(whole.goal.hyps, whole.decls, c);
1306
+ const lifted = pg && wg && withDeadline(end, () => transportCountCertificate(pg, wg, c, wallAt()));
1307
+ if (!lifted) {
1308
+ complete = false;
1309
+ break;
1310
+ }
1311
+ if (!checkMC(whole.goal.hyps, whole.decls, lifted)) {
1312
+ complete = false;
1313
+ break;
1314
+ }
1315
+ certs[whole.goal.name] = lifted;
1316
+ }
1317
+ if (complete) {
1318
+ r = { proof: { instances: probe.proof.instances, certs } };
1319
+ countsDump.on?.({ phase: kind + '-proof', law: law.name, local: local.length, whole: ls.length });
1320
+ return r;
666
1321
  }
667
- proofs.set(law.name, r.proof);
668
- instances[law.name] = r.proof.instances;
669
- Object.assign(certs, r.proof.certs);
670
1322
  }
671
- if (env.GDP_COUNTS_TRACE)
672
- console.error(`counts: round ${round}: ${set.length} laws, ${kept.size} kept, ${carried.size} carried, failed ${[...failed].join('; ').slice(0, 600)}`);
673
- if (!failed.size)
674
- return finish(set, { instances, certs });
675
- const next = set.filter(l => !failed.has(l.name) || caller.includes(l));
676
- // (only callers fail: drop nothing more, give up)
677
- if (next.length === set.length)
678
- return { proven: false, laws: set, m, why: `not proven: ${[...failed].join(', ')}` };
679
- // (a proof that assumes no law dropped at any key is one over the rest: its goals are the same; the kernel checks all)
680
- const dropped = set.filter(l => !next.includes(l));
681
- carried = new Map([...proofs].filter(([, pr]) => dropped.every(d => d.forall && !pr.instances[d.name]?.length)));
682
- set = next;
1323
+ r = attempt(law, ls, pass, Math.max(0, end - clock()));
683
1324
  }
684
- return { proven: false, laws: set, m, why: 'time' };
1325
+ catch (error) {
1326
+ // A local wall expires this attempt, not the whole enclosing search.
1327
+ // Invalid or captured proposals are likewise never assumptions.
1328
+ if (!(error instanceof UnsupportedCountProposal) && !(error instanceof WallExpired))
1329
+ throw error;
1330
+ countsDump.on?.({ law: law.name, pass, phase: 'rejected proposal', error: String(error) });
1331
+ r = { stuck: 'unknown' };
1332
+ }
1333
+ if (env.GDP_COUNTS_TRACE?.includes('3'))
1334
+ console.error(`counts: try ${law.name.slice(0, 50)} | ls ${ls.length} pass ${pass} ms ${Math.round(ms)} took ${Math.round(clock() - t0)} wall ${Math.round(performance.now() - w0)} [${Object.entries(cprof).filter(([k2, x]) => x - (p0[k2] ?? 0) >= 1).map(([k2, x]) => `${k2} ${Math.round(x - (p0[k2] ?? 0))}`).join(' ')}] -> ${'proof' in r ? 'kept' : r.stuck}`);
1335
+ return r;
685
1336
  };
686
- return join();
1337
+ return { traced, get counted() { return counted; }, set houdini(value) { houdini = value; } };
687
1338
  }