gdp-wired 0.49.0 → 0.50.1

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 (86) hide show
  1. package/README.md +4 -0
  2. package/dist/core/candidate-seeds.d.ts +25 -0
  3. package/dist/core/candidate-seeds.js +90 -0
  4. package/dist/core/chart.js +28 -4
  5. package/dist/core/cli.js +3 -0
  6. package/dist/core/compose.js +4 -3
  7. package/dist/core/count-support.d.ts +1 -0
  8. package/dist/core/count-support.js +23 -2
  9. package/dist/core/counted-candidate-seeds.d.ts +12 -0
  10. package/dist/core/counted-candidate-seeds.js +31 -0
  11. package/dist/core/counts.js +9 -2
  12. package/dist/core/dsl-binders.d.ts +15 -0
  13. package/dist/core/dsl-binders.js +129 -0
  14. package/dist/core/dsl.d.ts +28 -2
  15. package/dist/core/dsl.js +147 -52
  16. package/dist/core/exists.js +2 -1
  17. package/dist/core/field-laws.js +23 -5
  18. package/dist/core/infer.js +10 -5
  19. package/dist/core/laws.js +2 -1
  20. package/dist/core/lift-cli.d.ts +11 -0
  21. package/dist/core/lift-cli.js +113 -0
  22. package/dist/core/proof-output.d.ts +53 -0
  23. package/dist/core/proof-output.js +38 -0
  24. package/dist/core/quorum-laws.js +55 -16
  25. package/dist/kernel/function-instances.d.ts +45 -0
  26. package/dist/kernel/function-instances.js +460 -0
  27. package/dist/kernel/prove.d.ts +12 -3
  28. package/dist/kernel/prove.js +164 -90
  29. package/dist/lean-kernel/axiom-audit.d.ts +11 -0
  30. package/dist/lean-kernel/axiom-audit.js +50 -0
  31. package/dist/lean-kernel/emit.d.ts +25 -2
  32. package/dist/lean-kernel/emit.js +75 -10
  33. package/dist/lean-kernel/legacy-family-order.d.ts +1 -0
  34. package/dist/lean-kernel/legacy-family-order.js +26 -0
  35. package/dist/lean-kernel/library.js +22 -0
  36. package/dist/lean-kernel/lift/counted-source-data.d.ts +7 -0
  37. package/dist/lean-kernel/lift/counted-source-data.js +78 -0
  38. package/dist/lean-kernel/lift/index.d.ts +82 -0
  39. package/dist/lean-kernel/lift/index.js +116 -0
  40. package/dist/lean-kernel/lift/project.d.ts +4 -0
  41. package/dist/lean-kernel/lift/project.js +15 -0
  42. package/dist/lean-kernel/lift/proof-capture.d.ts +104 -0
  43. package/dist/lean-kernel/lift/proof-capture.js +216 -0
  44. package/dist/lean-kernel/lift/proof-codec.d.ts +28 -0
  45. package/dist/lean-kernel/lift/proof-codec.js +299 -0
  46. package/dist/lean-kernel/lift/proof-counted-source.d.ts +16 -0
  47. package/dist/lean-kernel/lift/proof-counted-source.js +68 -0
  48. package/dist/lean-kernel/lift/proof-frontier.d.ts +19 -0
  49. package/dist/lean-kernel/lift/proof-frontier.js +153 -0
  50. package/dist/lean-kernel/lift/proof-graph.d.ts +17 -0
  51. package/dist/lean-kernel/lift/proof-graph.js +130 -0
  52. package/dist/lean-kernel/lift/proof-parts.d.ts +29 -0
  53. package/dist/lean-kernel/lift/proof-parts.js +131 -0
  54. package/dist/lean-kernel/lift/proof-prelude.d.ts +2 -0
  55. package/dist/lean-kernel/lift/proof-prelude.js +38 -0
  56. package/dist/lean-kernel/lift/proof-witness.d.ts +30 -0
  57. package/dist/lean-kernel/lift/proof-witness.js +283 -0
  58. package/dist/lean-kernel/lift/shape.d.ts +5 -0
  59. package/dist/lean-kernel/lift/shape.js +57 -0
  60. package/dist/lean-kernel/lift/source-projection.d.ts +16 -0
  61. package/dist/lean-kernel/lift/source-projection.js +81 -0
  62. package/dist/lean-kernel/lift/source.d.ts +23 -0
  63. package/dist/lean-kernel/lift/source.js +111 -0
  64. package/dist/lean-kernel/lift/witness-alpha.d.ts +9 -0
  65. package/dist/lean-kernel/lift/witness-alpha.js +31 -0
  66. package/dist/lean-kernel/lift-legacy.d.ts +58 -0
  67. package/dist/lean-kernel/lift-legacy.js +84 -0
  68. package/dist/lean-kernel/lift-names.d.ts +22 -0
  69. package/dist/lean-kernel/lift-names.js +36 -0
  70. package/dist/lean-kernel/lift-simulation/index.d.ts +29 -0
  71. package/dist/lean-kernel/lift-simulation/index.js +352 -0
  72. package/dist/lean-kernel/lift-simulation/shape.d.ts +41 -0
  73. package/dist/lean-kernel/lift-simulation/shape.js +173 -0
  74. package/dist/lean-kernel/lift-special/index.d.ts +36 -0
  75. package/dist/lean-kernel/lift-special/index.js +241 -0
  76. package/dist/lean-kernel/lift-special/structural.d.ts +25 -0
  77. package/dist/lean-kernel/lift-special/structural.js +126 -0
  78. package/dist/lean-kernel/lift-typed/index.d.ts +35 -0
  79. package/dist/lean-kernel/lift-typed/index.js +256 -0
  80. package/dist/lean-kernel/lift-typed/roles.d.ts +17 -0
  81. package/dist/lean-kernel/lift-typed/roles.js +170 -0
  82. package/dist/lean-kernel/lift-typed/shape.d.ts +1 -0
  83. package/dist/lean-kernel/lift-typed/shape.js +12 -0
  84. package/dist/lean-kernel/lift.d.ts +30 -0
  85. package/dist/lean-kernel/lift.js +97 -0
  86. package/package.json +8 -2
