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
@@ -0,0 +1,1052 @@
1
+ // UNTRUSTED relative-CTI proposals, not a proof, finite cover, or drop decision.
2
+ // The consumer MUST independently check m.pre, ALL m.facts, the WHOLE current
3
+ // family, the source interpreter's enabled step, and each reported post-law. This module owns no
4
+ // solver/kernel policy and never extends the enclosing cooperative wall.
5
+ import { cpair, cunpair, walk } from "./machine.js";
6
+ import { checkWall, WallExpired } from "./wall.js";
7
+ const unique = (xs) => [...new Set(xs)];
8
+ const conjunction = (xs) => {
9
+ if (xs.includes(false))
10
+ return false;
11
+ const ys = xs.filter(x => x !== true);
12
+ return ys.length === 0 ? true : ys.length === 1 ? ys[0] : { op: 'and', xs: ys };
13
+ };
14
+ const disjunction = (xs) => {
15
+ if (xs.includes(true))
16
+ return true;
17
+ const ys = xs.filter(x => x !== false);
18
+ return ys.length === 0 ? false : ys.length === 1 ? ys[0] : { op: 'or', xs: ys };
19
+ };
20
+ const negate = (x) => typeof x === 'boolean' ? !x : x.op === 'not' ? x.x : { op: 'not', x };
21
+ const dependencyCache = new WeakMap();
22
+ const depsOf = (p) => {
23
+ if (typeof p === 'boolean')
24
+ return [];
25
+ checkWall('tiny dependencies');
26
+ const hit = dependencyCache.get(p);
27
+ if (hit)
28
+ return hit;
29
+ const out = p.op === 'atom' ? unique([...p.a.deps, ...p.b.deps]) : p.op === 'not' ? depsOf(p.x) : unique(p.xs.flatMap(depsOf));
30
+ dependencyCache.set(p, out);
31
+ return out;
32
+ };
33
+ const conjuncts = (c) => c.op === 'and' ? c.xs.flatMap(conjuncts) : [c];
34
+ class Unsupported extends Error {
35
+ }
36
+ // All code strings below are built from closed operators, numerical literals,
37
+ // and slot numbers. Source names and external function JS are never executable.
38
+ class Compiler {
39
+ source;
40
+ m;
41
+ p;
42
+ slots;
43
+ cells;
44
+ binders;
45
+ terms = [];
46
+ flagConstants = new Map();
47
+ intern = new Map();
48
+ reads = new Map();
49
+ flags = new Map();
50
+ environmentKey(env) { return this.source.inputs.map(k => Object.hasOwn(env, k) ? `${k}:${env[k]}` : k).join(';'); }
51
+ constructor(source, m, p, slots, cells, binders) {
52
+ this.source = source;
53
+ this.m = m;
54
+ this.p = p;
55
+ this.slots = slots;
56
+ this.cells = cells;
57
+ this.binders = binders;
58
+ }
59
+ term(code, args, lo, hi, deps = unique(args.flatMap(t => t.deps))) {
60
+ if (!Number.isSafeInteger(lo) || !Number.isSafeInteger(hi))
61
+ throw new Unsupported('inexact arithmetic range');
62
+ const key = code + ':' + args.map(a => a.id).join(',');
63
+ let t = this.intern.get(key);
64
+ if (!t) {
65
+ t = { id: this.terms.length, code, args, lo, hi, deps, ...(hi - lo <= 16 ? { values: Array.from({ length: hi - lo + 1 }, (_, i) => lo + i) } : {}) };
66
+ this.terms.push(t);
67
+ this.intern.set(key, t);
68
+ }
69
+ return t;
70
+ }
71
+ constant(n) { return this.term(String(n), [], n, n); }
72
+ ref(t) { return `t${t.id}`; }
73
+ slot(i) { const vs = this.slots[i].values; return this.term(`v[${i}]`, [], Math.min(...vs), Math.max(...vs), [i]); }
74
+ binary(op, a, b) {
75
+ checkWall('tiny arithmetic compile');
76
+ const finish = (t) => {
77
+ t.arithmetic = op;
78
+ if (a.values && b.values && a.values.length * b.values.length <= 256)
79
+ t.values = unique(a.values.flatMap(x => b.values.map(y => op === 'add' ? x + y : op === 'sub' ? Math.max(0, x - y) : op === 'prod' ? x * y : op === 'min' ? Math.min(x, y) : op === 'max' ? Math.max(x, y) : cpair(x, y)))).sort((x, y) => x - y);
80
+ return t;
81
+ };
82
+ const ar = this.ref(a), br = this.ref(b);
83
+ if (a.lo === a.hi && b.lo === b.hi) {
84
+ const x = a.lo, y = b.lo;
85
+ return this.constant(op === 'add' ? x + y : op === 'sub' ? Math.max(0, x - y) : op === 'prod' ? x * y : op === 'min' ? Math.min(x, y) : op === 'max' ? Math.max(x, y) : cpair(x, y));
86
+ }
87
+ if ((op === 'add' || op === 'sub') && b.hi === 0)
88
+ return a;
89
+ if (op === 'add' && a.hi === 0)
90
+ return b;
91
+ if (op === 'prod' && (a.hi === 0 || b.hi === 0))
92
+ return this.constant(0);
93
+ if (op === 'prod' && b.lo === 1 && b.hi === 1)
94
+ return a;
95
+ if (op === 'prod' && a.lo === 1 && a.hi === 1)
96
+ return b;
97
+ if (op === 'add')
98
+ return finish(this.term(`(${ar}+${br})`, [a, b], a.lo + b.lo, a.hi + b.hi));
99
+ if (op === 'sub')
100
+ return finish(this.term(`Math.max(0,${ar}-${br})`, [a, b], Math.max(0, a.lo - b.hi), Math.max(0, a.hi - b.lo)));
101
+ if (op === 'prod')
102
+ return finish(this.term(`(${ar}*${br})`, [a, b], a.lo * b.lo, a.hi * b.hi));
103
+ if (op === 'min' || op === 'max')
104
+ return finish(this.term(`Math.${op}(${ar},${br})`, [a, b], Math[op](a.lo, b.lo), Math[op](a.hi, b.hi)));
105
+ throw new Unsupported('nonconstant tuple');
106
+ }
107
+ compare(cmp, a, b) {
108
+ checkWall('tiny comparison compile');
109
+ if (cmp === '=') {
110
+ if (a.id === b.id)
111
+ return true;
112
+ if (a.hi < b.lo || b.hi < a.lo)
113
+ return false;
114
+ if (a.lo === a.hi && b.lo === b.hi)
115
+ return a.lo === b.lo;
116
+ }
117
+ if (cmp === '<') {
118
+ if (a.hi < b.lo)
119
+ return true;
120
+ if (a.lo >= b.hi)
121
+ return false;
122
+ }
123
+ if (cmp === '<=') {
124
+ if (a.hi <= b.lo)
125
+ return true;
126
+ if (a.lo > b.hi)
127
+ return false;
128
+ }
129
+ if (a.choice) {
130
+ const q = a.choice;
131
+ return disjunction([conjunction([q.c, this.compare(cmp, q.a, b)]), conjunction([negate(q.c), this.compare(cmp, q.b, b)])]);
132
+ }
133
+ if (b.choice) {
134
+ const q = b.choice;
135
+ return disjunction([conjunction([q.c, this.compare(cmp, a, q.a)]), conjunction([negate(q.c), this.compare(cmp, a, q.b)])]);
136
+ }
137
+ return { op: 'atom', cmp, a, b };
138
+ }
139
+ // A numeric conditional keeps its condition's dependencies; the condition is
140
+ // evaluated only once all of them are assigned (no guessed truth values).
141
+ conditional(c, a, b) {
142
+ if (typeof c === 'boolean')
143
+ return c ? a : b;
144
+ if (a.id === b.id)
145
+ return a;
146
+ if (a.lo === 1 && a.hi === 1 && b.lo === 0 && b.hi === 0 && c.op === 'atom') {
147
+ if (c.cmp === '=' && c.a.lo === 0 && c.a.hi === 1 && c.b.lo === 1 && c.b.hi === 1)
148
+ return c.a;
149
+ if (c.cmp === '<=' && c.a.lo === 1 && c.a.hi === 1 && c.b.lo === 0 && c.b.hi === 1)
150
+ return c.b;
151
+ }
152
+ const ds = unique([...depsOf(c), ...a.deps, ...b.deps]), used = [];
153
+ const code = this.predicateCode(c, undefined, used);
154
+ const out = this.term(`(${code}?${this.ref(a)}:${this.ref(b)})`, uniqueTerms([...used, a, b]), Math.min(a.lo, b.lo), Math.max(a.hi, b.hi), ds);
155
+ out.choice = { c, a, b };
156
+ if (a.values && b.values)
157
+ out.values = unique([...a.values, ...b.values]).sort((x, y) => x - y);
158
+ return out;
159
+ }
160
+ expression(e, env, post = false, stack = []) {
161
+ checkWall('tiny compile expression');
162
+ if (stack.length > 48)
163
+ throw new Unsupported('recursive count/flag');
164
+ switch (e.op) {
165
+ case 'const': return this.constant(e.value);
166
+ case 'var': {
167
+ if (Object.hasOwn(env, e.name))
168
+ return this.constant(env[e.name]);
169
+ if (post && e.name in this.source.state)
170
+ return this.expression(this.source.step.state?.[e.name] ?? e, env, false, stack);
171
+ const i = this.slots.findIndex(s => s.key === undefined && s.name === e.name);
172
+ if (i >= 0)
173
+ return this.slot(i);
174
+ throw new Unsupported(`free variable ${e.name}`);
175
+ }
176
+ case 'add':
177
+ case 'sub':
178
+ case 'prod':
179
+ case 'min':
180
+ case 'max':
181
+ case 'tup': return this.binary(e.op, this.expression(e.a, env, post, stack), this.expression(e.b, env, post, stack));
182
+ case 'mul': return this.binary('prod', this.constant(e.k), this.expression(e.a, env, post, stack));
183
+ case 'proj': {
184
+ const a = this.expression(e.a, env, post, stack);
185
+ if (a.lo !== a.hi)
186
+ throw new Unsupported('nonconstant projection');
187
+ return this.constant(cunpair(a.lo)[e.k]);
188
+ }
189
+ case 'if': {
190
+ const c = this.condition(e.c, env, post, stack);
191
+ if (typeof c === 'boolean')
192
+ return this.expression(c ? e.then : e.else, env, post, stack);
193
+ return this.conditional(c, this.expression(e.then, env, post, stack), this.expression(e.else, env, post, stack));
194
+ }
195
+ case 'get': {
196
+ const key = this.expression(e.key, env, post, stack);
197
+ if (key.lo !== key.hi) {
198
+ if (!key.values && key.hi - key.lo > 256)
199
+ throw new Unsupported('wide dynamic map key');
200
+ if (key.values && key.values.length > 256)
201
+ throw new Unsupported('many dynamic map keys');
202
+ const keys = key.values ?? Array.from({ length: key.hi - key.lo + 1 }, (_, i) => key.lo + i);
203
+ let out = this.read(e.map, keys.at(-1), env, post, stack);
204
+ for (const k of keys.slice(0, -1).reverse()) {
205
+ checkWall('tiny dynamic reads');
206
+ out = this.conditional(this.compare('=', key, this.constant(k)), this.read(e.map, k, env, post, stack), out);
207
+ }
208
+ return out;
209
+ }
210
+ return this.read(e.map, key.lo, env, post, stack);
211
+ }
212
+ }
213
+ }
214
+ read(map, key, env, post, stack) {
215
+ checkWall('tiny compile read');
216
+ const id = JSON.stringify([map, key, post, this.environmentKey(env)]);
217
+ const hit = this.reads.get(id);
218
+ if (hit)
219
+ return hit;
220
+ const value = this.readUncached(map, key, env, post, stack);
221
+ this.reads.set(id, value);
222
+ return value;
223
+ }
224
+ readUncached(map, key, env, post, stack) {
225
+ const d = this.m.counts?.[map];
226
+ if (d) {
227
+ if (stack.includes(`count:${map}`))
228
+ throw new Unsupported('recursive count');
229
+ const at = { ...env, [d.j]: d.base ? Math.floor(key / d.base) : key, ...(d.lo && d.base ? { [d.lo]: key % d.base } : {}) };
230
+ const bound = this.expression(d.below, at, post, stack);
231
+ if (bound.lo !== bound.hi || bound.hi > 16)
232
+ throw new Unsupported('nonconstant/large count bound');
233
+ let out = this.constant(0);
234
+ for (let k = 0; k < bound.hi; k++) {
235
+ checkWall('tiny count expansion');
236
+ out = this.binary('add', out, this.expression(d.body, { ...at, [d.key]: k }, post, [...stack, `count:${map}`]));
237
+ }
238
+ return out;
239
+ }
240
+ if (this.m.fns?.[map])
241
+ throw new Unsupported('external function');
242
+ if (post && map in (this.source.maps ?? {})) {
243
+ const w = this.source.step.maps?.[map];
244
+ if (w && 'each' in w)
245
+ return this.expression(w.value, { ...env, [w.each]: key }, false, stack);
246
+ if (w)
247
+ return this.conditional(this.compare('=', this.expression(w.key, env, false, stack), this.constant(key)), this.expression(w.value, env, false, stack), this.read(map, key, env, false, stack));
248
+ }
249
+ const i = this.slots.findIndex(s => s.name === map && s.key === key);
250
+ if (i >= 0)
251
+ return this.slot(i);
252
+ if (map in (this.source.maps ?? {}))
253
+ return this.constant(this.source.maps[map]);
254
+ if (this.source.inputMaps?.includes(map))
255
+ return this.constant(0);
256
+ throw new Unsupported(`unknown map ${map}`);
257
+ }
258
+ condition(c, env, post = false, stack = []) {
259
+ checkWall('tiny compile predicate');
260
+ if (stack.length > 48)
261
+ throw new Unsupported('recursive count/flag');
262
+ switch (c.op) {
263
+ case '<':
264
+ case '<=':
265
+ case '=': return this.compare(c.op, this.expression(c.a, env, post, stack), this.expression(c.b, env, post, stack));
266
+ case 'not': return negate(this.condition(c.x, env, post, stack));
267
+ case 'and':
268
+ case 'or': {
269
+ const xs = [];
270
+ for (const x of c.xs) {
271
+ const p = this.condition(x, env, post, stack);
272
+ if (p === (c.op === 'or'))
273
+ return p;
274
+ xs.push(p);
275
+ }
276
+ return c.op === 'and' ? conjunction(xs) : disjunction(xs);
277
+ }
278
+ case 'flag': {
279
+ if (this.flagConstants.has(c.name))
280
+ return this.flagConstants.get(c.name);
281
+ const f = this.source.step.flags?.[c.name];
282
+ if (!f || stack.includes(`flag:${c.name}`))
283
+ throw new Unsupported('unknown/recursive flag');
284
+ const id = JSON.stringify([c.name, this.environmentKey(env)]);
285
+ let value = this.flags.get(id);
286
+ if (value === undefined) {
287
+ value = this.condition(f, env, false, [...stack, `flag:${c.name}`]);
288
+ this.flags.set(id, value);
289
+ }
290
+ return value;
291
+ }
292
+ case 'all': return conjunction(bindings([c.key, ...c.keys ?? []], this.binders, env).map(at => this.condition(c.c, at, post, stack)));
293
+ }
294
+ }
295
+ predicateCode(p, rank, used, polarity = true) {
296
+ checkWall('tiny predicate code');
297
+ if (typeof p === 'boolean')
298
+ return String(p === polarity);
299
+ if (p.op === 'not')
300
+ return this.predicateCode(p.x, rank, used, !polarity);
301
+ if (p.op === 'and' || p.op === 'or')
302
+ return '(' + p.xs.map(x => this.predicateCode(x, rank, used, polarity)).join((p.op === 'and') === polarity ? '&&' : '||') + ')';
303
+ used.push(p.a, p.b);
304
+ const ds = unique([...p.a.deps, ...p.b.deps]), ready = rank ? Math.max(-1, ...ds.map(i => rank[i])) + 1 : 0;
305
+ const test = `(${this.ref(p.a)}${p.cmp === '=' ? '===' : p.cmp}${this.ref(p.b)})`;
306
+ return `(${rank && ready > 0 ? `d<${ready}||` : ''}${polarity ? test : '!' + test})`;
307
+ }
308
+ // Three-valued interval truth: -1=false, 0=unknown, 1=true. Only a
309
+ // definitely true target rules out its negation; intersecting bounds stay
310
+ // unknown. All generated code is built from closed operators and numbers.
311
+ compileIntervalFailure(p, readyAt) {
312
+ const lines = [], ranges = new Map(), truths = new WeakMap();
313
+ let chars = 0, next = 0;
314
+ const emit = (line) => {
315
+ checkWall('tiny interval code');
316
+ chars += line.length;
317
+ if (chars > 65_536)
318
+ throw new Unsupported('large interval screen');
319
+ lines.push(line);
320
+ };
321
+ const range = (t) => {
322
+ checkWall('tiny interval term');
323
+ if (t.lo < 0 || t.hi < t.lo)
324
+ throw new Unsupported('non-natural interval');
325
+ const hit = ranges.get(t.id);
326
+ if (hit)
327
+ return hit;
328
+ let lo = String(t.lo), hi = String(t.hi);
329
+ if (!t.args.length && t.deps.length === 1) {
330
+ const i = t.deps[0], ready = readyAt[i];
331
+ if (ready === undefined)
332
+ throw new Unsupported('missing interval readiness');
333
+ lo = `(d>=${ready}?v[${i}]:${lo})`;
334
+ hi = `(d>=${ready}?v[${i}]:${hi})`;
335
+ }
336
+ else if (t.choice) {
337
+ const c = truth(t.choice.c), a = range(t.choice.a), b = range(t.choice.b);
338
+ lo = `(${c}===1?${a.lo}:${c}===-1?${b.lo}:Math.min(${a.lo},${b.lo}))`;
339
+ hi = `(${c}===1?${a.hi}:${c}===-1?${b.hi}:Math.max(${a.hi},${b.hi}))`;
340
+ }
341
+ else if (t.arithmetic && t.args.length === 2) {
342
+ const a = range(t.args[0]), b = range(t.args[1]);
343
+ if (t.arithmetic === 'add') {
344
+ lo = `(${a.lo}+${b.lo})`;
345
+ hi = `(${a.hi}+${b.hi})`;
346
+ }
347
+ else if (t.arithmetic === 'sub') {
348
+ lo = `Math.max(0,${a.lo}-${b.hi})`;
349
+ hi = `Math.max(0,${a.hi}-${b.lo})`;
350
+ }
351
+ else if (t.arithmetic === 'prod') {
352
+ lo = `(${a.lo}*${b.lo})`;
353
+ hi = `(${a.hi}*${b.hi})`;
354
+ }
355
+ else if (t.arithmetic === 'min' || t.arithmetic === 'max') {
356
+ lo = `Math.${t.arithmetic}(${a.lo},${b.lo})`;
357
+ hi = `Math.${t.arithmetic}(${a.hi},${b.hi})`;
358
+ }
359
+ }
360
+ const out = { lo: `l${t.id}`, hi: `h${t.id}` };
361
+ emit(`const ${out.lo}=${lo},${out.hi}=${hi};`);
362
+ ranges.set(t.id, out);
363
+ return out;
364
+ };
365
+ const truth = (q) => {
366
+ checkWall('tiny interval predicate');
367
+ if (typeof q === 'boolean')
368
+ return q ? '1' : '-1';
369
+ const hit = truths.get(q);
370
+ if (hit)
371
+ return hit;
372
+ let code;
373
+ if (q.op === 'atom') {
374
+ const a = range(q.a), b = range(q.b);
375
+ const yes = q.cmp === '<' ? `${a.hi}<${b.lo}` : q.cmp === '<=' ? `${a.hi}<=${b.lo}` : `${a.lo}===${a.hi}&&${b.lo}===${b.hi}&&${a.lo}===${b.lo}`;
376
+ const no = q.cmp === '<' ? `${a.lo}>=${b.hi}` : q.cmp === '<=' ? `${a.lo}>${b.hi}` : `${a.hi}<${b.lo}||${b.hi}<${a.lo}`;
377
+ code = `((${yes})?1:(${no})?-1:0)`;
378
+ }
379
+ else if (q.op === 'not')
380
+ code = `(-${truth(q.x)})`;
381
+ else {
382
+ const xs = q.xs.map(truth), all = q.op === 'and', decisive = all ? -1 : 1, neutral = -decisive;
383
+ code = `((${xs.map(x => `${x}===${decisive}`).join('||') || 'false'})?${decisive}:(${xs.map(x => `${x}===${neutral}`).join('&&') || 'true'})?${neutral}:0)`;
384
+ }
385
+ const name = `b${next++}`;
386
+ emit(`const ${name}=${code};`);
387
+ truths.set(q, name);
388
+ return name;
389
+ };
390
+ const result = truth(p);
391
+ emit(`return ${result}!==1;`);
392
+ // oxlint-disable-next-line typescript/no-implied-eval
393
+ return new Function('v', 'd', lines.join(''));
394
+ }
395
+ compileValues(values, order) {
396
+ checkWall('tiny transition code');
397
+ const rank = order ? this.slots.map((_, i) => order.indexOf(i)) : undefined;
398
+ const seen = new Set(), lines = [];
399
+ let chars = 0;
400
+ const emit = (t) => {
401
+ checkWall('tiny transition terms');
402
+ if (seen.has(t.id))
403
+ return;
404
+ seen.add(t.id);
405
+ t.args.forEach(emit);
406
+ const ready = rank ? Math.max(-1, ...t.deps.map(i => rank[i])) + 1 : 0;
407
+ const line = `const t${t.id}=${ready > 0 ? `d>=${ready}?${t.code}:0` : t.code};`;
408
+ chars += line.length;
409
+ if (chars > 65_536)
410
+ throw new Unsupported('large transition screen');
411
+ lines.push(line);
412
+ };
413
+ values.forEach(emit);
414
+ // Only closed AST operators, validated numerical literals and slot indices;
415
+ // callback replay, never this generated transition, authorizes a CTI.
416
+ // oxlint-disable-next-line typescript/no-implied-eval
417
+ return new Function('v', 'd', `${lines.join('')}return [${values.map(t => this.ref(t)).join(',')}];`);
418
+ }
419
+ // Upper truth bound, not a two-valued evaluation of an incomplete state.
420
+ // true includes UNKNOWN; false rules out this polarity for every completion.
421
+ // In particular, polarity=false cannot prune on an unassigned atom.
422
+ compile(p, order, polarity = true, readyAt) {
423
+ checkWall('tiny generate screen');
424
+ // Keep native compilation and hot execution in bounded clauses rather
425
+ // than one giant predicate. Partial-assignment polarity is unchanged.
426
+ if (typeof p === 'boolean')
427
+ return () => p === polarity;
428
+ if (p.op === 'not')
429
+ return this.compile(p.x, order, !polarity, readyAt);
430
+ if (p.op === 'and' || p.op === 'or') {
431
+ if (!p.xs.length)
432
+ return () => (p.op === 'and') === polarity;
433
+ if (p.xs.length === 1)
434
+ return this.compile(p.xs[0], order, polarity, readyAt);
435
+ // Share the expression DAG inside one bounded native clause. Split only
436
+ // when the existing code-size cap demands it, not once per atomic test.
437
+ try {
438
+ return this.compileNative(p, order, polarity, readyAt);
439
+ }
440
+ catch (e) {
441
+ if (!(e instanceof Unsupported) || e.message !== 'large generated screen')
442
+ throw e;
443
+ }
444
+ const middle = Math.ceil(p.xs.length / 2), all = (p.op === 'and') === polarity;
445
+ const tests = [this.compile({ op: p.op, xs: p.xs.slice(0, middle) }, order, polarity, readyAt),
446
+ this.compile({ op: p.op, xs: p.xs.slice(middle) }, order, polarity, readyAt)];
447
+ return (v, depth) => {
448
+ for (const test of tests) {
449
+ checkWall('tiny predicate clause');
450
+ if (test(v, depth) !== all)
451
+ return !all;
452
+ }
453
+ return all;
454
+ };
455
+ }
456
+ return this.compileNative(p, order, polarity, readyAt);
457
+ }
458
+ compileNative(p, order, polarity = true, readyAt) {
459
+ checkWall('tiny native clause');
460
+ const rank = readyAt ? readyAt.map(depth => depth - 1) : order ? this.slots.map((_, i) => order.indexOf(i)) : undefined, used = [];
461
+ // An atomic predicate is unknown until ALL of its dependencies are set.
462
+ // Its old per-term placeholders could not affect that result, so return
463
+ // before evaluating the closed expression DAG instead. Once ready, every
464
+ // dependency of every prerequisite term is ready too.
465
+ const atomic = typeof p !== 'boolean' && p.op === 'atom';
466
+ const ready = rank && atomic ? Math.max(-1, ...depsOf(p).map(i => rank[i])) + 1 : 0;
467
+ const guard = ready > 0 ? `if(d<${ready})return true;` : '';
468
+ const code = this.predicateCode(p, atomic ? undefined : rank, used, polarity), seen = new Set(), lines = [];
469
+ let chars = guard.length + code.length;
470
+ if (chars > 65_536)
471
+ throw new Unsupported('large generated screen');
472
+ const emit = (t) => {
473
+ checkWall('tiny term code');
474
+ if (seen.has(t.id))
475
+ return;
476
+ seen.add(t.id);
477
+ t.args.forEach(emit);
478
+ const termReady = rank && !atomic ? Math.max(-1, ...t.deps.map(i => rank[i])) + 1 : 0;
479
+ const line = `const t${t.id}=${termReady > 0 ? `d>=${termReady}?${t.code}:0` : t.code};`;
480
+ chars += line.length;
481
+ if (chars > 65_536)
482
+ throw new Unsupported('large generated screen');
483
+ lines.push(line);
484
+ };
485
+ used.forEach(emit);
486
+ // Closed AST operators, validated numerical literals and slot indices only;
487
+ // no identifier or external function source is interpolated. This is an
488
+ // UNTRUSTED screen: the callback must independently replay every proposal.
489
+ // oxlint-disable-next-line typescript/no-implied-eval
490
+ return new Function('v', 'd', `${guard}${lines.join('')}return ${code};`);
491
+ }
492
+ }
493
+ const uniqueTerms = (ts) => [...new Map(ts.map(t => [t.id, t])).values()];
494
+ function bindings(names, domain, env) {
495
+ checkWall('tiny bindings');
496
+ if (!names.length)
497
+ return [env];
498
+ if (names.length > 5)
499
+ throw new Unsupported('many binders');
500
+ return domain.flatMap(k => bindings(names.slice(1), domain, { ...env, [names[0]]: k }));
501
+ }
502
+ // Structurally recover row addressing from COUNT BODIES, not names: one
503
+ // counted member plus a scaled row variable (or a native tuple of the two).
504
+ function gridKeys(m, size) {
505
+ const cells = {};
506
+ for (const [name] of Object.entries(m.maps ?? {}))
507
+ cells[name] = Array.from({ length: size }, (_, i) => i);
508
+ for (const d of Object.values(m.counts ?? {}))
509
+ walk(d.body, o => {
510
+ checkWall('tiny grid inference');
511
+ if (o.op !== 'get' || !Object.hasOwn(cells, String(o.map)))
512
+ return;
513
+ const key = o.key;
514
+ if (key.op === 'add') {
515
+ const [a, b] = key.a.op === 'mul' ? [key.a, key.b] : [key.b, key.a];
516
+ if (a.op === 'mul' && a.a.op === 'var' && b.op === 'var' && b.name === d.key && a.a.name !== d.key && a.k >= 1 && Number.isSafeInteger(a.k) && Number.isSafeInteger(a.k * size))
517
+ cells[String(o.map)] = unique([...(cells[String(o.map)] ?? []), ...Array.from({ length: size * size }, (_, i) => Math.floor(i / size) * a.k + i % size)]);
518
+ }
519
+ if (key.op === 'tup' && key.a.op === 'var' && key.b.op === 'var' && (key.a.name === d.key || key.b.name === d.key))
520
+ cells[String(o.map)] = unique([...(cells[String(o.map)] ?? []), ...Array.from({ length: size * size }, (_, i) => cpair(Math.floor(i / size), i % size))]);
521
+ });
522
+ return cells;
523
+ }
524
+ function tinyScope(params, stateValues, options) {
525
+ return { params: { ...params }, scalarValues: [...stateValues], cellValues: [...stateValues], cells: {}, inputValues: {}, inputCells: {}, binderValues: [], postTargetPruning: options.postTargetPruning === true, postTargetIntervals: options.postTargetIntervals === true, seedNeighborhood: options.seedTransitions !== undefined, seedUniformMaps: options.seedTransitions !== undefined && options.seedUniformMaps === true };
526
+ }
527
+ function tinyLayout(source, m, params, stateValues, scope) {
528
+ checkWall('tiny start');
529
+ if (!stateValues.length || stateValues.length > 4 || stateValues.some(n => !Number.isSafeInteger(n) || n < 0))
530
+ throw new Unsupported('invalid finite value domain');
531
+ if (source.history || source.leasts || source.sums)
532
+ throw new Unsupported('history/least/sums');
533
+ if (!source.params.every(p => Number.isSafeInteger(params[p]) && params[p] >= 0))
534
+ throw new Unsupported('missing/non-natural params');
535
+ // The finite dimension comes from a parameter-only count bound. No
536
+ // parameter name is significant. Ambiguous bounds use the largest one.
537
+ const bounds = Object.values(m.counts ?? {}).flatMap(d => d.below.op === 'var' && Object.hasOwn(params, d.below.name) ? [params[d.below.name]] : d.below.op === 'const' ? [d.below.value] : []);
538
+ const size = Math.max(0, ...bounds);
539
+ if (size < 1 || size > 4)
540
+ throw new Unsupported('count grid bound outside 1..4');
541
+ scope.cells = gridKeys(m, size);
542
+ scope.binderValues = Array.from({ length: size }, (_, i) => i);
543
+ const slots = Object.keys(source.state).map(name => ({ name, values: stateValues }));
544
+ for (const name of Object.keys(source.maps ?? {}))
545
+ for (const key of scope.cells[name] ?? []) {
546
+ checkWall('tiny state coordinates');
547
+ slots.push({ name, key, values: stateValues });
548
+ }
549
+ const stateSlots = slots.length;
550
+ for (const name of source.inputs) {
551
+ checkWall('tiny request domains');
552
+ // Explicit conjunctive natural bounds are domain hints; other inputs use
553
+ // 0..size. No domain or quotient is a trusted pruning justification.
554
+ let hi = 16, bounded = false;
555
+ for (const c of conjuncts(source.assume ?? { op: 'and', xs: [] })) {
556
+ checkWall('tiny numeric bounds');
557
+ if ((c.op === '<' || c.op === '<=') && c.a.op === 'var' && c.a.name === name) {
558
+ const b = c.b.op === 'const' ? c.b.value : c.b.op === 'var' ? params[c.b.name] : undefined;
559
+ if (b !== undefined) {
560
+ hi = Math.min(hi, b - Number(c.op === '<'));
561
+ bounded = true;
562
+ }
563
+ }
564
+ }
565
+ if (!bounded)
566
+ hi = size;
567
+ if (!Number.isSafeInteger(hi) || hi < 0 || hi > 16)
568
+ throw new Unsupported('request domain');
569
+ const values = Array.from({ length: hi + 1 }, (_, i) => i);
570
+ scope.inputValues[name] = values;
571
+ slots.push({ name, request: true, values });
572
+ }
573
+ for (const name of source.inputMaps ?? []) {
574
+ checkWall('tiny carried coordinates');
575
+ scope.inputCells[name] = Array.from({ length: size }, (_, i) => i);
576
+ for (const key of scope.inputCells[name])
577
+ slots.push({ name, key, request: true, values: [0, 1] });
578
+ }
579
+ if (slots.length > 64)
580
+ throw new Unsupported('more than 64 tiny coordinates');
581
+ return { slots, stateSlots };
582
+ }
583
+ function materializeTiny(source, slots, values, fixed = {}) {
584
+ const preState = { scalars: {}, maps: Object.fromEntries(Object.keys(source.maps ?? {}).map(name => [name, new Map()])) };
585
+ const request = Object.fromEntries((source.inputMaps ?? []).map(name => [name, new Map()]));
586
+ for (let i = 0; i < slots.length; i++) {
587
+ checkWall('tiny candidate materialization');
588
+ const s = slots[i], value = s.request && s.key === undefined && Object.hasOwn(fixed, s.name) ? fixed[s.name] : values[i];
589
+ if (s.request) {
590
+ if (s.key === undefined)
591
+ request[s.name] = value;
592
+ else
593
+ request[s.name].set(s.key, value);
594
+ }
595
+ else if (s.key === undefined)
596
+ preState.scalars[s.name] = value;
597
+ else
598
+ preState.maps[s.name].set(s.key, value);
599
+ }
600
+ return { pre: preState, request };
601
+ }
602
+ function walkTinySeedVectors(source, params, slots, options, visit) {
603
+ const bases = [], seen = new Set();
604
+ let attempts = 0;
605
+ for (const seed of options.seedTransitions?.slice(-8) ?? []) {
606
+ checkWall('tiny seed projection');
607
+ if (!Object.keys(params).every(key => seed.params[key] === params[key]))
608
+ continue;
609
+ const values = [];
610
+ for (const slot of slots) {
611
+ const entry = slot.request ? seed.request[slot.name] : seed.pre.scalars[slot.name];
612
+ const value = slot.key === undefined ? entry : slot.request
613
+ ? entry instanceof Map ? entry.get(slot.key) ?? 0 : undefined
614
+ : seed.pre.maps[slot.name]?.get(slot.key) ?? seed.pre.defaults?.[slot.name] ?? source.maps?.[slot.name];
615
+ if (typeof value !== 'number' || !slot.values.includes(value))
616
+ break;
617
+ values.push(value);
618
+ }
619
+ if (values.length === slots.length)
620
+ bases.push(values);
621
+ }
622
+ const attempt = (values, coupled = false) => {
623
+ checkWall('tiny seed attempt');
624
+ if (attempts >= 256)
625
+ return false;
626
+ const key = values.join(',');
627
+ if (seen.has(key))
628
+ return true;
629
+ seen.add(key);
630
+ attempts++;
631
+ visit(values, coupled);
632
+ return true;
633
+ };
634
+ for (const base of bases)
635
+ if (!attempt(base))
636
+ return;
637
+ if (options.seedUniformMaps) {
638
+ const grouped = new Map();
639
+ for (const [i, slot] of slots.entries()) {
640
+ checkWall('tiny seed map grouping');
641
+ if (slot.key === undefined)
642
+ continue;
643
+ const key = `${Number(!!slot.request)}:${slot.name}`, group = grouped.get(key) ?? [];
644
+ group.push(i);
645
+ grouped.set(key, group);
646
+ }
647
+ const groups = [...grouped.values()].filter(group => group.length > 1)
648
+ .sort((a, b) => Number(!!slots[b[0]].request) - Number(!!slots[a[0]].request));
649
+ for (const group of groups)
650
+ for (const base of bases)
651
+ for (const value of slots[group[0]].values) {
652
+ checkWall('tiny seed uniform map');
653
+ if (!group.every(i => slots[i].values.includes(value)) || group.every(i => base[i] === value))
654
+ continue;
655
+ const values = base.slice();
656
+ for (const i of group)
657
+ values[i] = value;
658
+ if (!attempt(values, true))
659
+ return;
660
+ }
661
+ }
662
+ // Request axes first; round-robin across seeds avoids one long seed
663
+ // neighborhood consuming the entire fixed attempt allowance.
664
+ const axes = [...slots.keys()].sort((a, b) => Number(!!slots[b].request) - Number(!!slots[a].request) || a - b);
665
+ for (const i of axes)
666
+ for (const base of bases)
667
+ for (const value of slots[i].values) {
668
+ checkWall('tiny seed neighbor');
669
+ if (value === base[i])
670
+ continue;
671
+ const values = base.slice();
672
+ values[i] = value;
673
+ if (!attempt(values))
674
+ return;
675
+ }
676
+ }
677
+ // Cheap finite-grid proposals only: no predicates or native transition code are
678
+ // compiled. The supplied checker must establish every removal independently.
679
+ export function tinySeedCandidates(source, m, params, onCandidate, options = {}) {
680
+ const values = unique([...(options.valueDomain ?? [0, 1])]).sort((a, b) => a - b), start = performance.now();
681
+ const stats = { phase: 'seed-only', scope: tinyScope(params, values, options), completed: false, timedOut: false,
682
+ unsupported: [], models: 0, accepted: 0, coupledModels: 0, coupledAccepted: 0, ms: 0 };
683
+ try {
684
+ const { slots } = tinyLayout(source, m, params, values, stats.scope);
685
+ walkTinySeedVectors(source, params, slots, options, (vector, coupled) => {
686
+ stats.models++;
687
+ if (coupled)
688
+ stats.coupledModels++;
689
+ const { pre, request } = materializeTiny(source, slots, vector);
690
+ if (onCandidate(pre, request)) {
691
+ stats.accepted++;
692
+ if (coupled)
693
+ stats.coupledAccepted++;
694
+ }
695
+ });
696
+ stats.completed = true;
697
+ }
698
+ catch (e) {
699
+ if (e instanceof WallExpired)
700
+ stats.timedOut = true;
701
+ else if (e instanceof Unsupported)
702
+ stats.unsupported.push(e.message);
703
+ else
704
+ throw e;
705
+ }
706
+ finally {
707
+ stats.ms = performance.now() - start;
708
+ }
709
+ return stats;
710
+ }
711
+ /** A deliberately small heuristic scope: binary source scalars/cells by default,
712
+ * count-bound-sized rows and Boolean carried sets. Unsupported syntax is
713
+ * unknown. completed means this recorded finite SCREEN traversal finished;
714
+ * exhausted additionally means it emitted no proposals. Neither establishes
715
+ * validity, reachability, or a complete universal cover.
716
+ * Callback false rejects a proposal and resumes that search; void/true stops
717
+ * that target at its first proposal. Neither outcome authorizes a drop.
718
+ * WallExpired is caught to return partial statistics; an expired parent wall
719
+ * remains expired, and consumers must immediately check their own checkWall.
720
+ */
721
+ export function tinyFiniteCandidates(source, m, family, params, onCandidate, options = {}) {
722
+ const stateValues = unique([...(options.valueDomain ?? [0, 1])]).sort((a, b) => a - b);
723
+ const start = performance.now(), scope = tinyScope(params, stateValues, options);
724
+ const stats = { scope, completed: false, exhausted: false, timedOut: false, unsupported: [], nodes: 0, states: 0, steps: 0, scenarios: 0, candidates: 0, postStatePrunes: 0, postRequestPrunes: 0, postIntervalFallbacks: 0, seedModels: 0, seedCandidates: 0, seedCoupledModels: 0, seedCoupledCandidates: 0, ms: 0 };
725
+ const unknown = (e) => { const reason = e instanceof Error ? e.message : String(e); if (!stats.unsupported.includes(reason))
726
+ stats.unsupported.push(reason); };
727
+ try {
728
+ const { slots, stateSlots } = tinyLayout(source, m, params, stateValues, scope);
729
+ const compiler = new Compiler(source, m, params, slots, scope.cells, scope.binderValues);
730
+ const pres = [];
731
+ if (source.pre)
732
+ pres.push(compiler.condition(source.pre, params));
733
+ const instances = new Map();
734
+ for (const law of family) {
735
+ checkWall('tiny family compile');
736
+ if (law.some?.length) {
737
+ unknown(new Unsupported('existential law'));
738
+ continue;
739
+ }
740
+ if ([law.forall, ...law.keys ?? []].some(k => k !== undefined && (k in source.state || source.params.includes(k) || source.inputs.includes(k)))) {
741
+ unknown(new Unsupported('shadowing law binder'));
742
+ continue;
743
+ }
744
+ try {
745
+ const ats = bindings(uniqueNames([law.forall, ...law.keys ?? []]), scope.binderValues, params);
746
+ const ps = ats.map(at => compiler.condition(law.holds, at));
747
+ pres.push(...ps);
748
+ instances.set(law, ats);
749
+ }
750
+ catch (e) {
751
+ if (e instanceof WallExpired)
752
+ throw e;
753
+ unknown(e);
754
+ }
755
+ }
756
+ const pre = conjunction(pres);
757
+ if (pre === false) {
758
+ stats.completed = stats.exhausted = stats.unsupported.length === 0;
759
+ return stats;
760
+ }
761
+ // An input compared with several constants is a structural dispatch
762
+ // coordinate. Closing it before compilation folds inactive branches and
763
+ // quotients request coordinates irrelevant to that operation slice.
764
+ const dispatches = new Map();
765
+ walk(source.step, o => {
766
+ checkWall('tiny dispatch inference');
767
+ if (o.op !== '=')
768
+ return;
769
+ const a = o.a, b = o.b;
770
+ const [v, k] = a.op === 'var' ? [a, b] : [b, a];
771
+ if (v.op === 'var' && k.op === 'const' && source.inputs.includes(v.name)) {
772
+ const set = dispatches.get(v.name) ?? new Set();
773
+ set.add(k.value);
774
+ dispatches.set(v.name, set);
775
+ }
776
+ });
777
+ const dispatch = [...dispatches].filter(([, ks]) => ks.size > 1).sort((a, b) => b[1].size - a[1].size)[0]?.[0];
778
+ const slices = dispatch ? scope.inputValues[dispatch].map(value => ({ ...params, [dispatch]: value })) : [params];
779
+ const emitted = new Set(), highs = slots.map(s => Math.max(...s.values));
780
+ const writeFlags = new Set();
781
+ walk([source.step.state, source.step.maps], o => { checkWall('tiny write flags'); if (o.op === 'flag')
782
+ writeFlags.add(o.name); });
783
+ const slotValue = (c, i, env, post) => {
784
+ const s = slots[i];
785
+ return s.key === undefined ? c.expression({ op: 'var', name: s.name }, env, post) : c.read(s.name, s.key, env, post, []);
786
+ };
787
+ // Guard pruning is used only after a structural, finite-screen identity
788
+ // check with every write-referenced flag false. This is NOT trusted by Main.
789
+ let inactiveIdentity = false;
790
+ try {
791
+ const off = new Compiler(source, m, params, slots, scope.cells, scope.binderValues);
792
+ off.flagConstants = new Map([...writeFlags].map(name => [name, false]));
793
+ inactiveIdentity = slots.slice(0, stateSlots).every((_, i) => slotValue(off, i, params, true).id === off.slot(i).id);
794
+ }
795
+ catch (e) {
796
+ if (e instanceof WallExpired)
797
+ throw e;
798
+ if (!(e instanceof Unsupported))
799
+ throw e;
800
+ }
801
+ const flatPreds = (p) => typeof p !== 'boolean' && p.op === 'and' ? p.xs.flatMap(flatPreds) : [p];
802
+ const operations = [];
803
+ for (const fixed of slices) {
804
+ checkWall('tiny operation compile');
805
+ try {
806
+ const outputs = slots.slice(0, stateSlots).map((_, i) => slotValue(compiler, i, fixed, true));
807
+ if (outputs.every((t, i) => t.id === compiler.slot(i).id))
808
+ continue;
809
+ const active = inactiveIdentity && writeFlags.size ? disjunction([...writeFlags].map(name => compiler.condition({ op: 'flag', name }, fixed))) : true;
810
+ const enabled = conjunction([source.assume ? compiler.condition(source.assume, fixed) : true, active]);
811
+ if (enabled === false)
812
+ continue;
813
+ const relevant = new Set([...depsOf(enabled), ...outputs.flatMap(t => t.deps)]);
814
+ const clauses = flatPreds(enabled).map(depsOf);
815
+ const degrees = slots.map((_, i) => clauses.reduce((sum, ds) => sum + (ds.includes(i) ? 1 / Math.max(1, ds.length) : 0), 0));
816
+ const order = slots.map((_, i) => i).filter(i => i >= stateSlots && relevant.has(i)).sort((a, b) => degrees[b] - degrees[a] || a - b);
817
+ operations.push({ fixed, order, gate: compiler.compile(enabled, order), step: compiler.compileValues(outputs), outputs });
818
+ outputs.forEach((t, i) => { checkWall('tiny post ranges'); highs[i] = Math.max(highs[i], t.hi); });
819
+ stats.scenarios++;
820
+ }
821
+ catch (e) {
822
+ if (e instanceof WallExpired)
823
+ throw e;
824
+ unknown(e);
825
+ }
826
+ }
827
+ const postSlots = slots.map((s, i) => i < stateSlots ? { ...s, values: unique([...s.values, highs[i]]) } : s);
828
+ const postCompiler = new Compiler(source, m, params, postSlots, scope.cells, scope.binderValues);
829
+ const targets = [], predicates = [];
830
+ for (const [law, ats] of instances) {
831
+ checkWall('tiny shared post predicates');
832
+ try {
833
+ const p = conjunction(ats.map(at => postCompiler.condition(law.holds, at)));
834
+ if (p === true)
835
+ continue;
836
+ targets.push(law);
837
+ predicates.push(p);
838
+ }
839
+ catch (e) {
840
+ if (e instanceof WallExpired)
841
+ throw e;
842
+ unknown(e);
843
+ }
844
+ }
845
+ if (!operations.length || !targets.length) {
846
+ stats.completed = stats.exhausted = stats.unsupported.length === 0;
847
+ return stats;
848
+ }
849
+ const postTests = predicates.map(p => postCompiler.compile(p)), preDeps = pres.map(depsOf);
850
+ const degrees = slots.map((_, i) => preDeps.reduce((sum, ds) => sum + (ds.includes(i) ? 1 / Math.max(1, ds.length) : 0), 0));
851
+ const stateOrder = slots.slice(0, stateSlots).map((_, i) => i).sort((a, b) => degrees[b] - degrees[a] || a - b);
852
+ const preTest = compiler.compile(pre, stateOrder), v = slots.map(s => s.values[0]);
853
+ if (options.postTargetPruning)
854
+ for (const op of operations) {
855
+ checkWall('tiny post-target circuit');
856
+ try {
857
+ const order = [...stateOrder, ...op.order], rank = slots.map((_, i) => order.indexOf(i));
858
+ // A post coordinate is unknown until every source dependency of its
859
+ // output is assigned. Distinct outputs need not become ready together.
860
+ const readyAt = slots.map((_, i) => i < stateSlots ? Math.max(-1, ...op.outputs[i].deps.map(j => rank[j])) + 1 : rank[i] + 1);
861
+ const changed = new Set(op.outputs.flatMap((t, i) => t.id === compiler.slot(i).id ? [] : [i]));
862
+ const needed = new Set(), screens = [];
863
+ for (const [i, law] of targets.entries()) {
864
+ checkWall('tiny post-target predicate');
865
+ const p = predicates[i], deps = depsOf(p);
866
+ // Unchanged primitive dependencies preserve this full-family law.
867
+ if (!deps.some(j => changed.has(j)))
868
+ continue;
869
+ deps.forEach(j => needed.add(j));
870
+ try {
871
+ let mayFail;
872
+ if (options.postTargetIntervals) {
873
+ try {
874
+ mayFail = postCompiler.compileIntervalFailure(p, readyAt);
875
+ }
876
+ catch (e) {
877
+ if (e instanceof WallExpired)
878
+ throw e;
879
+ if (!(e instanceof Unsupported))
880
+ throw e;
881
+ stats.postIntervalFallbacks++;
882
+ mayFail = postCompiler.compile(p, undefined, false, readyAt);
883
+ }
884
+ }
885
+ else
886
+ mayFail = postCompiler.compile(p, undefined, false, readyAt);
887
+ screens.push({ law, mayFail });
888
+ }
889
+ catch (e) {
890
+ if (e instanceof WallExpired)
891
+ throw e;
892
+ if (!(e instanceof Unsupported))
893
+ throw e;
894
+ unknown(e);
895
+ screens.push({ law, mayFail: () => true });
896
+ }
897
+ }
898
+ // Share one let-bound output DAG instead of distributing each source
899
+ // conditional through every target. Placeholder zeroes are never read
900
+ // by a known atom until its readyAt depth has been reached.
901
+ const partial = compiler.compileValues(op.outputs.map((t, i) => needed.has(i) ? t : compiler.constant(0)), order);
902
+ op.mayFail = (values, depth) => {
903
+ if (!screens.some(screen => !emitted.has(screen.law)))
904
+ return false;
905
+ const post = partial(values, depth);
906
+ for (let i = stateSlots; i < slots.length; i++) {
907
+ const slot = slots[i];
908
+ post[i] = slot.key === undefined && Object.hasOwn(op.fixed, slot.name) ? op.fixed[slot.name] : rank[i] < 0 ? slot.values[0] : values[i];
909
+ }
910
+ return screens.some(screen => !emitted.has(screen.law) && screen.mayFail(post, depth));
911
+ };
912
+ }
913
+ catch (e) {
914
+ if (e instanceof WallExpired)
915
+ throw e;
916
+ if (!(e instanceof Unsupported))
917
+ throw e;
918
+ unknown(e);
919
+ op.mayFail = () => true;
920
+ }
921
+ }
922
+ const propose = (fixed, violated) => {
923
+ const { pre: preState, request } = materializeTiny(source, slots, v, fixed);
924
+ const accepted = onCandidate(preState, request, violated);
925
+ stats.candidates++;
926
+ if (accepted !== false)
927
+ for (const law of violated) {
928
+ checkWall('tiny proposed targets');
929
+ emitted.add(law);
930
+ }
931
+ };
932
+ const visit = () => {
933
+ stats.states++;
934
+ checkWall('tiny lawful state');
935
+ for (const op of operations) {
936
+ checkWall('tiny operation slice');
937
+ for (let i = stateSlots; i < slots.length; i++)
938
+ v[i] = slots[i].values[0];
939
+ for (const name of source.inputs)
940
+ if (Object.hasOwn(op.fixed, name))
941
+ v[slots.findIndex(s => s.request && s.key === undefined && s.name === name)] = op.fixed[name];
942
+ const requests = (d) => {
943
+ stats.nodes++;
944
+ checkWall('tiny request assignment');
945
+ if (!op.gate(v, d))
946
+ return;
947
+ if (op.mayFail && !op.mayFail(v, stateOrder.length + d)) {
948
+ stats.postRequestPrunes++;
949
+ return;
950
+ }
951
+ if (d < op.order.length) {
952
+ const i = op.order[d];
953
+ for (const value of slots[i].values) {
954
+ checkWall('tiny request values');
955
+ v[i] = value;
956
+ requests(d + 1);
957
+ }
958
+ return;
959
+ }
960
+ const values = op.step(v);
961
+ if (values.every((value, i) => value === v[i]))
962
+ return;
963
+ stats.steps++;
964
+ const post = v.slice();
965
+ for (let i = 0; i < stateSlots; i++)
966
+ post[i] = values[i];
967
+ const violated = targets.filter((law, i) => !emitted.has(law) && !postTests[i](post, 0));
968
+ if (violated.length)
969
+ propose(op.fixed, violated);
970
+ };
971
+ requests(0);
972
+ }
973
+ };
974
+ const states = (d) => {
975
+ stats.nodes++;
976
+ checkWall('tiny state assignment');
977
+ if (!preTest(v, d))
978
+ return;
979
+ if (options.postTargetPruning && operations.every(op => !op.mayFail(v, d))) {
980
+ stats.postStatePrunes++;
981
+ return;
982
+ }
983
+ if (d === stateOrder.length) {
984
+ visit();
985
+ return;
986
+ }
987
+ const i = stateOrder[d];
988
+ // Ones first reaches enabled guards early; both values remain enumerated.
989
+ for (const value of [...slots[i].values].reverse()) {
990
+ checkWall('tiny state values');
991
+ v[i] = value;
992
+ states(d + 1);
993
+ }
994
+ };
995
+ // A seed is only an untrusted coordinate suggestion, never a drop. Project
996
+ // the last eight into this exact finite grid, try radius-one neighbors,
997
+ // then retain the ordinary full traversal. Every proposal uses the same
998
+ // independent callback. Snapshot before callbacks can add later seeds.
999
+ if (options.seedTransitions)
1000
+ walkTinySeedVectors(source, params, slots, options, (values, coupled) => {
1001
+ stats.seedModels++;
1002
+ stats.nodes++;
1003
+ if (coupled)
1004
+ stats.seedCoupledModels++;
1005
+ for (let i = 0; i < values.length; i++)
1006
+ v[i] = values[i];
1007
+ if (!preTest(v, stateOrder.length))
1008
+ return;
1009
+ for (const op of operations) {
1010
+ checkWall('tiny seed operation');
1011
+ if (slots.some((s, i) => s.request && s.key === undefined && Object.hasOwn(op.fixed, s.name) && v[i] !== op.fixed[s.name]))
1012
+ continue;
1013
+ if (!op.gate(v, op.order.length))
1014
+ continue;
1015
+ const outputs = op.step(v);
1016
+ if (outputs.every((value, i) => value === v[i]))
1017
+ continue;
1018
+ stats.steps++;
1019
+ const post = v.slice();
1020
+ for (let i = 0; i < stateSlots; i++)
1021
+ post[i] = outputs[i];
1022
+ const violated = targets.filter((law, i) => !emitted.has(law) && !postTests[i](post, 0));
1023
+ if (violated.length) {
1024
+ stats.seedCandidates++;
1025
+ if (coupled)
1026
+ stats.seedCoupledCandidates++;
1027
+ propose(op.fixed, violated);
1028
+ }
1029
+ }
1030
+ });
1031
+ for (let i = 0; i < slots.length; i++)
1032
+ v[i] = slots[i].values[0];
1033
+ states(0);
1034
+ // completed records traversal even when proposals were emitted; exhausted
1035
+ // additionally records a proposal-free screen, never semantic validity.
1036
+ stats.completed = stats.unsupported.length === 0;
1037
+ stats.exhausted = stats.completed && stats.candidates === 0;
1038
+ }
1039
+ catch (e) {
1040
+ if (e instanceof WallExpired)
1041
+ stats.timedOut = true;
1042
+ else if (e instanceof Unsupported)
1043
+ unknown(e);
1044
+ else
1045
+ throw e;
1046
+ }
1047
+ finally {
1048
+ stats.ms = performance.now() - start;
1049
+ }
1050
+ return stats;
1051
+ }
1052
+ const uniqueNames = (xs) => [...new Set(xs.filter((x) => x !== undefined))];