gdp-wired 0.47.0 → 0.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/README.md +15 -4
  2. package/dist/core/carry.d.ts +15 -0
  3. package/dist/core/carry.js +651 -0
  4. package/dist/core/cli.d.ts +3 -1
  5. package/dist/core/cli.js +28 -8
  6. package/dist/core/count-cases.d.ts +24 -0
  7. package/dist/core/count-cases.js +320 -0
  8. package/dist/core/count-cert-grow.d.ts +4 -0
  9. package/dist/core/count-cert-grow.js +37 -0
  10. package/dist/core/count-cert-transport.d.ts +3 -0
  11. package/dist/core/count-cert-transport.js +58 -0
  12. package/dist/core/count-completion.d.ts +9 -0
  13. package/dist/core/count-completion.js +27 -0
  14. package/dist/core/count-cubes.d.ts +8 -0
  15. package/dist/core/count-cubes.js +69 -0
  16. package/dist/core/count-demand.d.ts +37 -0
  17. package/dist/core/count-demand.js +361 -0
  18. package/dist/core/count-facts.d.ts +52 -0
  19. package/dist/core/count-facts.js +247 -0
  20. package/dist/core/count-focus-proof.d.ts +8 -0
  21. package/dist/core/count-focus-proof.js +140 -0
  22. package/dist/core/count-focused.d.ts +22 -0
  23. package/dist/core/count-focused.js +676 -0
  24. package/dist/core/count-ranges.d.ts +5 -0
  25. package/dist/core/count-ranges.js +65 -0
  26. package/dist/core/count-recovery/action-guard.d.ts +5 -0
  27. package/dist/core/count-recovery/action-guard.js +51 -0
  28. package/dist/core/count-recovery/boolean-core.d.ts +16 -0
  29. package/dist/core/count-recovery/boolean-core.js +258 -0
  30. package/dist/core/count-recovery/carried-case.d.ts +2 -0
  31. package/dist/core/count-recovery/carried-case.js +24 -0
  32. package/dist/core/count-recovery/conditional-check-cache.d.ts +23 -0
  33. package/dist/core/count-recovery/conditional-check-cache.js +130 -0
  34. package/dist/core/count-recovery/conditional-cuts.d.ts +6 -0
  35. package/dist/core/count-recovery/conditional-cuts.js +318 -0
  36. package/dist/core/count-recovery/conditional-proof.d.ts +19 -0
  37. package/dist/core/count-recovery/conditional-proof.js +306 -0
  38. package/dist/core/count-recovery/derivability-closure.d.ts +14 -0
  39. package/dist/core/count-recovery/derivability-closure.js +533 -0
  40. package/dist/core/count-recovery/empty-count-source.d.ts +2 -0
  41. package/dist/core/count-recovery/empty-count-source.js +40 -0
  42. package/dist/core/count-recovery/field-bound-lemmas.d.ts +23 -0
  43. package/dist/core/count-recovery/field-bound-lemmas.js +640 -0
  44. package/dist/core/count-recovery/field-case.d.ts +5 -0
  45. package/dist/core/count-recovery/field-case.js +89 -0
  46. package/dist/core/count-recovery/field-demand.d.ts +46 -0
  47. package/dist/core/count-recovery/field-demand.js +47 -0
  48. package/dist/core/count-recovery/field-only.d.ts +3 -0
  49. package/dist/core/count-recovery/field-only.js +18 -0
  50. package/dist/core/count-recovery/fold-path.d.ts +6 -0
  51. package/dist/core/count-recovery/fold-path.js +35 -0
  52. package/dist/core/count-recovery/frame-lemmas.d.ts +9 -0
  53. package/dist/core/count-recovery/frame-lemmas.js +120 -0
  54. package/dist/core/count-recovery/guard-cases.d.ts +12 -0
  55. package/dist/core/count-recovery/guard-cases.js +138 -0
  56. package/dist/core/count-recovery/key-closure.d.ts +14 -0
  57. package/dist/core/count-recovery/key-closure.js +62 -0
  58. package/dist/core/count-recovery/leaf-allowance.d.ts +4 -0
  59. package/dist/core/count-recovery/leaf-allowance.js +7 -0
  60. package/dist/core/count-recovery/lift-count-proxies.d.ts +6 -0
  61. package/dist/core/count-recovery/lift-count-proxies.js +175 -0
  62. package/dist/core/count-recovery/live-dependencies.d.ts +6 -0
  63. package/dist/core/count-recovery/live-dependencies.js +76 -0
  64. package/dist/core/count-recovery/member-inclusions.d.ts +11 -0
  65. package/dist/core/count-recovery/member-inclusions.js +168 -0
  66. package/dist/core/count-recovery/member-premises.d.ts +29 -0
  67. package/dist/core/count-recovery/member-premises.js +114 -0
  68. package/dist/core/count-recovery/natural-cases.d.ts +6 -0
  69. package/dist/core/count-recovery/natural-cases.js +59 -0
  70. package/dist/core/count-recovery/ops.d.ts +6 -0
  71. package/dist/core/count-recovery/ops.js +8 -0
  72. package/dist/core/count-recovery/pre-state-source.d.ts +8 -0
  73. package/dist/core/count-recovery/pre-state-source.js +18 -0
  74. package/dist/core/count-recovery/rebase-path.d.ts +9 -0
  75. package/dist/core/count-recovery/rebase-path.js +70 -0
  76. package/dist/core/count-recovery/rename-proof.d.ts +2 -0
  77. package/dist/core/count-recovery/rename-proof.js +102 -0
  78. package/dist/core/count-recovery/row-cases.d.ts +16 -0
  79. package/dist/core/count-recovery/row-cases.js +291 -0
  80. package/dist/core/count-recovery/scalar-guards.d.ts +7 -0
  81. package/dist/core/count-recovery/scalar-guards.js +291 -0
  82. package/dist/core/count-recovery/source-memo.d.ts +12 -0
  83. package/dist/core/count-recovery/source-memo.js +67 -0
  84. package/dist/core/count-select.d.ts +16 -0
  85. package/dist/core/count-select.js +24 -0
  86. package/dist/core/count-support.d.ts +598 -0
  87. package/dist/core/count-support.js +2080 -0
  88. package/dist/core/count-unions.d.ts +2 -0
  89. package/dist/core/count-unions.js +139 -0
  90. package/dist/core/count-witness-flags.d.ts +9 -0
  91. package/dist/core/count-witness-flags.js +37 -0
  92. package/dist/core/count-write-frames.d.ts +12 -0
  93. package/dist/core/count-write-frames.js +206 -0
  94. package/dist/core/counts.d.ts +20 -2
  95. package/dist/core/counts.js +807 -156
  96. package/dist/core/dsl.d.ts +50 -6
  97. package/dist/core/dsl.js +307 -65
  98. package/dist/core/effect.js +8 -1
  99. package/dist/core/exists.d.ts +1 -1
  100. package/dist/core/exists.js +80 -15
  101. package/dist/core/extract-check.d.ts +7 -1
  102. package/dist/core/extract-check.js +130 -13
  103. package/dist/core/extract-read.d.ts +22 -8
  104. package/dist/core/extract-read.js +29 -11
  105. package/dist/core/extract-shapes.js +122 -41
  106. package/dist/core/extract-standalone.js +53 -9
  107. package/dist/core/extract.js +9 -3
  108. package/dist/core/field-laws.d.ts +2 -0
  109. package/dist/core/field-laws.js +100 -0
  110. package/dist/core/finite-frontiers.d.ts +5 -0
  111. package/dist/core/finite-frontiers.js +116 -0
  112. package/dist/core/finite-houdini.d.ts +52 -0
  113. package/dist/core/finite-houdini.js +460 -0
  114. package/dist/core/finite-model.d.ts +13 -0
  115. package/dist/core/finite-model.js +68 -0
  116. package/dist/core/finite-tiny.d.ts +72 -0
  117. package/dist/core/finite-tiny.js +1052 -0
  118. package/dist/core/infer.d.ts +1 -1
  119. package/dist/core/infer.js +32 -9
  120. package/dist/core/laws.d.ts +2 -1
  121. package/dist/core/laws.js +47 -14
  122. package/dist/core/lemma-cuts.d.ts +38 -0
  123. package/dist/core/lemma-cuts.js +365 -0
  124. package/dist/core/machine.d.ts +39 -2
  125. package/dist/core/machine.js +240 -35
  126. package/dist/core/mutate.d.ts +55 -0
  127. package/dist/core/mutate.js +210 -0
  128. package/dist/core/native-domain.d.ts +6 -0
  129. package/dist/core/native-domain.js +114 -0
  130. package/dist/core/native-law.d.ts +3 -0
  131. package/dist/core/native-law.js +174 -0
  132. package/dist/core/quorum-laws.d.ts +5 -0
  133. package/dist/core/quorum-laws.js +239 -0
  134. package/dist/core/relational.js +10 -2
  135. package/dist/core/relevance.d.ts +4 -0
  136. package/dist/core/relevance.js +79 -0
  137. package/dist/core/runtime-wall.d.ts +3 -0
  138. package/dist/core/runtime-wall.js +4 -0
  139. package/dist/core/sample-step.d.ts +16 -0
  140. package/dist/core/sample-step.js +28 -0
  141. package/dist/core/source-check.d.ts +44 -0
  142. package/dist/core/source-check.js +126 -0
  143. package/dist/core/source-diagnostic.d.ts +1 -0
  144. package/dist/core/source-diagnostic.js +34 -0
  145. package/dist/core/support-budget.d.ts +2 -0
  146. package/dist/core/support-budget.js +6 -0
  147. package/dist/core/system.js +2 -0
  148. package/dist/core/wall.d.ts +6 -0
  149. package/dist/core/wall.js +23 -0
  150. package/dist/core/watch.js +4 -0
  151. package/dist/kernel/cdcl.d.ts +4 -0
  152. package/dist/kernel/cdcl.js +20 -5
  153. package/dist/kernel/kernel.d.ts +10 -0
  154. package/dist/kernel/kernel.js +56 -3
  155. package/dist/kernel/model-sequence.d.ts +2 -2
  156. package/dist/kernel/model-sequence.js +4 -3
  157. package/dist/kernel/model-values.d.ts +2 -0
  158. package/dist/kernel/model-values.js +60 -0
  159. package/dist/kernel/prove.d.ts +10 -0
  160. package/dist/kernel/prove.js +56 -8
  161. package/dist/kernel/prover-rows.d.ts +29 -0
  162. package/dist/kernel/prover-rows.js +114 -0
  163. package/dist/lean-kernel/emit.d.ts +39 -2
  164. package/dist/lean-kernel/emit.js +136 -24
  165. package/dist/lean-kernel/lean-terms.d.ts +1 -0
  166. package/dist/lean-kernel/lean-terms.js +13 -5
  167. package/dist/lean-kernel/library.js +4 -0
  168. package/dist/lean-kernel/qalpha.d.ts +7 -0
  169. package/dist/lean-kernel/qalpha.js +40 -0
  170. package/package.json +5 -1