@@ -0,0 +1,460 @@
1
+ // Opt-in UNTRUSTED search only. This module proposes ordinary Instances of
2
+ // existing guarded facts. It never adds a fact, proves a goal, or changes a rule.
3
+ import { argsKey, pairedArgs } from "../core/machine.js";
4
+ import { startWork } from "../core/work-admission.js";
5
+ class Limited extends Error {
6
+ }
7
+ let active;
8
+ /** Read-only research telemetry. Inactive means no active discovery scope. */
9
+ export const functionInstanceProgress = () => active && { ...active.stats };
10
+ const safeLimit = (n, fallback) => {
11
+ const value = n ?? fallback;
12
+ if (!Number.isSafeInteger(value) || value < 1)
13
+ throw new Error('function-instantiation limits must be positive safe integers');
14
+ return value;
15
+ };
16
+ /** Synchronous, scoped, default OFF. Limits never become a successful partial
17
+ * search: a cap returns not proven, and the previous context is always restored. */
18
+ export function withFunctionInstances(source, run) {
19
+ const spec = structuredClone(source), old = active;
20
+ const context = { spec, limits: { work: safeLimit(spec.limits?.work, 500_000), candidates: safeLimit(spec.limits?.candidates, 32), tuples: safeLimit(spec.limits?.tuples, 256), depth: safeLimit(spec.limits?.depth, 4) }, stats: { work: 0, matched: 0, generated: 0, candidates: 0, cyclic: false } };
21
+ active = context;
22
+ try {
23
+ for (const [sort, parameter] of Object.entries(spec.sorts))
24
+ if (!sort || typeof parameter !== 'string')
25
+ throw new Error('invalid function-instantiation sort');
26
+ for (const d of [...Object.values(spec.functions), ...Object.values(spec.maps ?? {})]) {
27
+ if (d.result !== undefined && !(d.result in spec.sorts))
28
+ throw new Error('unknown result sort');
29
+ if ('args' in d && d.args !== undefined && (!d.args.length || d.args.some(s => !(s in spec.sorts))))
30
+ throw new Error('unknown argument sort');
31
+ }
32
+ const value = run();
33
+ if (value && typeof value === 'object' && 'then' in value)
34
+ throw new Error('function-instantiation scope must be synchronous');
35
+ return { status: 'complete', value, stats: { ...context.stats } };
36
+ }
37
+ catch (error) {
38
+ if (!(error instanceof Limited))
39
+ throw error;
40
+ return { status: 'limited', proven: false, checked: false, reason: error.message, stats: { ...context.stats } };
41
+ }
42
+ finally {
43
+ active = old;
44
+ }
45
+ }
46
+ const tick = (ctx, n = 1) => {
47
+ if (n > ctx.limits.work - ctx.stats.work)
48
+ throw new Limited('function-instantiation work limit');
49
+ startWork('ticks', n, 'function fact instantiation');
50
+ ctx.stats.work += n;
51
+ };
52
+ // Read exactly the already-supported argsKey encoding. Constant folding can
53
+ // erase its syntax; decode only canonical safe-natural constant images.
54
+ function callArgs(e, arity, ctx) {
55
+ const direct = pairedArgs(e, arity);
56
+ if (direct)
57
+ return direct;
58
+ if (e.op !== 'const' || !Number.isSafeInteger(e.value) || e.value < 0)
59
+ return undefined;
60
+ const out = [];
61
+ let z = BigInt(e.value);
62
+ for (let i = 1; i < arity; i++) {
63
+ let lo = 0n, hi = z + 1n;
64
+ while (hi - lo > 1n) {
65
+ tick(ctx);
66
+ const mid = (lo + hi) / 2n;
67
+ if (mid * mid <= z)
68
+ lo = mid;
69
+ else
70
+ hi = mid;
71
+ }
72
+ const b = z - lo * lo;
73
+ if (b > lo)
74
+ return undefined;
75
+ out.unshift({ op: 'const', value: Number(b) });
76
+ z = lo - b;
77
+ }
78
+ out.unshift({ op: 'const', value: Number(z) });
79
+ return out;
80
+ }
81
+ const children = (e) => e.op === 'if' ? [e.then, e.else] : e.op === 'mul' || e.op === 'proj' ? [e.a] : e.op === 'get' ? [e.key] : 'a' in e ? [e.a, e.b] : [];
82
+ function conditions(c, visitE, visitC) {
83
+ visitC?.(c);
84
+ if (c.op === 'all')
85
+ return; // no leaking locally bound variables
86
+ if (c.op === 'and' || c.op === 'or')
87
+ c.xs.forEach(x => conditions(x, visitE, visitC));
88
+ else if (c.op === 'not')
89
+ conditions(c.x, visitE, visitC);
90
+ else if (c.op !== 'flag') {
91
+ visitE(c.a);
92
+ visitE(c.b);
93
+ }
94
+ }
95
+ function factsOf(m, ctx) {
96
+ const byParameter = new Map();
97
+ for (const [s, p] of Object.entries(ctx.spec.sorts))
98
+ byParameter.set(p, [...byParameter.get(p) ?? [], s]);
99
+ const facts = [];
100
+ for (const law of m.facts ?? []) {
101
+ if (!law.forall || law.holds.op !== 'or' || law.holds.xs.length !== 2 || law.holds.xs[0].op !== 'not')
102
+ continue;
103
+ tick(ctx);
104
+ const guard = law.holds.xs[0].x, vars = [law.forall, ...law.keys ?? []], types = new Map();
105
+ conditions(guard, () => { }, c => {
106
+ tick(ctx);
107
+ if (c.op !== '<' || c.a.op !== 'var' || c.b.op !== 'var' || !vars.includes(c.a.name))
108
+ return;
109
+ const ss = byParameter.get(c.b.name);
110
+ if (ss?.length === 1)
111
+ types.set(c.a.name, ss[0]);
112
+ });
113
+ if (vars.some(v => !types.has(v)))
114
+ continue;
115
+ const patterns = [];
116
+ const visit = (e) => {
117
+ tick(ctx);
118
+ if (e.op === 'get') {
119
+ const d = Object.hasOwn(ctx.spec.functions, e.map) ? ctx.spec.functions[e.map] : undefined, args = d && d.args.length === (m.fns?.[e.map]?.arity ?? 1) && callArgs(e.key, d.args.length, ctx);
120
+ if (args)
121
+ patterns.push({ name: e.map, args });
122
+ }
123
+ if (e.op === 'if')
124
+ conditions(e.c, visit);
125
+ children(e).forEach(visit);
126
+ };
127
+ conditions(law.holds, visit);
128
+ if (patterns.length)
129
+ facts.push({ law, vars, sorts: vars.map(v => types.get(v)), patterns });
130
+ }
131
+ return facts;
132
+ }
133
+ /** An inactive/nonmatching machine takes the existing prover path untouched. */
134
+ export function hasFunctionInstances(m) {
135
+ return active !== undefined && !!m.facts?.some(f => f.forall && f.holds.op === 'or' && f.holds.xs[0]?.op === 'not') && Object.keys(active.spec.functions).some(name => Object.hasOwn(m.fns ?? {}, name));
136
+ }
137
+ export function extendFunctionInstances(m, input, goals, legacy) {
138
+ const ctx = active;
139
+ if (!ctx)
140
+ return input;
141
+ const facts = factsOf(m, ctx);
142
+ if (!facts.length)
143
+ return legacy ? legacy(m, input, goals) : input;
144
+ const pools = new Map(Object.keys(ctx.spec.sorts).map(s => [s, new Map()]));
145
+ const fingerprints = new WeakMap(), identities = new Map();
146
+ const pack = (parts) => {
147
+ const chars = parts.reduce((n, p) => n + (typeof p === 'string' ? p.length : 24), 0);
148
+ tick(ctx, 1 + Math.ceil(chars / 32));
149
+ return JSON.stringify(parts);
150
+ };
151
+ // Exact structural hash-consing, not recursive JSON-in-JSON strings (whose
152
+ // escaping grows exponentially with depth). IDs are local deterministic
153
+ // equality tokens, not hashes; distinct structures cannot collide.
154
+ const intern = (parts) => {
155
+ const text = pack(parts), prior = identities.get(text);
156
+ if (prior !== undefined)
157
+ return prior;
158
+ const id = String(identities.size);
159
+ identities.set(text, id);
160
+ return id;
161
+ };
162
+ const conditionKey = (c) => {
163
+ tick(ctx);
164
+ const prior = fingerprints.get(c);
165
+ if (prior !== undefined)
166
+ return prior;
167
+ let id;
168
+ if (c.op === 'flag')
169
+ id = intern(['C', c.op, c.name]);
170
+ else if (c.op === 'all')
171
+ id = intern(['C', c.op, c.key, ...c.keys ?? [], c.finite ?? '', conditionKey(c.c)]);
172
+ else if (c.op === 'not')
173
+ id = intern(['C', c.op, conditionKey(c.x)]);
174
+ else if (c.op === 'and' || c.op === 'or')
175
+ id = intern(['C', c.op, ...c.xs.map(conditionKey)]);
176
+ else
177
+ id = intern(['C', c.op, key(c.a), key(c.b)]);
178
+ fingerprints.set(c, id);
179
+ return id;
180
+ };
181
+ const key = (e) => {
182
+ tick(ctx);
183
+ const prior = fingerprints.get(e);
184
+ if (prior !== undefined)
185
+ return prior;
186
+ const metadata = e.op === 'var' ? e.name : e.op === 'const' ? e.value : e.op === 'get' ? e.map : e.op === 'mul' || e.op === 'proj' ? e.k : '';
187
+ const value = intern(['E', e.op, metadata, ...(e.op === 'if' ? [conditionKey(e.c)] : []), ...children(e).map(key)]);
188
+ fingerprints.set(e, value);
189
+ return value;
190
+ };
191
+ const add = (sort, e, priority, depth = 0) => {
192
+ const pool = pools.get(sort);
193
+ if (!pool)
194
+ return false;
195
+ const id = key(e), had = pool.get(id);
196
+ if (had) {
197
+ if (priority < had.priority)
198
+ had.priority = priority;
199
+ return false;
200
+ }
201
+ if (pool.size >= ctx.limits.candidates)
202
+ throw new Limited(`function-instantiation candidate limit for ${sort}`);
203
+ tick(ctx);
204
+ pool.set(id, { e, priority, depth });
205
+ ctx.stats.candidates++;
206
+ return true;
207
+ };
208
+ const reads = [];
209
+ const variableSort = (name) => {
210
+ for (const n of [name, name.replace(/#$/, '')])
211
+ if (Object.hasOwn(ctx.spec.variables ?? {}, n))
212
+ return ctx.spec.variables[n];
213
+ return undefined;
214
+ };
215
+ // Nominal declaration metadata is a search filter, never a new hypothesis.
216
+ // Legacy helpers can be instantiated at an entire encoded pair; do not feed
217
+ // that pair back as an atomic-sort candidate and recursively amplify it.
218
+ const compatible = (e, sort) => {
219
+ tick(ctx);
220
+ if (e.op === 'var') {
221
+ const s = variableSort(e.name);
222
+ return s === undefined || s === sort;
223
+ }
224
+ if (e.op === 'tup' || e.op !== 'const' && pairedArgs(e, 2))
225
+ return false;
226
+ if (e.op === 'if')
227
+ return compatible(e.then, sort) && compatible(e.else, sort);
228
+ if (e.op === 'get') {
229
+ const fn = Object.hasOwn(ctx.spec.functions, e.map) ? ctx.spec.functions[e.map] : undefined;
230
+ const mp = ctx.spec.maps && Object.hasOwn(ctx.spec.maps, e.map) ? ctx.spec.maps[e.map] : undefined;
231
+ const d = fn ?? mp;
232
+ if (d?.result !== undefined && d.result !== sort)
233
+ return false;
234
+ if (d?.args) {
235
+ const xs = callArgs(e.key, d.args.length, ctx);
236
+ if (!xs || !xs.every((x, i) => compatible(x, d.args[i])))
237
+ return false;
238
+ }
239
+ }
240
+ return true;
241
+ };
242
+ const seenExpressions = new Set();
243
+ const visit = (e) => {
244
+ tick(ctx);
245
+ const id = key(e);
246
+ if (seenExpressions.has(id))
247
+ return;
248
+ seenExpressions.add(id);
249
+ if (e.op === 'var') {
250
+ const s = variableSort(e.name);
251
+ if (s)
252
+ add(s, e, 1);
253
+ }
254
+ if (e.op === 'get') {
255
+ const d = Object.hasOwn(ctx.spec.functions, e.map) ? ctx.spec.functions[e.map] : undefined;
256
+ if (d && Object.hasOwn(m.fns ?? {}, e.map) && d.args.length === (m.fns[e.map].arity ?? 1)) {
257
+ const args = callArgs(e.key, d.args.length, ctx);
258
+ if (args?.every((arg, i) => compatible(arg, d.args[i]))) {
259
+ reads.push({ name: e.map, args });
260
+ args.forEach((arg, i) => add(d.args[i], arg, 0));
261
+ if (d.result)
262
+ add(d.result, e, 1);
263
+ }
264
+ }
265
+ const map = ctx.spec.maps && Object.hasOwn(ctx.spec.maps, e.map) ? ctx.spec.maps[e.map] : undefined;
266
+ if (map && compatible(e, map.result))
267
+ add(map.result, e, 1);
268
+ }
269
+ if (e.op === 'if')
270
+ scan(e.c);
271
+ children(e).forEach(visit);
272
+ };
273
+ const seenConditions = new Set();
274
+ const scan = (c2) => {
275
+ tick(ctx);
276
+ if (c2.op === 'all')
277
+ return;
278
+ const id = conditionKey(c2);
279
+ if (seenConditions.has(id))
280
+ return;
281
+ seenConditions.add(id);
282
+ tick(ctx);
283
+ if (c2.op === '<' && c2.a.op === 'var' && c2.b.op === 'var') {
284
+ const parameter = c2.b.name;
285
+ const matches = Object.entries(ctx.spec.sorts).filter(([, p]) => p === parameter);
286
+ if (matches.length === 1 && compatible(c2.a, matches[0][0]))
287
+ add(matches[0][0], c2.a, 1);
288
+ }
289
+ if (c2.op === 'and' || c2.op === 'or')
290
+ c2.xs.forEach(scan);
291
+ else if (c2.op === 'not')
292
+ scan(c2.x);
293
+ else if (c2.op !== 'flag') {
294
+ visit(c2.a);
295
+ visit(c2.b);
296
+ }
297
+ };
298
+ for (const goal of goals)
299
+ goal.hyps.forEach(scan);
300
+ // Generic sort-derived candidate, not an assertion of inhabitance. Original
301
+ // guards stay in every instance of every fact, even for empty sorts.
302
+ for (const sort of pools.keys())
303
+ add(sort, { op: 'const', value: 0 }, 3);
304
+ const functions = Object.entries(ctx.spec.functions).filter(([name, d]) => d.result && Object.hasOwn(m.fns ?? {}, name));
305
+ const rank = new Map(), visiting = new Set();
306
+ let cyclic = false;
307
+ const level = (sort) => {
308
+ tick(ctx);
309
+ if (visiting.has(sort)) {
310
+ cyclic = true;
311
+ return 0;
312
+ }
313
+ if (rank.has(sort))
314
+ return rank.get(sort);
315
+ visiting.add(sort);
316
+ const parents = functions.filter(([, d]) => d.result === sort).flatMap(([, d]) => d.args);
317
+ const n = parents.length ? 1 + Math.max(...parents.map(level)) : 0;
318
+ visiting.delete(sort);
319
+ rank.set(sort, n);
320
+ return n;
321
+ };
322
+ for (const sort of pools.keys())
323
+ level(sort);
324
+ ctx.stats.cyclic ||= cyclic;
325
+ const ordered = functions.sort(([, a], [, b]) => rank.get(a.result) - rank.get(b.result));
326
+ const candidates = (sort) => [...pools.get(sort).values()].sort((a, b) => a.priority - b.priority);
327
+ const cartesian = (ss, consume) => {
328
+ const go = (i, xs) => {
329
+ tick(ctx);
330
+ if (i === ss.length) {
331
+ consume(xs);
332
+ return;
333
+ }
334
+ for (const candidate of candidates(ss[i])) {
335
+ tick(ctx);
336
+ go(i + 1, [...xs, candidate]);
337
+ }
338
+ };
339
+ go(0, []);
340
+ };
341
+ for (let round = 0; round < (cyclic ? ctx.limits.depth + 1 : 1); round++) {
342
+ let changed = false;
343
+ for (const [name, d] of ordered)
344
+ cartesian([...d.args], xs => {
345
+ const depth = 1 + Math.max(...xs.map(x => x.depth));
346
+ // Check limits before constructing a new application.
347
+ if (cyclic && depth > ctx.limits.depth)
348
+ throw new Limited('function-instantiation cyclic depth limit');
349
+ tick(ctx, xs.length + 1);
350
+ const e = { op: 'get', map: name, key: argsKey(xs.map(x => x.e)) };
351
+ changed = add(d.result, e, 2, depth) || changed;
352
+ });
353
+ if (!changed)
354
+ break;
355
+ }
356
+ const match = (pattern, term, variables, binding) => {
357
+ tick(ctx);
358
+ if (pattern.op === 'var' && variables.has(pattern.name)) {
359
+ const prior = binding.get(pattern.name);
360
+ if (prior)
361
+ return key(prior) === key(term);
362
+ binding.set(pattern.name, term);
363
+ return true;
364
+ }
365
+ if (pattern.op !== term.op)
366
+ return false;
367
+ if (pattern.op === 'if' || term.op === 'if')
368
+ return key(pattern) === key(term); // conservative; no binder capture
369
+ if (pattern.op === 'var' && term.op === 'var')
370
+ return pattern.name === term.name;
371
+ if (pattern.op === 'const' && term.op === 'const')
372
+ return pattern.value === term.value;
373
+ if (pattern.op === 'get' && term.op === 'get') {
374
+ if (pattern.map !== term.map)
375
+ return false;
376
+ const decl = Object.hasOwn(ctx.spec.functions, pattern.map) ? ctx.spec.functions[pattern.map] : undefined;
377
+ if (decl) {
378
+ const pa = callArgs(pattern.key, decl.args.length, ctx), ta = callArgs(term.key, decl.args.length, ctx);
379
+ if (pa && ta)
380
+ return pa.every((p, i) => match(p, ta[i], variables, binding));
381
+ }
382
+ }
383
+ if ((pattern.op === 'mul' && term.op === 'mul' || pattern.op === 'proj' && term.op === 'proj') && pattern.k !== term.k)
384
+ return false;
385
+ const left = children(pattern), right = children(term);
386
+ return left.length === right.length && left.every((p, i) => match(p, right[i], variables, binding));
387
+ };
388
+ const handled = new Set(facts.map(f => f.law));
389
+ const other = (m.facts ?? []).filter(f => !handled.has(f));
390
+ const out = { ...(legacy && other.length ? legacy({ ...m, facts: other }, input, goals) : input) };
391
+ for (const fact of facts) {
392
+ const seen = new Set(), priorEntries = input[fact.law.name] ?? [], n = fact.vars.length;
393
+ if (priorEntries.length % n)
394
+ throw new Error('incomplete existing function-fact tuple');
395
+ if (priorEntries.length / n > ctx.limits.tuples)
396
+ throw new Limited(`function-instantiation existing tuple limit for ${fact.law.name}`);
397
+ tick(ctx, priorEntries.length + 1);
398
+ const entries = [...priorEntries];
399
+ const tupleKey = (xs) => pack(xs.map(key));
400
+ for (let i = 0; i < entries.length; i += n)
401
+ seen.add(tupleKey(entries.slice(i, i + n)));
402
+ const emit = (xs, matched) => {
403
+ tick(ctx);
404
+ const id = tupleKey(xs);
405
+ if (seen.has(id))
406
+ return;
407
+ if (seen.size >= ctx.limits.tuples)
408
+ throw new Limited(`function-instantiation tuple limit for ${fact.law.name}`);
409
+ seen.add(id);
410
+ entries.push(...xs);
411
+ if (matched)
412
+ ctx.stats.matched++;
413
+ else
414
+ ctx.stats.generated++;
415
+ };
416
+ const variables = new Set(fact.vars), partials = [], partialKeys = new Set();
417
+ const bindingKey = (b) => pack(fact.vars.map(v => b.has(v) ? key(b.get(v)) : ''));
418
+ for (const pattern of fact.patterns)
419
+ for (const read of reads) {
420
+ tick(ctx);
421
+ if (pattern.name !== read.name || pattern.args.length !== read.args.length)
422
+ continue;
423
+ const binding = new Map();
424
+ if (pattern.args.every((p, i) => match(p, read.args[i], variables, binding)) && binding.size) {
425
+ const id = bindingKey(binding);
426
+ if (partialKeys.has(id))
427
+ continue;
428
+ if (partials.length >= ctx.limits.tuples)
429
+ throw new Limited('function-instantiation pattern limit');
430
+ partialKeys.add(id);
431
+ partials.push(binding);
432
+ }
433
+ }
434
+ // Covering pattern sets: join compatible partial bindings, never changing a
435
+ // repeated variable. Dedup/cap before retaining each candidate join.
436
+ const joined = [new Map()], joinedKeys = new Set(['']);
437
+ for (const partial of partials) {
438
+ const count = joined.length;
439
+ for (let j = 0; j < count; j++) {
440
+ tick(ctx);
441
+ const prior = joined[j];
442
+ if ([...partial].some(([v, e]) => prior.has(v) && key(prior.get(v)) !== key(e)))
443
+ continue;
444
+ tick(ctx, prior.size + partial.size + 1);
445
+ const merged = new Map([...prior, ...partial]), id = bindingKey(merged);
446
+ if (joinedKeys.has(id))
447
+ continue;
448
+ if (joined.length >= ctx.limits.tuples)
449
+ throw new Limited('function-instantiation pattern-set limit');
450
+ joinedKeys.add(id);
451
+ joined.push(merged);
452
+ if (fact.vars.every(v => merged.has(v)))
453
+ emit(fact.vars.map(v => merged.get(v)), true);
454
+ }
455
+ }
456
+ cartesian(fact.sorts, xs => emit(xs.map(x => x.e), false));
457
+ out[fact.law.name] = entries;
458
+ }
459
+ return out;
460
+ }
@@ -150,12 +150,20 @@ export declare function openAt(goal: Goal, path: Path, rows: {
150
150
  }[]): Lin[];
151
151
  export declare const keyValue: (cell: string, w: Record<string, number>) => number | undefined;
152
152
  export declare const modelRounds = 4;
153
- export declare function modelInstances(m: Machine, laws: Law[], inst: Instances, goal: Goal, w: Record<string, number>, most?: number, sorted?: boolean): Instances | undefined;
153
+ export type ModelRoundPolicy = number | 'progress';
154
+ export declare function validateModelRounds(value: unknown): ModelRoundPolicy;
155
+ export declare function effectiveModelRounds(): ModelRoundPolicy;
156
+ export declare function withModelRounds<T>(value: ModelRoundPolicy | undefined, f: () => T): T;
157
+ export type ModelConfirmation = {
158
+ confirmed: boolean;
159
+ why?: string;
160
+ };
161
+ export declare function modelInstances(m: Machine, laws: Law[], inst: Instances, goal: Goal, w: Record<string, number>, most?: number, sorted?: boolean, confirmation?: ModelConfirmation): Instances | undefined;
154
162
  export declare const modelShare = 3;
155
163
  export declare function withModels<T>(m: Machine, laws: Law[], inst: Instances, goalOf: (i: Instances) => Goal[], ask: (gs: Goal[]) => T, modelOf: (t: T) => {
156
164
  goal: Goal;
157
165
  w: Record<string, number>;
158
- } | undefined, settled: (t: T) => boolean): {
166
+ } | undefined, settled: (t: T) => boolean, unknown: (t: T, why: string) => T): {
159
167
  result: T;
160
168
  inst: Instances;
161
169
  };
@@ -217,7 +225,7 @@ type Decided = {
217
225
  export declare const decideLawHook: {
218
226
  on?: (m: Machine, laws: Law[], i: number, out: Decided, ms: number) => void;
219
227
  };
220
- export declare function decideLaw(m: Machine, laws: Law[], i: number, rounds?: number): Decided;
228
+ export declare function decideLaw(m: Machine, laws: Law[], i: number, rounds?: ModelRoundPolicy): Decided;
221
229
  export declare const decideNote: {
222
230
  refuted: boolean;
223
231
  hint?: {
@@ -264,6 +272,7 @@ export declare function proveLaw(m: Machine, laws: Law[], i: number): {
264
272
  stuck: string;
265
273
  witness?: Record<string, number>;
266
274
  diagram?: Diagram;
275
+ why?: string;
267
276
  };
268
277
  export declare const withStrict: <T>(f: () => T) => T;
269
278
  export declare const sortMemoStats: {