@@ -0,0 +1,533 @@
1
+ // Untrusted model-driven recovery. Scalar facts are prepared once; numeric
2
+ // countermodels select batches of pointwise facts at bounded row leaves. Every
3
+ // cut and the final tree are independently checked, without new axioms.
4
+ import { x } from "../machine.js";
5
+ import { canon, canonFlip, facts, lemmaPath, linear, substC, substE, truth } from "../../kernel/kernel.js";
6
+ import { atPoint, brokenOf, clock, pastWall, usedHyps, wallAt, withDeadline } from "../../kernel/prove.js";
7
+ import { REFUTED } from "../../kernel/cdcl.js";
8
+ import { scale, sub } from "../solver.js";
9
+ import { check, grow, modelSequence, refuteFast, rowsAt, widen } from "./ops.js";
10
+ import { fieldBounds, countBindingsAt } from "./field-bound-lemmas.js";
11
+ import { preStateCountSource } from "./pre-state-source.js";
12
+ import { booleanCore } from "./boolean-core.js";
13
+ import { foldPath } from "./fold-path.js";
14
+ import { piecesAt, walkLive } from "./live-dependencies.js";
15
+ import { liftCountProxies } from "./lift-count-proxies.js";
16
+ import { proveNaturalCases } from "./natural-cases.js";
17
+ import { proveRowCases, rowPairs } from "./row-cases.js";
18
+ import { admitConditionalCut, inlineConditionalCuts } from "./conditional-cuts.js";
19
+ import { markConditionalProof, checkConditionalProof } from "./conditional-proof.js";
20
+ import { countScalarGuards } from "./scalar-guards.js";
21
+ import { proposeWriteCountFrames } from "../count-write-frames.js";
22
+ import { countsForReads } from "../count-facts.js";
23
+ import { memberInclusions } from "./member-inclusions.js";
24
+ import { leafAllowance } from "./leaf-allowance.js";
25
+ import { emptyCountSource } from "./empty-count-source.js";
26
+ import { beginFieldAttempt, endFieldAttempt } from "./field-demand.js";
27
+ const put = (p, lin, holds) => new Map(p).set(canon(lin), { lin, holds });
28
+ const plain = (lin) => !Object.keys(lin).some(k => k.startsWith('⟦'));
29
+ const fast = (g, p) => { const q = refuteFast(rowsAt(g, p), 256); return q?.kind === 'refuted' ? { leaf: q.steps } : undefined; };
30
+ const decide = (lin, path) => path.get(canon(lin))?.holds ?? (path.has(canonFlip(lin)) ? !path.get(canonFlip(lin)).holds : undefined);
31
+ const active = (saved, path) => saved.filter(s => lemmaPath([s.lemma], path) !== path);
32
+ export function deriveCountClosure(m, ds, g, cert, root, until, trace, options = {}) {
33
+ const wanted = new Set();
34
+ walkLive(options.claim, root, (o) => {
35
+ if (o.op === 'var' && cert.reads.some(r => r[0] === o.name))
36
+ wanted.add(o.name);
37
+ if (o.op === 'get')
38
+ for (const r of cert.reads)
39
+ if (r[1] === o.map && JSON.stringify(r[2]) === JSON.stringify(o.key))
40
+ wanted.add(r[0]);
41
+ });
42
+ if (wanted.size < 2 || !cert.insts.some(q => q.unit === 0 && q.terms.length >= 3) || clock() >= until || pastWall())
43
+ return undefined;
44
+ const started = clock(), reserve = Math.min(400, (until - started) / 3), buildEnd = until - reserve;
45
+ const raw = g.hyps.slice(0, -cert.insts.length), ids = new Set(cert.reads.map(r => r[0])), maps = new Set(cert.reads.map(r => r[1])), wits = new Set(cert.insts.map(q => q.wit));
46
+ const saved = [], models = [], pins = [];
47
+ let base = new Map(root);
48
+ let leafEnd;
49
+ const alive = () => clock() < until && !pastWall(), building = () => clock() < (leafEnd ?? buildEnd) && !pastWall();
50
+ const wallEnd = () => Math.min(wallAt(), performance.now() + Math.min(10000, Math.max(0, (leafEnd ?? until) - clock()) * 10));
51
+ const transport = (from, to, t, a, b) => alive() ? withDeadline(Math.min(until, leafEnd ?? until), () => widen(from, to, t, {}, a, b)) : undefined;
52
+ const sourceCache = new WeakMap();
53
+ const source = (path, witness) => {
54
+ let entry = sourceCache.get(path);
55
+ if (!entry) {
56
+ const rows = [];
57
+ for (const c of raw.flatMap(c => piecesAt(c, path))) {
58
+ let skip = false;
59
+ const owners = new Set();
60
+ walkLive(c, path, (o) => { if (o.op === 'get' && maps.has(o.map) || o.op === 'var' && ids.has(o.name))
61
+ skip = true;
62
+ else if (o.op === 'var' && wits.has(o.name))
63
+ owners.add(o.name); });
64
+ if (!skip && owners.size <= 1)
65
+ rows.push({ c, owner: owners.values().next().value });
66
+ }
67
+ entry = { rows, views: new Map() };
68
+ sourceCache.set(path, entry);
69
+ }
70
+ let view = entry.views.get(witness);
71
+ if (!view) {
72
+ view = entry.rows.filter(r => r.owner === undefined || r.owner === witness).map(r => r.c);
73
+ entry.views.set(witness, view);
74
+ }
75
+ return view;
76
+ };
77
+ const accept = (good, part, tree, from, scope, index) => {
78
+ if (!building())
79
+ return false;
80
+ const a = linear(good.a, from), b = linear(good.b, from);
81
+ if (!a || !b)
82
+ return false;
83
+ const cut = sub(a, b);
84
+ if (!plain(cut))
85
+ return false;
86
+ if (truth(good, lemmaPath(saved.map(s => s.lemma), scope)) === true)
87
+ return true;
88
+ const lemma = admitConditionalCut(g, part, tree, from, scope, cut, saved.map(s => s.lemma), wallEnd());
89
+ if (!lemma || !building())
90
+ return false;
91
+ saved.push({ lemma, good, ...(index === undefined ? {} : { index }) });
92
+ trace.push({ stage: 'closure-cut', index, when: lemma.when, cut: lemma.cut });
93
+ return true;
94
+ };
95
+ // Pin only consequences already proved from the original raw hypotheses.
96
+ // Other guards remain explicit conditions of a scalar cut, not assumptions.
97
+ const pin = (atom) => {
98
+ if (decide(atom, base) === true)
99
+ return true;
100
+ if (!plain(atom) || !building())
101
+ return false;
102
+ const noPath = put(base, atom, false), part = { name: g.name, hyps: raw }, tree = fast(part, noPath), no = tree && transport(part, g, tree, noPath, noPath);
103
+ if (!no)
104
+ return false;
105
+ pins.push({ split: atom, no });
106
+ base = put(base, atom, true);
107
+ return true;
108
+ };
109
+ // Phase A, once: plain-cell ceilings with their guard atoms in `when`.
110
+ for (const guarded of fieldBounds(m, ds, cert, { claim: options.claim, path: base })) {
111
+ if (!building())
112
+ break;
113
+ if (guarded.op !== '<=')
114
+ continue;
115
+ const condition = guarded.a.op === 'if' ? guarded.a.c : undefined;
116
+ if (condition && truth(condition, base) === false)
117
+ continue;
118
+ const conditions = condition ? facts(condition, base) : [];
119
+ conditions.forEach(pin);
120
+ let scope = new Map(base);
121
+ for (const atom of conditions)
122
+ scope = put(scope, atom, true);
123
+ if (condition && truth(condition, scope) !== true)
124
+ continue;
125
+ const good = { op: '<=', a: guarded.a.op === 'if' ? guarded.a.then : guarded.a, b: guarded.b }, a = linear(good.a, scope), b = linear(good.b, scope);
126
+ if (!a || !b || !plain(sub(a, b)) || truth(good, lemmaPath(saved.map(s => s.lemma), scope)) === true)
127
+ continue;
128
+ const before = clock(), traceStart = trace.length, noPath = put(scope, sub(a, b), false), small = { name: g.name, hyps: source(scope) }, meter = beginFieldAttempt(guarded, scope, options.fieldDemand, 'closure-scalar');
129
+ let accepted = false;
130
+ try {
131
+ const direct = fast(small, noPath);
132
+ accepted = !!direct && accept(good, small, direct, noPath, scope);
133
+ if (!accepted && options.fieldSource && building()) {
134
+ const claim = { op: 'not', x: good }, prior = preStateCountSource(g, cert, claim, scope), path = lemmaPath(saved.map(s => s.lemma), scope);
135
+ const tree = options.fieldSource(prior.goal, prior.cert, claim, path, Math.min(buildEnd, clock() + 250));
136
+ if (tree)
137
+ accepted = accept(good, prior.goal, tree, path, scope);
138
+ }
139
+ }
140
+ finally {
141
+ endFieldAttempt(meter, accepted);
142
+ }
143
+ trace.push({ stage: 'closure-scalar', plain: good, checked: accepted, ms: clock() - before, ...(!accepted ? { sourceTail: trace.slice(traceStart).slice(-8) } : {}) });
144
+ }
145
+ // Conditional source scopes are data, not arithmetic proof leaves. Minimal
146
+ // equal-row scopes come first; full order scopes cover the remaining cases.
147
+ const pairMap = new Map((options.pairs ?? []).map(pair => [JSON.stringify(pair), pair]));
148
+ for (const read of cert.reads)
149
+ if (wanted.has(read[0]) && read[1].endsWith('#'))
150
+ for (const pair of rowPairs(m, { reads: [read] }, base, options.claim))
151
+ pairMap.set(JSON.stringify(pair), pair);
152
+ const pairs = [...pairMap.values()].slice(0, 2), scopes = [], scopeByKey = new Map();
153
+ const addScope = (path) => { const key = JSON.stringify([...path].map(([id, a]) => [id, a.holds])), old = scopeByKey.get(key); if (old)
154
+ return old; scopeByKey.set(key, path); scopes.push(path); return path; };
155
+ const rowChoices = (path, pair) => {
156
+ const c = { op: '=', a: pair[0], b: pair[1] };
157
+ if (truth(c, path) !== undefined)
158
+ return [path];
159
+ const a = linear(pair[0], path), b = linear(pair[1], path);
160
+ if (!a || !b)
161
+ return [path];
162
+ const f = sub(a, b), back = scale(f, -1);
163
+ return [put(put(path, f, true), back, true), put(put(path, f, true), back, false), put(path, f, false)];
164
+ };
165
+ addScope(base);
166
+ for (const pair of pairs)
167
+ for (const scope of rowChoices(base, pair))
168
+ addScope(scope);
169
+ let complete = [base];
170
+ for (const pair of pairs)
171
+ complete = complete.flatMap(path => rowChoices(path, pair));
172
+ for (const scope of complete)
173
+ addScope(scope);
174
+ const rowScopes = [...scopes];
175
+ const postReads = new Set(cert.reads.filter(r => r[1].endsWith('#')).map(r => r[0]));
176
+ const conditional = (index) => cert.insts[index].terms.some(([, id]) => postReads.has(id));
177
+ const readMap = new Map(cert.reads.map(([id, map]) => [id, map]));
178
+ const frame = (index) => { const q = cert.insts[index]; if (q.terms.length !== 2)
179
+ return false; const [a, b] = q.terms.map(([, id]) => readMap.get(id)); return !!a && !!b && (a.endsWith('#') && a.slice(0, -1) === b || b.endsWith('#') && b.slice(0, -1) === a); };
180
+ const vector = (q) => JSON.stringify([...q.terms].sort((a, b) => a[1].localeCompare(b[1]) || a[0] - b[0]));
181
+ const memberHints = new Map(memberInclusions(m, ds, cert.reads).map(p => [vector({ wit: '', unit: 0, below: p.below, terms: [[1, p.positive], [-1, p.negative]] }), p.guards]));
182
+ const bridges = new Set(proposeWriteCountFrames(m, ds, { reads: cert.reads, insts: [] }, wanted).map(vector));
183
+ // Inclusion is cheap even when an expanded post partition is not. Rank by
184
+ // declarative membership containment only; the actual witness still proves it.
185
+ const predicates = new Map();
186
+ for (const read of cert.reads) {
187
+ const plainRead = [read[0], read[1].endsWith('#') ? read[1].slice(0, -1) : read[1], read[2]], count = countsForReads(ds, [plainRead])?.[0];
188
+ if (!count)
189
+ continue;
190
+ const body = substE(count.body, { vars: { [count.key]: x('closure$member') }, maps: {}, flags: {} });
191
+ if (body.op !== 'if' || body.then.op !== 'const' || body.then.value !== 1 || body.else.op !== 'const' || body.else.value !== 0)
192
+ continue;
193
+ const atoms = new Set(), collect = (c) => { if (c.op === 'and')
194
+ c.xs.forEach(collect);
195
+ else
196
+ atoms.add(JSON.stringify(c)); };
197
+ collect(body.c);
198
+ predicates.set(read[0], atoms);
199
+ }
200
+ const inclusion = (q) => {
201
+ if (q.unit !== 0 || q.terms.length !== 2)
202
+ return false;
203
+ const a = q.terms.find(([z]) => z === 1)?.[1], b = q.terms.find(([z]) => z === -1)?.[1];
204
+ if (!a || !b || postReads.has(a) !== postReads.has(b))
205
+ return false;
206
+ const left = predicates.get(a), right = predicates.get(b);
207
+ return !!left && !!right && [...right].every(atom => left.has(atom));
208
+ };
209
+ const rank = (index) => { const q = cert.insts[index], arity = q.terms.length; return q.unit !== 0 && arity === 1 ? -2 : inclusion(q) ? -1 : arity === 1 && wanted.has(q.terms[0][1]) ? 0 : !conditional(index) && arity === 3 ? 0 : bridges.has(vector(q)) ? 1 : !conditional(index) && arity === 5 ? 2 : frame(index) ? 3 : !conditional(index) ? 4 : arity === 3 ? 5 : arity === 2 ? 6 : 7; };
210
+ const pool = cert.insts.flatMap((q, index) => q.terms.length <= 5 ? [index] : []).sort((a, b) => rank(a) - rank(b));
211
+ const rowNames = new Set();
212
+ for (const pair of pairs)
213
+ walkLive(pair, base, (o) => { if (o.op === 'var' && !m.inputs.includes(o.name))
214
+ rowNames.add(o.name); });
215
+ const sourceRows = new Map(pool.map(index => {
216
+ const names = new Set();
217
+ for (const [, id] of cert.insts[index].terms) {
218
+ const read = cert.reads.find(r => r[0] === id);
219
+ if (read)
220
+ walkLive(read[2], base, (o) => { if (o.op === 'var' && rowNames.has(o.name))
221
+ names.add(o.name); });
222
+ }
223
+ return [index, names];
224
+ }));
225
+ const scalarAtoms = new Set(), scopeCache = new Map();
226
+ const scopesFor = (index) => {
227
+ const old = scopeCache.get(index);
228
+ if (old)
229
+ return old;
230
+ const rows = rowScopes.filter(scope => [...scope].every(([id, atom]) => base.has(id) || Object.keys(atom.lin).every(name => !rowNames.has(name) || sourceRows.get(index).has(name))));
231
+ const bridge = bridges.has(vector(cert.insts[index])), guarded = [], equalRows = rows.filter(scope => scope !== base && scope.size <= base.size + 2 && pairs.some(([a, b]) => truth({ op: '=', a, b }, scope) === true));
232
+ const distinctRows = bridge ? rows.filter(scope => { const states = pairs.map(([a, b]) => truth({ op: '=', a, b }, scope)); return states.includes(true) && states.includes(false); }) : [];
233
+ const origins = conditional(index) ? [...distinctRows, ...equalRows, base] : [base];
234
+ const preferred = memberHints.get(vector(cert.insts[index]));
235
+ const proposed = [...(preferred ? [preferred] : []), ...countScalarGuards(m, ds, cert.reads, cert.insts[index], base, { name: g.name, hyps: source(base, cert.insts[index].wit) })].slice(0, 8), equal = proposed.filter(guards => guards.every(c => c.op === '='));
236
+ const choices = bridge && equal.length ? equal.sort((a, b) => b.length - a.length) : proposed;
237
+ for (const guards of choices)
238
+ for (const origin of origins) {
239
+ let scope = new Map(origin), valid = true;
240
+ const aliases = {};
241
+ for (const [a, b] of pairs)
242
+ if (a.op === 'var' && truth({ op: '=', a, b }, origin) === true)
243
+ aliases[a.name] = b;
244
+ for (const original of guards) {
245
+ const condition = substC(original, { vars: aliases, maps: {}, flags: {} });
246
+ if (truth(condition, scope) === false) {
247
+ valid = false;
248
+ break;
249
+ }
250
+ for (const atom of facts(condition, scope)) {
251
+ if (!plain(atom)) {
252
+ valid = false;
253
+ break;
254
+ }
255
+ scalarAtoms.add(canon(atom));
256
+ scalarAtoms.add(canonFlip(atom));
257
+ scope = put(scope, atom, true);
258
+ }
259
+ if (!valid)
260
+ break;
261
+ }
262
+ if (valid)
263
+ guarded.push(addScope(scope));
264
+ }
265
+ const unique = new Set(), out = (bridge ? [base, ...rows, ...guarded] : [base, ...guarded, ...rows]).filter(scope => { const key = JSON.stringify([...scope].map(([id, a]) => [id, a.holds])); if (unique.has(key))
266
+ return false; unique.add(key); return true; });
267
+ scopeCache.set(index, out);
268
+ return out;
269
+ };
270
+ let rounds = 0, fixedPoint = false;
271
+ for (const index of pool)
272
+ scopesFor(index);
273
+ const excludedAt = new Map(), attempted = new Map();
274
+ const countBodies = new Map();
275
+ const validPoint = (part, path, point) => {
276
+ const model = { ...point };
277
+ walkLive(part.hyps, path, (o) => { if (o.op === 'var' && !Object.hasOwn(model, o.name))
278
+ model[o.name] = 0; });
279
+ for (const atom of path.values())
280
+ for (const name of Object.keys(atom.lin))
281
+ if (name !== '1' && !Object.hasOwn(model, name))
282
+ model[name] = 0;
283
+ if (!Object.values(model).every(Number.isSafeInteger) || brokenOf(part)(model).length)
284
+ return undefined;
285
+ return [...path.values()].every(a => { const n = Object.entries(a.lin).reduce((s, [k, z]) => s + z * (k === '1' ? 1 : model[k]), 0); return Number.isFinite(n) && (a.holds ? n <= 0 : n > 0); }) ? model : undefined;
286
+ };
287
+ const attempt = (index, scope, end) => {
288
+ if (!building())
289
+ return 'unknown';
290
+ scope = addScope(scope);
291
+ const version = saved.length, key = `${scopes.indexOf(scope)}:${index}`, had = attempted.get(key);
292
+ if (had?.version === version)
293
+ return had.outcome;
294
+ const inst = cert.insts[index], h = g.hyps[raw.length + index];
295
+ if (h?.op !== 'or' || h.xs[0]?.op !== '<=')
296
+ return 'unknown';
297
+ const good = { op: '<=', a: h.xs[0].a, b: h.xs[0].b }, available = active(saved, scope), path = scope, before = clock();
298
+ const meter = beginFieldAttempt(good, scope, options.fieldDemand, 'closure-count');
299
+ let emitted = false;
300
+ const aliases = {};
301
+ for (const [a, b] of pairs)
302
+ if (a.op === 'var' && truth({ op: '=', a, b }, path) === true)
303
+ aliases[a.name] = b;
304
+ const id = inst.unit === 0 && inst.terms.length === 1 && inst.terms[0][0] === 1 ? inst.terms[0][1] : undefined;
305
+ if (id && !countBodies.has(id)) {
306
+ const read = cert.reads.find(r => r[0] === id);
307
+ countBodies.set(id, read ? countsForReads(ds, [read])?.[0]?.body : undefined);
308
+ }
309
+ const body = id ? countBodies.get(id) : undefined, independent = !!body && emptyCountSource(body, aliases);
310
+ try {
311
+ const part = { name: g.name, hyps: [...(independent ? [] : source(path, inst.wit)), ...(independent ? [] : available.map(s => s.good)), h, { op: 'not', x: good }] };
312
+ const reused = models.some(m => validPoint({ ...part, hyps: part.hyps.map(c => substC(c, { vars: { [inst.wit]: x(m.witness) }, maps: {}, flags: {} })) }, path, m.model) !== undefined);
313
+ if (reused) {
314
+ attempted.set(key, { version, outcome: 'sat' });
315
+ trace.push({ stage: 'closure-source', scope: scopes.indexOf(scope), index, outcome: 'reused-model', ms: clock() - before });
316
+ return 'sat';
317
+ }
318
+ const queryLimit = Math.min(end, clock() + (inst.terms.length === 5 ? 150 : 50)), q = modelSequence(path)(part, queryLimit);
319
+ let tree = 'tree' in q ? q.tree : undefined, proofSource = part, validModel = false;
320
+ if (!tree && !('tree' in q) && q.stuck === 'sat' && q.witness) {
321
+ const model = validPoint(part, path, q.witness);
322
+ if (model) {
323
+ validModel = true;
324
+ models.push({ witness: inst.wit, model });
325
+ if (models.length > 32)
326
+ models.shift();
327
+ }
328
+ }
329
+ else if (!tree && !('tree' in q) && q.why === REFUTED && q.core?.length && q.core.length <= 8 && building()) {
330
+ const limit = Math.min(end, independent ? before + 150 : Math.max(queryLimit, clock() + 100)), small = { ...part, hyps: q.core.map(i => part.hyps[i]) }, oldPoint = atPoint.on;
331
+ atPoint.on = false;
332
+ try {
333
+ let local;
334
+ // Spend the existing 50+100 fallback envelope on the independent core,
335
+ // not unrelated field choices. No syntactic observation is a proof.
336
+ if (independent) {
337
+ const out = grow(small, path, { nodes: 0, until: limit, units: true });
338
+ if ('tree' in out)
339
+ local = out.tree;
340
+ }
341
+ if (!local && clock() < limit)
342
+ local = booleanCore(small, path, new Set([inst.wit]), limit, trace, { deferCheck: true, extended: true, scalarGuards: true, model: true });
343
+ if (!local && clock() < limit) {
344
+ const folded = foldPath(small, path), out = grow(folded.goal, path, { nodes: 0, until: Math.min(limit, clock() + 25), units: false });
345
+ local = 'tree' in out ? withDeadline(limit, () => widen(folded.goal, small, out.tree, folded.opaque, path, path)) : undefined;
346
+ }
347
+ if (local) {
348
+ tree = local;
349
+ proofSource = small;
350
+ }
351
+ }
352
+ finally {
353
+ atPoint.on = oldPoint;
354
+ }
355
+ }
356
+ const accepted = !!tree && accept(good, proofSource, tree, path, scope, index), outcome = accepted ? 'checked' : validModel ? 'sat' : 'unknown';
357
+ emitted = accepted;
358
+ attempted.set(key, { version, outcome });
359
+ trace.push({ stage: 'closure-source', scope: scopes.indexOf(scope), index, independent, core: 'tree' in q ? undefined : q.core?.length, tree: !!tree, outcome, ms: clock() - before });
360
+ return outcome;
361
+ }
362
+ finally {
363
+ endFieldAttempt(meter, emitted);
364
+ }
365
+ };
366
+ // Phase C only: use active proved facts, then decide one numeric goal per
367
+ // leaf. Natural-subtraction splitting is confined to this arithmetic phase.
368
+ const pure = (c, path) => { let other = false; walkLive(c, path, (o) => { if (o.op === 'get' || o.op === 'var' && wits.has(o.name))
369
+ other = true; }); return !other; };
370
+ const replacements = Object.fromEntries([...maps].map(map => [map, (key) => { const r = cert.reads.find(r => r[1] === map && JSON.stringify(r[2]) === JSON.stringify(key)); return r ? x(r[0]) : { op: 'get', map, key }; }]));
371
+ const flags = Object.fromEntries(Object.keys(m.step.flags ?? {}).map(name => [name, { op: 'flag', name }]));
372
+ const abstracted = raw.map(c => substC(c, { vars: {}, maps: replacements, flags }));
373
+ const finish = (scope, end, depth = 0) => {
374
+ if (!alive())
375
+ return undefined;
376
+ scope = addScope(scope);
377
+ const before = clock(), scopeKey = JSON.stringify([...scope].map(([id, a]) => [id, a.holds])), excluded = excludedAt.get(scopeKey) ?? new Set(), previousEnd = leafEnd;
378
+ excludedAt.set(scopeKey, excluded);
379
+ leafEnd = end;
380
+ const numericFor = () => ({ name: g.name, hyps: [...abstracted.flatMap(c => piecesAt(c, scope)).filter(c => pure(c, scope)), ...countBindingsAt(cert.reads, scope), ...active(saved, scope).map(s => s.good).filter(c => pure(c, scope))] });
381
+ const stop = (reason) => { trace.push({ stage: 'closure-final', mode: 'model-driven', outcome: 'unknown', reason, path: [...scope], cuts: active(saved, scope).length, ms: clock() - before, total: clock() - started }); return undefined; };
382
+ const merge = (candidate) => {
383
+ const path = new Map(scope);
384
+ for (const a of candidate.values()) {
385
+ const known = decide(a.lin, path);
386
+ if (known !== undefined && known !== a.holds)
387
+ return undefined;
388
+ path.set(canon(a.lin), a);
389
+ }
390
+ return addScope(path);
391
+ };
392
+ try {
393
+ for (let round = 0; round <= pool.length && building(); round++) {
394
+ rounds++;
395
+ const available = active(saved, scope), numeric = numericFor(), natural = proveNaturalCases(numeric, scope, end, trace, { deferCheck: true }), q = natural ? { tree: natural } : modelSequence(scope)(numeric, end);
396
+ let proof = 'tree' in q ? q.tree : undefined;
397
+ // An empty core refutes the path alone; it still needs a transported proof.
398
+ if (!proof && !('tree' in q) && q.why === REFUTED && q.core) {
399
+ const small = { ...numeric, hyps: q.core.map(i => numeric.hyps[i]) }, direct = fast(small, scope), out = direct ? undefined : grow(small, scope, { nodes: 0, until: end, units: false }), local = direct ?? (out && 'tree' in out ? out.tree : undefined);
400
+ if (local)
401
+ proof = transport(small, numeric, local, scope, scope);
402
+ }
403
+ if (proof) {
404
+ const extended = lemmaPath(available.map(s => s.lemma), scope), lifted = liftCountProxies(numeric, g, proof, cert.reads, scope, extended, e => trace.push({ stage: 'closure-transport', ...e }), { deferCheck: true });
405
+ const tree = lifted && (options.conditional ? markConditionalProof(g, lifted, available.map(s => s.lemma)) : inlineConditionalCuts(g, g, lifted, extended, scope, available.map(s => s.lemma), wallEnd(), e => trace.push({ stage: 'closure-inline', ...e })));
406
+ trace.push({ stage: 'closure-final', mode: 'model-driven', fixedPoint, hyps: numeric.hyps.length, cuts: available.length, rounds: round + 1, closedIndices: available.flatMap(s => s.index === undefined ? [] : [s.index]), outcome: tree ? 'checked' : 'untransported', ms: clock() - before, total: clock() - started });
407
+ return tree;
408
+ }
409
+ if ('tree' in q || q.stuck !== 'sat' || !q.witness)
410
+ return stop('no-numeric-model');
411
+ const point = { ...q.witness };
412
+ for (const index of pool) {
413
+ const h = g.hyps[raw.length + index];
414
+ if (h?.op === 'or' && h.xs[0]?.op === '<=')
415
+ walkLive(h.xs[0], scope, (o) => { if (o.op === 'var' && !Object.hasOwn(point, o.name))
416
+ point[o.name] = 0; });
417
+ }
418
+ const model = validPoint(numeric, scope, point);
419
+ if (!model)
420
+ return stop('invalid-numeric-model');
421
+ rowModel = point;
422
+ const violated = pool.filter(index => { const h = g.hyps[raw.length + index]; return h?.op === 'or' && h.xs[0]?.op === '<=' && brokenOf({ name: 'candidate', hyps: [h.xs[0]] })(model).length > 0; }), pending = new Set(violated.filter(i => !excluded.has(i))), startedVersion = saved.length;
423
+ if (pairs.some(([a, b]) => truth({ op: '=', a, b }, scope) === undefined)) {
424
+ rowSources = new Set(violated.flatMap(index => [...sourceRows.get(index) ?? []]));
425
+ return stop('row-demand');
426
+ }
427
+ trace.push({ stage: 'closure-model-round', round: round + 1, scope: scopes.indexOf(scope), violated, pending: [...pending], excluded: [...excluded], cuts: available.length, pool: pool.length });
428
+ if (!pending.size) {
429
+ fixedPoint = true;
430
+ return stop('no-unexcluded-violated-fact');
431
+ }
432
+ while (pending.size && building()) {
433
+ const indices = [...pending], baseGoal = numericFor(), goods = indices.map(i => g.hyps[raw.length + i].xs[0]), assumed = { ...baseGoal, hyps: [...baseGoal.hyps, ...goods] }, selection = modelSequence(scope)(assumed, end);
434
+ const core = 'tree' in selection ? [...usedHyps(assumed, selection.tree, scope)] : selection.why === REFUTED ? selection.core : undefined;
435
+ const validAssumedModel = !('tree' in selection) && selection.stuck === 'sat' && selection.witness && validPoint(assumed, scope, selection.witness);
436
+ if (!core?.length && !validAssumedModel)
437
+ return stop('no-batch-core-or-model');
438
+ // A partial violated set can leave another numeric model: its members
439
+ // are still useful cuts against the current model, not a generator gap.
440
+ const chosen = core?.length ? core.filter(i => i >= baseGoal.hyps.length).map(i => indices[i - baseGoal.hyps.length]).filter(i => i !== undefined) : indices;
441
+ trace.push({ stage: 'closure-batch-core', scope: scopes.indexOf(scope), round: round + 1, indices: chosen, core: core?.length, selector: core?.length ? 'refuted' : 'sat' });
442
+ if (!chosen.length) {
443
+ if (saved.length > startedVersion)
444
+ break;
445
+ return stop('empty-batch-core');
446
+ }
447
+ let changed = false;
448
+ for (const index of chosen) {
449
+ if (!building())
450
+ break;
451
+ pending.delete(index);
452
+ const candidates = scopesFor(index).map(merge).filter((p) => p !== undefined), hinted = memberHints.has(vector(cert.insts[index])), order = hinted ? [...candidates.filter(p => p !== scope), scope] : [scope, ...candidates], seen = new Set();
453
+ let allSat = true, proved = false;
454
+ for (const path of order) {
455
+ if (seen.has(path))
456
+ continue;
457
+ seen.add(path);
458
+ if (!building()) {
459
+ allSat = false;
460
+ break;
461
+ }
462
+ const result = attempt(index, path, end);
463
+ if (result === 'checked') {
464
+ changed = true;
465
+ proved = true;
466
+ break;
467
+ }
468
+ if (result !== 'sat')
469
+ allSat = false;
470
+ }
471
+ if (allSat && !proved)
472
+ excluded.add(index);
473
+ }
474
+ const guard = saved.slice(startedVersion).flatMap(s => s.lemma.when).find(atom => scalarAtoms.has(canon(atom)) && decide(atom, scope) === undefined);
475
+ if (guard) {
476
+ if (depth >= 8)
477
+ return stop('scalar-depth');
478
+ const yes = scalar(put(scope, guard, true), end, depth + 1), no = yes && scalar(put(scope, guard, false), end, depth + 1);
479
+ trace.push({ stage: 'closure-model-split', depth, split: guard, proposed: !!yes && !!no, ms: clock() - before });
480
+ return yes && no ? { split: guard, yes, no } : undefined;
481
+ }
482
+ if (changed)
483
+ break;
484
+ }
485
+ if (saved.length === startedVersion)
486
+ return stop(building() ? 'batch-exhausted' : 'time');
487
+ }
488
+ return stop('time');
489
+ }
490
+ finally {
491
+ leafEnd = previousEnd;
492
+ }
493
+ };
494
+ const scalar = (path, end, depth = 0) => {
495
+ if (!alive())
496
+ return undefined;
497
+ const candidates = new Map();
498
+ for (const { lemma } of saved) {
499
+ if (lemma.when.some(atom => decide(atom, path) === false))
500
+ continue;
501
+ for (const atom of lemma.when) {
502
+ const id = canon(atom);
503
+ if (!scalarAtoms.has(id) || decide(atom, path) !== undefined)
504
+ continue;
505
+ const old = candidates.get(id);
506
+ candidates.set(id, { atom, uses: (old?.uses ?? 0) + 1 });
507
+ }
508
+ }
509
+ const next = [...candidates.values()].sort((a, b) => b.uses - a.uses)[0];
510
+ if (!next || depth >= 8)
511
+ return finish(path, end, depth);
512
+ const yes = scalar(put(path, next.atom, true), end, depth + 1), no = yes && scalar(put(path, next.atom, false), end, depth + 1);
513
+ trace.push({ stage: 'closure-scalar-case', depth, split: next.atom, proposed: !!yes && !!no });
514
+ return yes && no ? { split: next.atom, yes, no } : undefined;
515
+ };
516
+ let rowModel, rowSources = new Set();
517
+ let leavesLeft = Math.max(1, complete.length);
518
+ const atLeaf = (path, end) => {
519
+ rowModel = undefined;
520
+ rowSources = new Set();
521
+ const before = clock(), remaining = Math.max(0, until - before), draw = leafAllowance(remaining, leavesLeft), stop = Math.min(end, before + draw);
522
+ trace.push({ stage: 'closure-leaf-budget', remaining, leavesLeft, draw, granted: Math.max(0, stop - before), end: stop });
523
+ return scalar(path, stop);
524
+ };
525
+ const rowTrace = (event) => { const e = event; if (e.stage === 'row-case' || e.stage === 'row-mirror')
526
+ leavesLeft = Math.max(1, leavesLeft - 1); trace.push(event); };
527
+ let tree = pairs.length ? proveRowCases(g, base, pairs, until, atLeaf, rowTrace, { deferToCaller: true, splitEqual: true, model: () => rowModel, sources: () => rowSources }) : atLeaf(base, until);
528
+ for (let i = pins.length - 1; tree && i >= 0; i--)
529
+ tree = { split: pins[i].split, yes: tree, no: pins[i].no };
530
+ const checked = !!tree && alive() && (options.conditional ? checkConditionalProof(g, tree, root) : check(g, tree, root));
531
+ trace.push({ stage: 'closure-complete', cuts: saved.length, rounds, fixedPoint, checked, total: clock() - started });
532
+ return checked ? tree : undefined;
533
+ }
@@ -0,0 +1,2 @@
1
+ import { type E } from '../machine.js';
2
+ export declare function emptyCountSource(body: E, aliases?: Record<string, E>): boolean;
@@ -0,0 +1,40 @@
1
+ export function emptyCountSource(body, aliases = {}) {
2
+ let work = 16384;
3
+ const same = (a, b, depth = 0) => {
4
+ if (--work < 0 || depth > 128)
5
+ return false;
6
+ if (a?.op === 'var' && aliases[a.name])
7
+ a = aliases[a.name];
8
+ if (b?.op === 'var' && aliases[b.name])
9
+ b = aliases[b.name];
10
+ if (a === b)
11
+ return true;
12
+ if (!a || !b || typeof a !== 'object' || typeof b !== 'object')
13
+ return false;
14
+ const keys = Object.keys(a);
15
+ return keys.length === Object.keys(b).length && keys.every(k => Object.hasOwn(b, k) && same(a[k], b[k], depth + 1));
16
+ };
17
+ const impossible = (c, depth = 0) => {
18
+ if (--work < 0 || depth > 128)
19
+ return false;
20
+ if (c.op === 'or')
21
+ return c.xs.every(x => impossible(x, depth + 1));
22
+ if (c.op !== 'and')
23
+ return false;
24
+ const xs = [], flatten = (x, d) => { if (--work < 0 || d > 128)
25
+ return; if (x.op === 'and')
26
+ x.xs.forEach(y => flatten(y, d + 1));
27
+ else
28
+ xs.push(x); };
29
+ flatten(c, depth);
30
+ return work >= 0 && (xs.some(x => x.op === 'or' && impossible(x, depth + 1)) || xs.some(x => x.op === 'not' && xs.some(y => same(x.x, y, depth + 1))));
31
+ };
32
+ const zero = (e, depth = 0) => {
33
+ if (--work < 0 || depth > 128)
34
+ return false;
35
+ if (e.op === 'const')
36
+ return e.value === 0;
37
+ return e.op === 'if' && (impossible(e.c, depth + 1) ? zero(e.else, depth + 1) : zero(e.then, depth + 1) && zero(e.else, depth + 1));
38
+ };
39
+ return zero(body);
40
+ }
@@ -0,0 +1,23 @@
1
+ import { type C, type Machine } from '../machine.js';
2
+ import { type CountCert, type CountDecl, type Goal, type Path, type Tree } from '../../kernel/kernel.js';
3
+ import { type SourceProofMemo } from './source-memo.js';
4
+ import { type FieldDemand } from './field-demand.js';
5
+ type Proposal = Pick<CountCert, 'reads' | 'insts'>;
6
+ export declare function countBindingsAt(reads: CountCert['reads'], root: Path): C[];
7
+ export declare function fieldBounds(m: Machine, ds: CountDecl[], cert: Proposal, options?: {
8
+ claim?: C;
9
+ path?: Path;
10
+ }): C[];
11
+ export declare function emptyCountCandidate(m: Machine, cert: Proposal, inst: Proposal['insts'][number]): boolean;
12
+ export declare const fieldBoundLemmas: typeof fieldBoundLemmasImpl;
13
+ declare function fieldBoundLemmasImpl(m: Machine, ds: CountDecl[], g: Goal, cert: Proposal, until: number, trace: object[], onModel?: (goal: Goal, witness: Record<string, number>) => boolean, root?: Path, options?: {
14
+ splitRows?: boolean;
15
+ deferCheck?: boolean;
16
+ fieldClaim?: C;
17
+ memo?: SourceProofMemo;
18
+ closure?: boolean;
19
+ conditional?: boolean;
20
+ fieldDemand?: FieldDemand;
21
+ onSourceModel?: (goal: Goal, witness: Record<string, number>, path: Path) => void;
22
+ }): Tree | undefined;
23
+ export {};