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,2080 @@
1
+ // Private untrusted count-candidate scheduling. Every emitted tuple instantiates a whole
2
+ // original PRE law; every CountInst is reified by mcGoal and the final closed family is
3
+ // checked by checkCountedLaws. No coordinate projection is an equality premise.
4
+ import { x } from "./machine.js";
5
+ import { linOfE, canon } from "./solver.js";
6
+ import { substC, substE, mcGoal, countedObligations } from "../kernel/kernel.js";
7
+ import { certFor } from "./counts.js";
8
+ import { wallAt } from "../kernel/prove.js";
9
+ import { memberInclusions } from "./count-recovery/member-inclusions.js";
10
+ export class UnsupportedCountProposal extends Error {
11
+ }
12
+ const json = (v) => JSON.stringify(v);
13
+ const sourceNames = (v, check) => {
14
+ const out = new Set();
15
+ const visit = (v) => {
16
+ check?.();
17
+ if (typeof v === 'string') {
18
+ out.add(v);
19
+ return;
20
+ }
21
+ if (!v || typeof v !== 'object')
22
+ return;
23
+ for (const [k, x] of Object.entries(v)) {
24
+ out.add(k);
25
+ visit(x);
26
+ }
27
+ };
28
+ visit(v);
29
+ return out;
30
+ };
31
+ const names = (v, check) => {
32
+ const out = new Set();
33
+ const visit = (v) => { check?.(); if (!v || typeof v !== 'object')
34
+ return; const o = v; if (o.op === 'var')
35
+ out.add(String(o.name)); for (const x of Object.values(o))
36
+ visit(x); };
37
+ visit(v);
38
+ return out;
39
+ };
40
+ const mentions = (v, n) => names(v).has(n);
41
+ const vars = (l) => [l.forall, ...(l.keys ?? [])].filter((n) => !!n);
42
+ const keyless = (d) => genuinelyKeyless(d);
43
+ // Only commutativity is used here. Keep the original full premise in the
44
+ // certificate; this key merely avoids spending source slots twice on it.
45
+ const premiseKey = (c) => c.op === 'and' || c.op === 'or'
46
+ ? json([c.op, c.xs.map(premiseKey).sort((a, b) => a.localeCompare(b))])
47
+ : c.op === 'not' ? json(['not', premiseKey(c.x)])
48
+ : c.op === '=' ? json(['=', [json(c.a), json(c.b)].sort((a, b) => a.localeCompare(b))]) : json(c);
49
+ const duplicateTerm = (law, old, tuple) => {
50
+ if (!law || !tuple.length || old.length % tuple.length)
51
+ return false;
52
+ const ns = vars(law), key = (ts) => premiseKey(substC(law.holds, { vars: Object.fromEntries(ns.map((n, i) => [n, ts[i]])), maps: {}, flags: {} })), wanted = key(tuple);
53
+ for (let i = 0; i < old.length; i += tuple.length)
54
+ if (key(old.slice(i, i + tuple.length)) === wanted)
55
+ return true;
56
+ return false;
57
+ };
58
+ // Instance changes matter to a count-read pool only when their law/flag can
59
+ // introduce a count read. Follow flag references to a fixed point, including
60
+ // reads under quantified flags; primitive flags must not invalidate the pool.
61
+ // A proposal cache depends on exact raw count-read spellings and definitions,
62
+ // not on which PRE tuple first exposed an already-present read. A hit never
63
+ // reuses a verdict: reservation and reification still inspect the current goal.
64
+ export function countPoolKey(goal, decls) {
65
+ const maps = new Set(decls.map(d => d.map)), reads = readTuples(goal.hyps).filter(([map]) => maps.has(map)).map(read => json(read)).sort();
66
+ return json([decls, reads, goal.hyps.at(-1)]);
67
+ }
68
+ export function countedInstanceSources(m, laws) {
69
+ const analyze = (value) => {
70
+ let count = false;
71
+ const flags = new Set();
72
+ const visit = (v) => {
73
+ if (!v || typeof v !== 'object')
74
+ return;
75
+ const o = v;
76
+ if (o.op === 'get' && typeof o.map === 'string' && Object.hasOwn(m.counts ?? {}, o.map))
77
+ count = true;
78
+ if (o.op === 'flag' && typeof o.name === 'string')
79
+ flags.add(o.name);
80
+ for (const x of Object.values(o))
81
+ visit(x);
82
+ };
83
+ visit(value);
84
+ return { count, flags };
85
+ };
86
+ const defs = Object.entries(m.step.flags ?? {}).map(([name, c]) => ({ name, ...analyze(c) })), counted = new Set();
87
+ let changed = true;
88
+ while (changed) {
89
+ changed = false;
90
+ for (const d of defs)
91
+ if (!counted.has(d.name) && (d.count || [...d.flags].some(f => counted.has(f)))) {
92
+ counted.add(d.name);
93
+ changed = true;
94
+ }
95
+ }
96
+ const out = new Set([...counted].map(f => '?' + f));
97
+ for (const l of laws) {
98
+ const d = analyze(l.holds);
99
+ if (d.count || [...d.flags].some(f => counted.has(f)))
100
+ out.add(l.name);
101
+ }
102
+ return out;
103
+ }
104
+ export function readTuples(value, more) {
105
+ const found = new Map();
106
+ const walk = (o) => {
107
+ if (more && !more())
108
+ return false;
109
+ if (!o || typeof o !== 'object')
110
+ return true;
111
+ const p = o;
112
+ if (p.op === 'all')
113
+ return true; // No reads under an uninstantiated local binder.
114
+ if (p.op === 'get')
115
+ found.set(json([p.map, p.key]), [p.map, p.key]);
116
+ for (const v of Object.values(p))
117
+ if (!walk(v))
118
+ return false;
119
+ return true;
120
+ };
121
+ walk(value);
122
+ return [...found.values()];
123
+ }
124
+ export const keyId = (e) => { const l = linOfE(e); return l ? 'lin:' + canon(l) : json(e); };
125
+ const readKey = (map, key) => json([map, keyId(key)]);
126
+ function bodyAt(d, r) {
127
+ let vars;
128
+ if (d.base) {
129
+ if (r[2].op !== 'add' || r[2].a.op !== 'mul' || r[2].a.k !== d.base || !d.lo)
130
+ return;
131
+ vars = { [d.j]: r[2].a.a, [d.lo]: r[2].b };
132
+ }
133
+ else
134
+ vars = { [d.j]: r[2] };
135
+ vars[d.key] = { op: 'var', name: '$body-witness' }; // canonical binder, never emitted into a goal
136
+ return { body: substE(d.body, { vars, maps: {}, flags: {} }), below: substE(d.below, { vars, maps: {}, flags: {} }) };
137
+ }
138
+ // A proposal-work ceiling, not additional proof/search time. The real wall is
139
+ // checked because pure JS enumeration does not advance the counted clock.
140
+ // Laws are immutable during one attempt. Only fully traversed patterns are cached;
141
+ // a hit is still metered, and a different meter never inherits another attempt's work.
142
+ const patternIndices = new WeakMap();
143
+ function lawReads(l, more) {
144
+ const cache = more && patternIndices.get(more)?.laws, cached = cache?.get(l);
145
+ if (cached)
146
+ return more() ? cached : [];
147
+ let complete = true;
148
+ const reads = readTuples(l.holds, more ? () => { const ok = more(); if (!ok)
149
+ complete = false; return ok; } : undefined);
150
+ if (complete)
151
+ cache?.set(l, reads);
152
+ return reads;
153
+ }
154
+ export function candidateWork() {
155
+ const state = { work: 0, limit: 65_536, exhausted: false, deadline: false, phases: [], omittedPhases: 0 };
156
+ const tick = () => {
157
+ if (state.exhausted || state.deadline)
158
+ return false;
159
+ if (performance.now() >= wallAt()) {
160
+ state.deadline = true;
161
+ return false;
162
+ }
163
+ if (state.work >= state.limit) {
164
+ state.exhausted = true;
165
+ return false;
166
+ }
167
+ state.work++;
168
+ return true;
169
+ };
170
+ const mark = (phase) => { if (state.phases.length < 128)
171
+ state.phases = [...state.phases, { phase, work: state.work }];
172
+ else
173
+ state.omittedPhases++; };
174
+ patternIndices.set(tick, { laws: new WeakMap() });
175
+ return { state, tick, mark };
176
+ }
177
+ export function grammarPool(goal, decls, cap = 1000, budget = candidateWork(), structured = true, m) {
178
+ const more = budget.tick;
179
+ budget.mark('pool:begin');
180
+ const base = certFor(goal, decls, true, cap, more, structured), byMap = new Map(decls.map(d => [d.map, d])), byRead = new Map(base.reads.map(r => [r[0], r])), insts = [...base.insts], wits = [...base.wits];
181
+ const added = [], proposed = [];
182
+ let omittedProvenance = 0;
183
+ const semantic = (i) => json([i.terms.map(([k, r]) => [k, byRead.get(r)?.slice(1)]), i.unit, keyId(i.below)]), had = new Set(insts.map(semantic)), taken = names([goal, decls, insts]);
184
+ let serial = insts.length;
185
+ const add = (i, reason, links) => {
186
+ if (insts.length >= cap || !more())
187
+ return;
188
+ const id = semantic(i);
189
+ if (had.has(id))
190
+ return;
191
+ const detail = proposed.length < 128 ? links?.() : undefined;
192
+ if (proposed.length < 128)
193
+ proposed.push({ candidate: i, reason, links: detail, capped: false });
194
+ else
195
+ omittedProvenance++;
196
+ let wit;
197
+ do {
198
+ wit = 'w$' + serial++;
199
+ } while (taken.has(wit));
200
+ taken.add(wit);
201
+ const instance = { ...i, wit };
202
+ insts.push(instance);
203
+ wits.push(wit);
204
+ had.add(id);
205
+ added.push({ instance, reason, ...(detail === undefined ? {} : { links: detail }) });
206
+ };
207
+ budget.mark('pool:base');
208
+ // A conditional member inclusion is an ordinary count witness disjunction,
209
+ // not a guarded arithmetic premise. The main lazy loop must see it before
210
+ // returning a model. Reuse this pool's cap, semantic dedup and fresh names.
211
+ if (structured && m?.inputMaps?.length && insts.length < cap && more()) {
212
+ for (const p of memberInclusions(m, decls, base.reads, more))
213
+ add({ wit: '', terms: [[1, p.positive], [-1, p.negative]], unit: 0, below: p.below }, 'guarded member inclusion', () => ({ carried: p.carried, guards: p.guards }));
214
+ budget.mark('pool:member-inclusions');
215
+ }
216
+ // No post-cap enumeration is needed: selected entries absent from this bounded
217
+ // prefix can still be reinserted by reservePool from their exact prior definitions.
218
+ // Narrow triples require an actual POST read; without one that pass cannot
219
+ // add anything, so do not rescan the entire immutable hypothesis context.
220
+ if (insts.length < cap && base.reads.some(r => r[1].endsWith('#')) && more()) {
221
+ const narrow = certFor(goal, decls, false, cap, more);
222
+ for (const i of narrow.insts) {
223
+ if (insts.length >= cap || !more())
224
+ break;
225
+ if (i.terms.length === 3)
226
+ add(i, 'preserved narrow triple');
227
+ }
228
+ }
229
+ budget.mark('pool:narrow');
230
+ const checkedDefinitions = new Set(), eligible = [], at = new Map();
231
+ if (insts.length < cap)
232
+ for (const r of base.reads) {
233
+ if (!more())
234
+ break;
235
+ if (r[1].endsWith('#'))
236
+ continue;
237
+ const d = byMap.get(r[1]);
238
+ if (!d)
239
+ continue;
240
+ if (!checkedDefinitions.has(r[1])) {
241
+ readTuples([d.body, d.below], more);
242
+ if (budget.state.exhausted || budget.state.deadline)
243
+ break;
244
+ checkedDefinitions.add(r[1]);
245
+ }
246
+ const b = bodyAt(d, r);
247
+ if (!b)
248
+ continue;
249
+ const foot = new Set(readTuples(b.body, more).map(([mp, k]) => json([mp, keyId(k)])));
250
+ if (budget.state.exhausted || budget.state.deadline)
251
+ break;
252
+ eligible.push(r);
253
+ at.set(r[0], { ...b, foot });
254
+ }
255
+ const fixed = [], keyed = [], classes = new Map();
256
+ for (const r of eligible) {
257
+ if (!more())
258
+ break;
259
+ let fixedClass = classes.get(r[1]);
260
+ if (fixedClass === undefined) {
261
+ fixedClass = genuinelyKeyless(byMap.get(r[1]));
262
+ classes.set(r[1], fixedClass);
263
+ }
264
+ ;
265
+ (fixedClass ? fixed : keyed).push(r);
266
+ }
267
+ triples: for (const a of fixed)
268
+ for (const d of fixed) {
269
+ if (insts.length >= cap || !more())
270
+ break triples;
271
+ if (a === d)
272
+ continue;
273
+ const aa = at.get(a[0]), dd = at.get(d[0]);
274
+ if (!aa.foot.size || aa.foot.size >= dd.foot.size || ![...aa.foot].every(x => dd.foot.has(x)))
275
+ continue;
276
+ for (const c of keyed) {
277
+ if (insts.length >= cap || !more())
278
+ break triples;
279
+ const cc = at.get(c[0]);
280
+ if (keyId(aa.below) !== keyId(dd.below) || keyId(aa.below) !== keyId(cc.below))
281
+ continue;
282
+ const bridge = [...dd.foot].filter(x => !aa.foot.has(x) && cc.foot.has(x));
283
+ if (!bridge.length)
284
+ continue;
285
+ add({ wit: '', below: aa.below, terms: [[1, a[0]], [-1, d[0]], [-1, c[0]]], unit: 0 }, 'definition-linked PRE triple', () => ({ a: [a[1], a[2]], d: [d[1], d[2]], c: [c[1], c[2]], aReads: [...aa.foot], dReads: [...dd.foot], cReads: [...cc.foot], bridge }));
286
+ }
287
+ }
288
+ budget.mark('pool:end');
289
+ return { full: { ...base, insts, wits }, base, added, proposed, oldEntriesPreserved: json(insts.slice(0, base.insts.length)) === json(base.insts), freshWitnesses: new Set(insts.map(i => i.wit)).size === insts.length,
290
+ work: { ...budget.state, capReached: insts.length >= cap, provenanceLimit: 128, omittedProvenance, truncated: budget.state.exhausted || budget.state.deadline || insts.length >= cap || omittedProvenance > 0 } };
291
+ }
292
+ export function smallSelection(goal, decls, full, ownKeys, previous, budget = candidateWork()) {
293
+ const more = budget.tick;
294
+ budget.mark('selection:begin');
295
+ const rootReads = readTuples(goal.hyps.at(-1), more);
296
+ const byRead = new Map(full.reads.map(r => [r[0], r])), byMap = new Map(decls.map(d => [d.map, d])), own = new Set([...ownKeys, ...rootReads.map(([, key]) => key)].map(keyId)), direct = new Set(rootReads.map(([mp]) => mp));
297
+ const insts = full.insts.filter(i => {
298
+ if (!more())
299
+ return false;
300
+ if (i.unit !== 0)
301
+ return false;
302
+ if (i.terms.length === 3)
303
+ return true;
304
+ if (i.terms.length !== 2 || i.terms[0][0] !== 1 || i.terms[1][0] !== -1)
305
+ return false;
306
+ const a = byRead.get(i.terms[0][1]), b = byRead.get(i.terms[1][1]);
307
+ if (a[1].endsWith('#') || b[1].endsWith('#'))
308
+ return false;
309
+ const da = byMap.get(a[1]), db = byMap.get(b[1]);
310
+ return keyless(da) && keyless(db) && (direct.has(a[1]) || direct.has(b[1])) || !keyless(da) && !keyless(db) && keyId(a[2]) === keyId(b[2]) && own.has(keyId(a[2]));
311
+ });
312
+ // Cover each concrete root key before another difference at an already covered
313
+ // key or a keyless residual. No new instance, read, or witness is constructed.
314
+ const keyed = new Map(), residual = [];
315
+ for (const i of insts) {
316
+ if (!more())
317
+ break;
318
+ const rs = i.terms.map(([, id]) => byRead.get(id)), key = rs[0]?.[2];
319
+ const exact = i.terms.length === 2 && key && rs.every(r => !keyless(byMap.get(r[1])) && keyId(r[2]) === keyId(key) && keyId(byMap.get(r[1]).below) === keyId(i.below)) && own.has(keyId(key));
320
+ if (exact) {
321
+ const id = keyId(key), rows = keyed.get(id) ?? [];
322
+ rows.push(i);
323
+ keyed.set(id, rows);
324
+ }
325
+ else
326
+ residual.push(i);
327
+ }
328
+ // A definition-linked PRE overlap lifts an already-relevant difference. Keep
329
+ // that difference and its existing lift ahead of mirror pairs, but never ahead
330
+ // of first coverage at any distinct current root key. Match actual read IDs and
331
+ // bounds; footprint links only rank candidates, never assert a source equality.
332
+ const pairId = (i) => json([keyId(i.below), i.unit, [...i.terms].sort((a, b) => a[1].localeCompare(b[1]))]);
333
+ const pairs = new Map(), footprints = new Map();
334
+ for (const i of insts) {
335
+ if (!more())
336
+ break;
337
+ if (i.terms.length === 2)
338
+ pairs.set(pairId(i), i);
339
+ }
340
+ const footprint = (id, below) => {
341
+ const cacheKey = json([id, keyId(below)]);
342
+ if (footprints.has(cacheKey))
343
+ return footprints.get(cacheKey);
344
+ const r = byRead.get(id), d = r && byMap.get(r[1]), b = d && r && !r[1].endsWith('#') ? bodyAt(d, r) : undefined;
345
+ const foot = b && keyId(b.below) === keyId(below) ? new Set(readTuples(b.body, more).map(([mp, k]) => readKey(mp, k))) : undefined;
346
+ if (budget.state.exhausted || budget.state.deadline)
347
+ return;
348
+ footprints.set(cacheKey, foot);
349
+ return foot;
350
+ };
351
+ const liftedPairs = [], overlaps = [];
352
+ for (const i of residual) {
353
+ if (!more())
354
+ break;
355
+ if (i.terms.length !== 3)
356
+ continue;
357
+ for (let extra = 0; extra < i.terms.length; extra++) {
358
+ if (!more())
359
+ break;
360
+ const pair = pairs.get(pairId({ ...i, terms: i.terms.filter((_, j) => j !== extra) })), r = byRead.get(i.terms[extra][1]);
361
+ if (!pair || !r || keyless(byMap.get(r[1])))
362
+ continue;
363
+ if (!pair.terms.every(([, id]) => keyless(byMap.get(byRead.get(id)[1]))))
364
+ continue;
365
+ const a = footprint(pair.terms[0][1], i.below), b = footprint(pair.terms[1][1], i.below), c = footprint(r[0], i.below);
366
+ if (!a || !b || !c)
367
+ continue;
368
+ const [small, large] = a.size < b.size ? [a, b] : [b, a];
369
+ if (!small.size || small.size >= large.size || ![...small].every(x => large.has(x)) || ![...large].some(x => !small.has(x) && c.has(x)))
370
+ continue;
371
+ liftedPairs.push(pair);
372
+ overlaps.push(i);
373
+ break;
374
+ }
375
+ }
376
+ const ordered = [...[...keyed.values()].map(rows => rows[0]), ...liftedPairs, ...overlaps];
377
+ for (let round = 1; round < 10; round++)
378
+ for (const rows of keyed.values())
379
+ if (rows[round])
380
+ ordered.push(rows[round]);
381
+ const seen = new Set(), unique = [...ordered, ...residual].filter(i => { const id = instId(i, full.reads); if (seen.has(id))
382
+ return false; seen.add(id); return true; }).slice(0, 10);
383
+ const used = new Set(unique.flatMap(i => i.terms.map(([, r]) => r))), oldReads = new Map(previous.reads.map(r => [r[0], r.slice(1)])), oldPicks = new Set((previous.picks ?? []).map(p => json([oldReads.get(p[0]), p[1]])));
384
+ const seenPicks = new Set(), picks = [];
385
+ for (const p of full.picks) {
386
+ if (!more() || picks.length + unique.length >= 10)
387
+ break;
388
+ const id = json([byRead.get(p[0])?.slice(1), p[1].map(keyId)]);
389
+ if (!seenPicks.has(id) && used.has(p[0]) && oldPicks.has(json([byRead.get(p[0]).slice(1), p[1]]))) {
390
+ seenPicks.add(id);
391
+ picks.push(p);
392
+ }
393
+ }
394
+ budget.mark('selection:end');
395
+ return { ...full, insts: unique, picks };
396
+ }
397
+ export function genuinelyKeyless(d) {
398
+ if ((d.base === undefined) !== (d.lo === undefined) || d.base !== undefined && (!Number.isInteger(d.base) || d.base <= 0))
399
+ return false;
400
+ return [d.j, ...(d.lo ? [d.lo] : [])].every(n => !mentions([d.body, d.below], n));
401
+ }
402
+ export function vacuousCountBinder(m, l, more = () => true) {
403
+ const ns = [l.forall, ...(l.keys ?? [])].filter((n) => !!n);
404
+ if (ns.length !== 1)
405
+ return false;
406
+ const n = ns[0];
407
+ let ignored = false;
408
+ const visit = (v) => {
409
+ if (!more())
410
+ return false;
411
+ if (Array.isArray(v))
412
+ return v.every(visit);
413
+ if (!v || typeof v !== 'object')
414
+ return true;
415
+ const o = v;
416
+ if (o.op === 'var' && o.name === n)
417
+ return false;
418
+ if (o.op === 'all' && (o.key === n || o.keys?.includes(n)))
419
+ return false;
420
+ if (o.op === 'get' && typeof o.map === 'string') {
421
+ const d = m.counts?.[o.map];
422
+ if (d && genuinelyKeyless(d)) {
423
+ if (mentions(o.key, n))
424
+ ignored = true;
425
+ return true;
426
+ }
427
+ }
428
+ return Object.values(o).every(visit);
429
+ };
430
+ return visit(l.holds) && ignored;
431
+ }
432
+ export function seedVacuousCounts(m, laws, initial, cap, more = candidateWork().tick) {
433
+ const at = { ...initial }, added = [];
434
+ for (const l of laws) {
435
+ if (added.length >= cap || !more())
436
+ break;
437
+ if (!vacuousCountBinder(m, l, more) || (at[l.name]?.length ?? 0) >= 4)
438
+ continue;
439
+ const zero = { op: 'const', value: 0 };
440
+ if ((at[l.name] ?? []).some(t => json(t) === json(zero)))
441
+ continue;
442
+ at[l.name] = [...(at[l.name] ?? []), zero];
443
+ added.push({ law: l.name, tuple: [zero] });
444
+ }
445
+ return { at, added };
446
+ }
447
+ export function postDirections(raw, decls) {
448
+ const post = new Set(decls.filter(d => d.map.endsWith('#')).map(d => d.map)), out = new Map();
449
+ const record = (map, key, directions, evidence) => { const id = readKey(map, key), r = out.get(id) ?? { map, key, directions: new Set(), evidence: [] }; directions.forEach(d => r.directions.add(d)); r.evidence.push(evidence); out.set(id, r); };
450
+ const coefficients = (e) => {
451
+ if (e.op === 'var' || e.op === 'const')
452
+ return new Map();
453
+ if (e.op === 'get')
454
+ return post.has(e.map) ? new Map([[readKey(e.map, e.key), { map: e.map, key: e.key, k: 1 }]]) : new Map();
455
+ if (e.op === 'mul') {
456
+ const a = coefficients(e.a);
457
+ if (!a)
458
+ return;
459
+ return new Map([...a].map(([id, r]) => [id, { ...r, k: r.k * e.k }]));
460
+ }
461
+ if (e.op === 'add') {
462
+ const a = coefficients(e.a), b = coefficients(e.b);
463
+ if (!a || !b)
464
+ return;
465
+ for (const [id, r] of b)
466
+ a.set(id, { ...r, k: r.k + (a.get(id)?.k ?? 0) });
467
+ return a;
468
+ }
469
+ return readTuples(e).some(([mp]) => post.has(mp)) ? undefined : new Map();
470
+ };
471
+ const walk = (c, positive, path) => {
472
+ if (c.op === 'not') {
473
+ walk(c.x, !positive, path + '/not');
474
+ return;
475
+ }
476
+ if (c.op === 'and' || c.op === 'or') {
477
+ c.xs.forEach((x, i) => walk(x, positive, path + '/' + c.op + i));
478
+ return;
479
+ }
480
+ if (c.op === 'all') {
481
+ walk(c.c, positive, path + '/all');
482
+ return;
483
+ }
484
+ if (c.op === 'flag')
485
+ return;
486
+ const a = coefficients(c.a), b = coefficients(c.b);
487
+ if (c.op === '=' || !a || !b) {
488
+ for (const [mp, key] of readTuples(c))
489
+ if (post.has(mp))
490
+ record(mp, key, ['lower', 'upper'], { path, op: c.op, positive, ambiguous: c.op === '=' ? 'equality' : 'unsupported expression' });
491
+ return;
492
+ }
493
+ for (const [id, r] of b)
494
+ a.set(id, { ...r, k: (a.get(id)?.k ?? 0) - r.k });
495
+ for (const r of a.values()) {
496
+ const k = r.k * (positive ? 1 : -1);
497
+ record(r.map, r.key, k > 0 ? ['lower'] : k < 0 ? ['upper'] : ['lower', 'upper'], { path, op: c.op, positive, coefficient: k, ...(k === 0 ? { ambiguous: 'cancelled coefficient' } : {}) });
498
+ }
499
+ };
500
+ walk(raw, true, 'raw');
501
+ return [...out.values()].map(r => ({ ...r, directions: [...r.directions] }));
502
+ }
503
+ export function polaritySelection(goal, decls, pool, budget = candidateWork(), sourceMaps) {
504
+ const full = pool.full, ordinary = certFor(goal, decls, false, 10, budget.tick), rawNarrow = certFor(goal, decls, false, 1000, budget.tick), narrow = json(rawNarrow.reads) === json(full.reads) ? rawNarrow : { ...full, insts: [] }, byMap = new Map(decls.map(d => [d.map, d])), byRead = new Map(full.reads.map(r => [r[0], r])), directions = postDirections(goal.hyps.at(-1), decls);
505
+ if (json(full.reads) !== json(narrow.reads))
506
+ throw Error('selector read context changed');
507
+ const candidates = new Map();
508
+ for (const [source, rows] of [['wide', full.insts], ['narrow', narrow.insts]])
509
+ for (const i of rows) {
510
+ if (!budget.tick())
511
+ break;
512
+ const id = instId(i, full.reads);
513
+ if (!candidates.has(id))
514
+ candidates.set(id, { instance: i, source });
515
+ }
516
+ const feet = (name) => { const d = byMap.get(name); return new Set(readTuples(substE(d.body, { vars: { [d.key]: { op: 'var', name: '$priority-witness' } }, maps: {}, flags: {} }), budget.tick).map(([mp, key]) => readKey(mp, key))); };
517
+ const preferred = [];
518
+ for (const [id, { instance: i, source }] of candidates) {
519
+ if (!budget.tick())
520
+ break;
521
+ const reasons = [];
522
+ let rank = 99;
523
+ if (i.unit === -1 && i.terms.length === 2 && i.terms.every(([k]) => k === 1))
524
+ for (const target of directions)
525
+ if (target.directions.includes('upper')) {
526
+ const twin = i.terms.find(([, n]) => { const r = byRead.get(n); return r[1] === target.map.slice(0, -1) && keyId(r[2]) === keyId(target.key); }), other = i.terms.find(t => t !== twin);
527
+ if (twin && other) {
528
+ const r = byRead.get(other[1]);
529
+ if (!r[1].endsWith('#') && genuinelyKeyless(byMap.get(r[1])) && (!sourceMaps || sourceMaps.has(r[1]))) {
530
+ rank = 1;
531
+ reasons.push({ direction: 'upper', kind: 'existing keyless PRE/target-twin meet', target, keyless: r.slice(1) });
532
+ }
533
+ }
534
+ }
535
+ if (i.unit !== 0) {
536
+ if (rank < 99)
537
+ preferred.push({ id, instance: i, source, rank, reasons });
538
+ continue;
539
+ }
540
+ for (const target of directions) {
541
+ const postTerm = i.terms.find(([, n]) => { const r = byRead.get(n); return r && readKey(r[1], r[2]) === readKey(target.map, target.key); });
542
+ if (!postTerm)
543
+ continue;
544
+ const others = i.terms.filter(t => t !== postTerm);
545
+ for (const direction of target.directions) {
546
+ const sign = direction === 'lower' ? -1 : 1;
547
+ if (postTerm[0] !== sign)
548
+ continue;
549
+ if (i.terms.length === 2 && others[0]?.[0] === -sign) {
550
+ const r = byRead.get(others[0][1]), before = byMap.get(r[1]), after = byMap.get(target.map);
551
+ if (r[1] === target.map.slice(0, -1) && (keyId(r[2]) === keyId(target.key) || keyless(before) && keyless(after))) {
552
+ rank = Math.min(rank, 0);
553
+ reasons.push({ direction, kind: 'same-key pre/post', target });
554
+ }
555
+ // A keyless source read whose exact cells occur in the POST definition is
556
+ // a candidate copy bound. This only orders an existing counting instance;
557
+ // the unchanged counting lemma still has to establish the relation.
558
+ if (direction === 'lower' && !r[1].endsWith('#') && keyless(before)) {
559
+ const source = feet(r[1]), destination = feet(target.map);
560
+ if (source.size && [...source].every(cell => destination.has(cell))) {
561
+ rank = Math.min(rank, 1);
562
+ reasons.push({ direction, kind: 'definition-linked source/post', source: r.slice(1), target });
563
+ }
564
+ }
565
+ }
566
+ if (direction === 'lower' && i.terms.length === 3) {
567
+ const plus = others.find(t => t[0] === 1), minus = others.find(t => t[0] === -1);
568
+ if (!plus || !minus)
569
+ continue;
570
+ const a = byRead.get(plus[1]), d = byRead.get(minus[1]), ad = byMap.get(a[1]), dd = byMap.get(d[1]);
571
+ if (a[1].endsWith('#') || d[1].endsWith('#') || !keyless(ad) || !keyless(dd))
572
+ continue;
573
+ const af = feet(a[1]), df = feet(d[1]), postMaps = new Set(readTuples(byMap.get(target.map).body).map(([mp]) => mp)), bridge = [...df].filter(x => !af.has(x) && postMaps.has(JSON.parse(x)[0]));
574
+ if (af.size && af.size < df.size && [...af].every(x => df.has(x)) && bridge.length) {
575
+ rank = Math.min(rank, 1);
576
+ reasons.push({ direction, kind: 'existing keyless-difference/post triple', a: a.slice(1), d: d.slice(1), target, bridge });
577
+ }
578
+ }
579
+ }
580
+ }
581
+ if (rank < 99)
582
+ preferred.push({ id, instance: i, source, rank, reasons });
583
+ }
584
+ preferred.sort((a, b) => a.rank - b.rank);
585
+ const selected = [], seen = new Set();
586
+ const initialPriorityOnly = !!sourceMaps?.size && preferred.length > 0;
587
+ for (const i of [...preferred.map(p => p.instance), ...(initialPriorityOnly ? [] : json(ordinary.reads) === json(full.reads) ? ordinary.insts : full.insts.slice(0, 10))]) {
588
+ const id = instId(i, full.reads);
589
+ if (!seen.has(id) && selected.length < 10) {
590
+ seen.add(id);
591
+ selected.push(candidates.get(id)?.instance ?? i);
592
+ }
593
+ }
594
+ const pick = { ...full, insts: selected, wits: selected.map(i => i.wit), picks: [] };
595
+ return { pick, record: { directions, preferred: preferred.map(({ instance, ...p }) => ({ ...p, instance, selected: seen.has(p.id), presentBeforeCap: true })), selected: selected.map(i => instId(i, full.reads)), selectedCount: selected.length, initialPriorityOnly, activePoolCap: 1000, newGrammar: false, work: budget.state } };
596
+ }
597
+ export const instId = (i, rs) => { const rd = new Map(rs.map(r => [r[0], [r[1], keyId(r[2])]])); return json([i.terms.map(([n, r]) => [n, rd.get(r)]).sort((a, b) => json(a).localeCompare(json(b))), i.unit, keyId(i.below)]); };
598
+ export const ids = (c) => { const rd = new Map(c.reads.map(r => [r[0], [r[1], keyId(r[2])]])); return [...(c.picks ?? []).map(p => 'p' + json([rd.get(p[0]), p[1].map(keyId)])), ...c.insts.map(i => 'i' + instId(i, c.reads))]; };
599
+ function requireValue(x, message) { if (x === undefined)
600
+ throw new UnsupportedCountProposal('unresolved reservation: ' + message); return x; }
601
+ const reservationOpen = () => { if (performance.now() >= wallAt())
602
+ throw new UnsupportedCountProposal('reservation deadline'); };
603
+ // A lexical free-variable walk, not sourceNames: local quantified binders and a
604
+ // declaration's formal parameters do not grant scope to a retained read key.
605
+ function reservationFree(value, bound = new Set(), out = new Set()) {
606
+ reservationOpen();
607
+ if (!value || typeof value !== 'object')
608
+ return out;
609
+ if (Array.isArray(value)) {
610
+ for (const v of value)
611
+ reservationFree(v, bound, out);
612
+ return out;
613
+ }
614
+ const o = value;
615
+ if (o.op === 'var') {
616
+ if (!bound.has(String(o.name)))
617
+ out.add(String(o.name));
618
+ return out;
619
+ }
620
+ if (o.op === 'all') {
621
+ reservationFree(o.c, new Set([...bound, String(o.key), ...(o.keys ?? [])]), out);
622
+ if (o.witness)
623
+ reservationFree(o.witness, bound, out);
624
+ return out;
625
+ }
626
+ for (const v of Object.values(o))
627
+ reservationFree(v, bound, out);
628
+ return out;
629
+ }
630
+ // Only the actual selected certificate's closure (<=10 entries, <=3 reads each),
631
+ // never the old optional pool. This validates before optional generation and is
632
+ // revalidated on insertion. No candidate fuel is created or consumed by replay.
633
+ export function reservationReadClosure(goal, decls, previous, previousDecls, chosen, globals = []) {
634
+ reservationOpen();
635
+ if (chosen.size > 10)
636
+ throw new UnsupportedCountProposal('selected cap');
637
+ if (!chosen.size)
638
+ return { reads: [], scope: new Set(globals) };
639
+ const scope = new Set(globals), needed = new Set(), oldIds = ids(previous), picked = [], insts = [];
640
+ for (const n of reservationFree(goal.hyps))
641
+ scope.add(n);
642
+ for (const d of decls)
643
+ for (const n of reservationFree([d.body, d.below], new Set([d.j, d.key, ...(d.lo ? [d.lo] : [])])))
644
+ scope.add(n);
645
+ for (const key of chosen) {
646
+ reservationOpen();
647
+ const at = oldIds.indexOf(key);
648
+ if (at < 0)
649
+ throw new UnsupportedCountProposal('unresolved reservation: selected entry absent from previous pool');
650
+ if (at < (previous.picks?.length ?? 0)) {
651
+ const p = previous.picks[at];
652
+ picked.push(p);
653
+ needed.add(p[0]);
654
+ }
655
+ else {
656
+ const i = previous.insts[at - (previous.picks?.length ?? 0)];
657
+ if (i.terms.length > 3)
658
+ throw new UnsupportedCountProposal('reservation read closure cap');
659
+ insts.push(i);
660
+ for (const [, r] of i.terms)
661
+ needed.add(r);
662
+ }
663
+ }
664
+ if (needed.size > 30)
665
+ throw new UnsupportedCountProposal('reservation read closure cap');
666
+ const reads = [], byRead = new Map(previous.reads.map(r => [r[0], r])), oldDecls = new Map(previousDecls.map(d => [d.map, d])), nowDecls = new Map(decls.map(d => [d.map, d])), oldWits = new Set(previous.insts.map(i => i.wit)), selectedWits = new Set(insts.map(i => i.wit));
667
+ if (byRead.size !== previous.reads.length || oldDecls.size !== previousDecls.length || nowDecls.size !== decls.length)
668
+ throw new UnsupportedCountProposal('reservation ambiguous read/definition');
669
+ for (const id of needed) {
670
+ reservationOpen();
671
+ const r = requireValue(byRead.get(id), 'previous read ' + id), od = requireValue(oldDecls.get(r[1]), 'old definition ' + r[1]), nd = requireValue(nowDecls.get(r[1]), 'new definition ' + r[1]);
672
+ if (json(od) !== json(nd) || insts.some(i => i.terms.some(([, x]) => x === id) && keyId(i.below) !== keyId(nd.below)))
673
+ throw new UnsupportedCountProposal('unresolved reservation: changed bound/definition ' + r[1]);
674
+ for (const n of reservationFree(r[2]))
675
+ if (!scope.has(n) || oldWits.has(n) || decls.some(d => d.key === n))
676
+ throw new UnsupportedCountProposal('reservation read key out of scope/captured');
677
+ reads.push(r);
678
+ }
679
+ for (const [, terms] of picked)
680
+ for (const n of reservationFree(terms))
681
+ if (oldWits.has(n) ? !selectedWits.has(n) : !scope.has(n))
682
+ throw new UnsupportedCountProposal('reservation pick dependency/scope');
683
+ for (const i of insts)
684
+ if (reads.some(r => r[0] === i.wit || names(r[2]).has(i.wit)) || decls.some(d => [d.j, d.lo, d.key].includes(i.wit) || names([d.body, d.below]).has(i.wit)))
685
+ throw new UnsupportedCountProposal('reservation witness capture');
686
+ reservationOpen();
687
+ if (!mcGoal(goal.hyps, decls, { reads, insts, picks: picked }))
688
+ throw new UnsupportedCountProposal('unresolved reservation: selected reification rejected');
689
+ reservationOpen();
690
+ return { reads, scope };
691
+ }
692
+ // A cache spelling is not ownership. This state is created once per goal within
693
+ // one attempt; only validated actual selections can acquire its <=10 live leases.
694
+ export function reservationState(goal, rawSource, next) {
695
+ reservationOpen();
696
+ return { next, inserted: new Map(), ownership: { goal: json([goal.name, goal.hyps.at(-1)]), reserved: sourceNames(rawSource, reservationOpen), leases: new Map() } };
697
+ }
698
+ function reservationIdentity(i, reads, decls) {
699
+ const rs = new Map(reads.map(r => [r[0], r])), ds = new Map(decls.map(d => [d.map, d]));
700
+ return json([i.below, i.unit, i.terms.map(([co, id]) => { const r = requireValue(rs.get(id), 'owned read'); return [co, r[1], r[2], requireValue(ds.get(r[1]), 'owned definition')]; }).sort((a, b) => json(a).localeCompare(json(b)))]);
701
+ }
702
+ // Only free variable occurrences in HYPS are exempt. In particular map names,
703
+ // lexical binder declarations and all non-HYPS fields keep their ordinary names.
704
+ function reservationHypNames(value, out = new Set()) {
705
+ reservationOpen();
706
+ if (typeof value === 'string') {
707
+ out.add(value);
708
+ return out;
709
+ }
710
+ if (!value || typeof value !== 'object')
711
+ return out;
712
+ const o = value;
713
+ for (const [k, v] of Object.entries(o)) {
714
+ out.add(k);
715
+ if (o.op === 'var' && k === 'name')
716
+ continue;
717
+ reservationHypNames(v, out);
718
+ }
719
+ return out;
720
+ }
721
+ export function reservePool(goal, decls, pool, previous, previousDecls, chosen, state, cap = 1000, reservation) {
722
+ const closure = reservationReadClosure(goal, decls, previous, previousDecls, chosen, reservation?.scope);
723
+ const owner = state.ownership, leases = new Map();
724
+ if (owner && owner.goal !== json([goal.name, goal.hyps.at(-1)]))
725
+ throw new UnsupportedCountProposal('reservation goal/attempt changed');
726
+ const reads = [...pool.full.reads], fresh = sourceNames([goal, decls, pool.full], reservationOpen), preserved = [];
727
+ let serial = reads.length;
728
+ for (const r of closure.reads) {
729
+ reservationOpen();
730
+ let current = reads.find(x => x[1] === r[1] && json(x[2]) === json(r[2]));
731
+ if (!current) {
732
+ let id;
733
+ do {
734
+ reservationOpen();
735
+ id = 'r$' + serial++;
736
+ } while (fresh.has(id));
737
+ fresh.add(id);
738
+ current = [id, r[1], r[2]];
739
+ reads.push(current);
740
+ }
741
+ if (names([goal.hyps, decls.map(d => [d.body, d.below]), reads.map(r => r[2])], reservationOpen).has(current[0]) || decls.some(d => [d.j, d.lo, d.key].includes(current[0])))
742
+ throw new UnsupportedCountProposal('reservation read capture');
743
+ preserved.push(current);
744
+ }
745
+ const full = { ...pool.full, reads, insts: [...pool.full.insts] }, oldReads = new Map(previous.reads.map(r => [r[0], r])), nowReads = new Map(full.reads.map(r => [json([r[1], keyId(r[2])]), r])), oldDecls = new Map(previousDecls.map(d => [d.map, d])), nowDecls = new Map(decls.map(d => [d.map, d])), fullIds = ids(full), currentIds = new Set(fullIds), oldIds = ids(previous), pending = [], rebindings = [];
746
+ for (const r of preserved)
747
+ nowReads.set(json([r[1], keyId(r[2])]), r);
748
+ const renamed = [], quarantined = [];
749
+ if (owner) {
750
+ // Regenerated representatives do not own selected binder names. Restore
751
+ // those entries from the prior checked semantic selection below instead.
752
+ full.insts = full.insts.filter((_, i) => { const key = fullIds[(full.picks?.length ?? 0) + i]; if (!chosen.has(key))
753
+ return true; currentIds.delete(key); return false; });
754
+ const protectedWits = new Map(), protect = (key, wit) => { const old = protectedWits.get(wit); if (old !== undefined && old !== key)
755
+ throw new UnsupportedCountProposal('reservation different witness owner'); protectedWits.set(wit, key); };
756
+ for (const [key, lease] of owner.leases)
757
+ protect(key, lease.wit);
758
+ for (const key of chosen)
759
+ if (key.startsWith('i')) {
760
+ const at = oldIds.indexOf(key) - (previous.picks?.length ?? 0);
761
+ protect(key, requireValue(previous.insts[at], 'selected owner').wit);
762
+ }
763
+ for (const wit of protectedWits.keys())
764
+ fresh.add(wit);
765
+ for (const name of owner.reserved)
766
+ fresh.add(name);
767
+ let dependencies;
768
+ // Regeneration may assign an old owner's spelling to a different cold entry.
769
+ // Rename only that independent binder, never a live owner or a referenced term.
770
+ for (const [at, i] of full.insts.entries()) {
771
+ reservationOpen();
772
+ const owned = protectedWits.get(i.wit);
773
+ if (owned === undefined)
774
+ continue;
775
+ const key = 'i' + instId(i, full.reads);
776
+ if (owned === key)
777
+ continue;
778
+ dependencies ??= sourceNames([full.reads, full.picks, full.insts.map(j => j.below)], reservationOpen);
779
+ if (dependencies.has(i.wit)) {
780
+ if (chosen.has(key) || owner.leases.has(key))
781
+ throw new UnsupportedCountProposal('reservation cold witness dependency');
782
+ // A dependent cold proposal cannot be renamed. Drop only that unselected
783
+ // entry; live owners and every read/pick term retain their exact spelling.
784
+ quarantined.push({ index: at, instance: i });
785
+ continue;
786
+ }
787
+ let wit;
788
+ do {
789
+ reservationOpen();
790
+ wit = 'w$' + state.next++;
791
+ } while (fresh.has(wit));
792
+ fresh.add(wit);
793
+ full.insts[at] = { ...i, wit };
794
+ renamed.push({ key, from: i.wit, to: wit });
795
+ }
796
+ if (quarantined.length) {
797
+ const removed = new Set(quarantined.map(q => q.index));
798
+ full.insts = full.insts.filter((_, i) => !removed.has(i));
799
+ }
800
+ }
801
+ for (const key of chosen) {
802
+ reservationOpen();
803
+ if (!key.startsWith('i')) {
804
+ if (!currentIds.has(key))
805
+ throw new UnsupportedCountProposal('unresolved reservation: selected pick missing');
806
+ continue;
807
+ }
808
+ const oi = oldIds.indexOf(key) - (previous.picks?.length ?? 0), old = requireValue(previous.insts[oi], key + ' not in previous actual pool');
809
+ const terms = old.terms.map(([coefficient, id]) => { const r = requireValue(oldReads.get(id), 'previous read ' + id), next = requireValue(nowReads.get(json([r[1], keyId(r[2])])), 'current exact map/key ' + json(r.slice(1))), od = requireValue(oldDecls.get(r[1]), 'old definition ' + r[1]), nd = requireValue(nowDecls.get(r[1]), 'new definition ' + r[1]); if (json(od) !== json(nd) || keyId(od.below) !== keyId(old.below))
810
+ throw new UnsupportedCountProposal('unresolved reservation: changed bound/definition ' + r[1]); return [coefficient, next[0]]; });
811
+ const rebound = { ...old, terms };
812
+ if ('i' + instId(rebound, full.reads) !== key)
813
+ throw new UnsupportedCountProposal('unresolved reservation: semantic change');
814
+ rebindings.push({ key, oldTerms: old.terms, newTerms: terms, allReadsAndDefinitionsPresent: true });
815
+ let wit;
816
+ if (owner) {
817
+ const identity = reservationIdentity(old, previous.reads, decls), prior = owner.leases.get(key);
818
+ if (prior && (prior.identity !== identity || prior.wit !== old.wit))
819
+ throw new UnsupportedCountProposal('reservation stale owned identity/witness');
820
+ wit = prior?.wit ?? old.wit;
821
+ const forbidden = sourceNames([{ ...goal, hyps: undefined }, decls, full.reads, [...previous.insts, ...full.insts].map(i => i.below)], reservationOpen);
822
+ for (const n of reservationHypNames(goal.hyps))
823
+ forbidden.add(n);
824
+ if (owner.reserved.has(wit) || forbidden.has(wit))
825
+ throw new UnsupportedCountProposal('reservation owned witness capture/source');
826
+ if ([...owner.leases, ...leases].some(([id, l]) => id !== key && l.wit === wit) || full.insts.some(i => i.wit === wit && 'i' + instId(i, full.reads) !== key))
827
+ throw new UnsupportedCountProposal('reservation different witness owner');
828
+ if (reservationIdentity(rebound, full.reads, decls) !== identity)
829
+ throw new UnsupportedCountProposal('reservation owned read/definition changed');
830
+ leases.set(key, { wit, identity });
831
+ }
832
+ if (!currentIds.has(key))
833
+ pending.push({ ...rebound, ...(wit ? { wit } : {}) });
834
+ else
835
+ for (const [at, i] of full.insts.entries())
836
+ if ('i' + instId(i, full.reads) === key) {
837
+ if (wit && i.wit !== wit && sourceNames([goal, decls, full.reads, full.insts.map(j => j.below), full.picks], reservationOpen).has(i.wit))
838
+ throw new UnsupportedCountProposal('reservation renamed pool witness dependency');
839
+ full.insts[at] = wit ? { ...rebound, wit } : { ...i, terms };
840
+ }
841
+ }
842
+ // Several raw aliases can denote one selected semantic entry. Align exactly
843
+ // one FULL representative with the live view, not multiple copies of its lease.
844
+ if (owner) {
845
+ const seen = new Set();
846
+ full.insts = full.insts.filter(i => { const key = 'i' + instId(i, full.reads); if (!chosen.has(key))
847
+ return true; if (seen.has(key))
848
+ return false; seen.add(key); return true; });
849
+ }
850
+ const taken = new Set([...full.insts.map(i => i.wit), ...sourceNames([goal, decls, full.reads], reservationOpen)]), inserted = [];
851
+ for (const old of pending) {
852
+ reservationOpen();
853
+ const key = 'i' + instId(old, full.reads);
854
+ let wit = leases.get(key)?.wit ?? state.inserted.get(key);
855
+ if (!leases.has(key) && (!wit || taken.has(wit))) {
856
+ do {
857
+ reservationOpen();
858
+ wit = 'w$' + state.next++;
859
+ } while (taken.has(wit));
860
+ }
861
+ wit = requireValue(wit, 'allocated witness');
862
+ state.inserted.set(key, wit);
863
+ taken.add(wit);
864
+ const i = { ...old, wit };
865
+ if (!mcGoal(goal.hyps, decls, { reads: full.reads, insts: [i], picks: [] }))
866
+ throw new UnsupportedCountProposal('unresolved reservation: CountInst reification rejected');
867
+ inserted.push(i);
868
+ }
869
+ let need = Math.max(0, full.insts.length + inserted.length - cap);
870
+ const evicted = [], kept = [...full.insts], protectedNames = names((previous.picks ?? []).filter((_, i) => chosen.has(oldIds[i])));
871
+ for (let i = kept.length - 1; i >= 0 && need; i--) {
872
+ reservationOpen();
873
+ const v = kept[i];
874
+ if (chosen.has('i' + instId(v, full.reads)) || protectedNames.has(v.wit))
875
+ continue;
876
+ evicted.push(v);
877
+ kept.splice(i, 1);
878
+ need--;
879
+ }
880
+ if (need)
881
+ throw new UnsupportedCountProposal('unresolved reservation: no unselected tail space');
882
+ const insts = [...kept, ...inserted], next = { ...full, insts, wits: insts.map(i => i.wit) };
883
+ reservationOpen();
884
+ const selected = chosenView(next, chosen), selectedWits = new Set(selected.insts.map(i => i.wit)), allWits = new Set([...insts, ...previous.insts].map(i => i.wit));
885
+ for (const [, terms] of selected.picks)
886
+ for (const n of names(terms))
887
+ if (allWits.has(n) && !selectedWits.has(n))
888
+ throw new UnsupportedCountProposal('reservation pick dependency');
889
+ if (!mcGoal(goal.hyps, decls, selected))
890
+ throw new UnsupportedCountProposal('unresolved reservation: selected reification rejected');
891
+ reservationOpen();
892
+ if (insts.length > cap || new Set(next.wits).size !== insts.length || ![...chosen].every(k => ids(next).includes(k)))
893
+ throw new UnsupportedCountProposal('reservation postcondition');
894
+ if (owner) {
895
+ if (leases.size > 10 || !mcGoal(goal.hyps, decls, next))
896
+ throw new UnsupportedCountProposal('reservation full alignment rejected');
897
+ owner.leases = leases;
898
+ for (const key of state.inserted.keys())
899
+ if (!chosen.has(key))
900
+ state.inserted.delete(key);
901
+ }
902
+ return { full: next, record: { cap, chosen: chosen.size, renamed, quarantined: quarantined.map(q => q.instance), baseSize: full.insts.length, finalSize: insts.length, preservedReads: preserved, rebindings, inserted: inserted.map(i => ({ key: 'i' + instId(i, full.reads), instance: i })), evicted: evicted.map(i => ({ key: 'i' + instId(i, full.reads), instance: i })), reified: inserted.length, unselectedTailOnly: true } };
903
+ }
904
+ const canonJSON = (v) => JSON.stringify(v, (_k, x) => x && typeof x === 'object' && !Array.isArray(x) ? Object.fromEntries(Object.entries(x).sort(([a], [b]) => a.localeCompare(b))) : x);
905
+ export function stableState(rawSource) { return { reserved: sourceNames(rawSource), bySemantic: new Map(), used: new Set() }; }
906
+ export function stableSelected(goal, decls, view, state, context) {
907
+ if (context.lazyRoom || context.fullPoolUsed || (view.picks?.length ?? 0) > 0)
908
+ throw new UnsupportedCountProposal('stable selected view cannot cross full-pool model/pick view');
909
+ if (new Set(view.reads.map(r => r[0])).size !== view.reads.length)
910
+ throw new UnsupportedCountProposal('duplicate/aliased count read identifiers');
911
+ const needed = new Set([...view.insts.flatMap(i => i.terms.map(([, r]) => r)), ...(view.picks ?? []).map(([r]) => r)]), projectedReads = view.reads.filter(([r]) => needed.has(r));
912
+ if (projectedReads.length !== needed.size)
913
+ throw new UnsupportedCountProposal('missing referenced count read');
914
+ const reads = new Map(projectedReads.map(r => [r[0], r])), ds = new Map(decls.map(d => [d.map, d])), updates = [];
915
+ const insts = view.insts.map(i => {
916
+ const semantic = instId(i, view.reads), definition = canonJSON({ below: i.below, defs: i.terms.map(([coefficient, id]) => { const r = reads.get(id), d = r && ds.get(r[1]); if (!r || !d)
917
+ throw new UnsupportedCountProposal('unresolved stable read/definition'); return { coefficient, map: r[1], definition: d }; }).sort((a, b) => canonJSON(a).localeCompare(canonJSON(b))) });
918
+ let prior = state.bySemantic.get(semantic);
919
+ if (prior) {
920
+ if (prior.definition !== definition)
921
+ throw new UnsupportedCountProposal('unresolved stable definition/bound changed');
922
+ }
923
+ else {
924
+ if (state.reserved.has(i.wit) || state.used.has(i.wit))
925
+ throw new UnsupportedCountProposal('stable witness source collision/nonunique');
926
+ prior = { wit: i.wit, definition };
927
+ state.bySemantic.set(semantic, prior);
928
+ state.used.add(prior.wit);
929
+ }
930
+ if (state.reserved.has(prior.wit))
931
+ throw new UnsupportedCountProposal('stable witness no longer fresh from source');
932
+ updates.push({ semantic, poolWitness: i.wit, selectedWitness: prior.wit, exactDefinitions: true, sourceFresh: true });
933
+ return { ...i, wit: prior.wit };
934
+ });
935
+ if (new Set(insts.map(i => i.wit)).size !== insts.length)
936
+ throw new UnsupportedCountProposal('nonunique stable selected witnesses');
937
+ for (const i of insts)
938
+ if (projectedReads.some(r => r[0] === i.wit || names(r[2]).has(i.wit)) || decls.some(d => names([d.below, d.body]).has(i.wit)))
939
+ throw new UnsupportedCountProposal('stable witness captured by count read/definition');
940
+ const cert = { ...view, reads: projectedReads, insts, picks: view.picks ?? [], wits: insts.map(i => i.wit) };
941
+ if (!mcGoal(goal.hyps, decls, cert))
942
+ throw new UnsupportedCountProposal('stable selected reification failed');
943
+ return { cert, record: { stable: true, selectedCount: insts.length, updates, fullPoolModelUsed: false, picksUsed: false, sourceReadCount: view.reads.length, selectedReadCount: projectedReads.length, referencedReadIds: [...needed], omittedReadIds: view.reads.filter(([r]) => !needed.has(r)).map(([r]) => r) } };
944
+ }
945
+ export function fixedStateCoordinates(m, key, binder) {
946
+ const a = linOfE(key);
947
+ if (!a || !a[binder])
948
+ return [];
949
+ return Object.entries(a).filter(([n, c]) => n !== binder && n !== '1' && c !== 0 && Object.hasOwn(m.state, n)).map(([name, coefficient]) => ({ name, coefficient }));
950
+ }
951
+ export function projectBoundCoordinate(m, pattern, actual, binder) {
952
+ const a = linOfE(pattern), b = linOfE(actual), unmatchedFixed = fixedStateCoordinates(m, pattern, binder);
953
+ if (!a || !b || !unmatchedFixed.length)
954
+ return;
955
+ // A unique coefficient position is a coordinate; no fixed coordinate is rebound or equated.
956
+ const coefficient = a[binder], bound = Object.entries(b).filter(([n, c]) => n !== '1' && c === coefficient);
957
+ if (bound.length !== 1 || Object.entries(a).some(([n, c]) => n !== binder && n !== '1' && c === coefficient))
958
+ return;
959
+ const name = bound[0][0];
960
+ return { binding: { [binder]: { op: 'var', name } }, kind: 'coordinate-projection', unmatchedFixed, sourceCoordinates: Object.entries(b).filter(([n, c]) => n !== '1' && c !== 0 && n !== name).map(([name, coefficient]) => ({ name, coefficient })), boundCoordinate: { name, coefficient } };
961
+ }
962
+ export function matchAffineRemainder(pattern, actual, binders, live) {
963
+ const a = linOfE(pattern), b = linOfE(actual);
964
+ if (!a || !b)
965
+ return;
966
+ if ([...Object.entries(a), ...Object.entries(b)].some(([n, k]) => !Number.isInteger(k) || (n !== '1' && k < 0)))
967
+ return;
968
+ const tails = binders.filter(n => a[n] === 1);
969
+ if (tails.length !== 1)
970
+ return;
971
+ const tail = tails[0], rest = { ...b }, binding = {};
972
+ for (const [name, k] of Object.entries(a)) {
973
+ if (name === '1' || binders.includes(name))
974
+ continue;
975
+ if (rest[name] !== k)
976
+ return;
977
+ delete rest[name];
978
+ }
979
+ for (const name of binders) {
980
+ const k = a[name];
981
+ if (name === tail || k === undefined)
982
+ continue;
983
+ if (k <= 1)
984
+ return;
985
+ const fits = Object.entries(rest).filter(([n, v]) => n !== '1' && v === k);
986
+ if (fits.length !== 1)
987
+ return;
988
+ const n = fits[0][0];
989
+ binding[name] = { op: 'var', name: n };
990
+ delete rest[n];
991
+ }
992
+ const constant = (b['1'] ?? 0) - (a['1'] ?? 0);
993
+ delete rest['1'];
994
+ if (constant < 0 || Object.values(rest).some(k => k < 0 || !Number.isInteger(k)))
995
+ return;
996
+ const terms = Object.entries(rest).filter(([, k]) => k > 0).sort(([a], [b]) => a.localeCompare(b)).map(([name, k]) => k === 1 ? { op: 'var', name } : { op: 'mul', k, a: { op: 'var', name } });
997
+ if (constant)
998
+ terms.push({ op: 'const', value: constant });
999
+ binding[tail] = terms.length === 0 ? { op: 'const', value: 0 } : terms.slice(1).reduce((a, b) => ({ op: 'add', a, b }), terms[0]);
1000
+ const liveAnchors = Object.values(binding).flatMap(e => e.op === 'var' && live.has(e.name) ? [e.name] : []);
1001
+ if (!liveAnchors.length)
1002
+ return;
1003
+ const expanded = linOfE(substE(pattern, { vars: binding, maps: {}, flags: {} }));
1004
+ if (!expanded || canon(expanded) !== canon(b))
1005
+ return;
1006
+ return { binding, tail, remainder: binding[tail], polynomial: canon(expanded), liveAnchors };
1007
+ }
1008
+ export function matchRead(pattern, term, binders) {
1009
+ const out = {};
1010
+ const go = (a, b) => {
1011
+ if (a.op === 'var' && binders.includes(a.name)) {
1012
+ if (out[a.name])
1013
+ return json(out[a.name]) === json(b);
1014
+ out[a.name] = b;
1015
+ return true;
1016
+ }
1017
+ if (!b || a.op !== b.op)
1018
+ return false;
1019
+ const target = b;
1020
+ return Object.entries(a).every(([k, v]) => k === 'op' || (v && typeof v === 'object' ? (Array.isArray(v) ? Array.isArray(target[k]) && v.length === target[k].length && v.every((x, i) => go(x, target[k][i])) : go(v, target[k])) : v === target[k]));
1021
+ };
1022
+ if (go(pattern, term))
1023
+ return out;
1024
+ const a = linOfE(pattern), b = linOfE(term);
1025
+ if (!a || !b || (a['1'] ?? 0) !== (b['1'] ?? 0))
1026
+ return;
1027
+ const aa = Object.entries(a).filter(([n]) => n !== '1').sort((a, b) => b[1] - a[1]), bb = Object.entries(b).filter(([n]) => n !== '1').sort((a, b) => b[1] - a[1]);
1028
+ if (aa.length !== bb.length || aa.some(([, c], i) => c !== bb[i][1] || (i > 0 && c === aa[i - 1][1])))
1029
+ return;
1030
+ const result = {};
1031
+ for (const [i, [n]] of aa.entries()) {
1032
+ const t = bb[i][0];
1033
+ if (binders.includes(n))
1034
+ result[n] = { op: 'var', name: t };
1035
+ else if (n !== t)
1036
+ return;
1037
+ }
1038
+ return result;
1039
+ }
1040
+ export const projectionEligible = (m, l, more) => { const ns = vars(l); return ns.length === 1 && lawReads(l, more).some(([, key]) => fixedStateCoordinates(m, key, ns[0]).length > 0); };
1041
+ function emptyReadResult(at, cap) {
1042
+ return { at, added: [], proposals: [], mixed: [], summary: { livePairWork: 0, livePairLimit: 4096, livePairExhausted: false, anchors: [], candidates: 0, mixedAlternatives: 0, admitted: 0, perLawLimit: 4, cap, rawFocusSupplied: false, selectedWitnesses: [], directCountMaps: [], writeVariables: [], allTuplesGenuinePRE: true, noMixedTupleAdmitted: true } };
1043
+ }
1044
+ function baseReadInstances(m, laws, own, at, goal, cert, cap = 64, rawNegatedPost, more = candidateWork().tick, mode = 'all', pairBudget = { work: 0 }) {
1045
+ const boundedReads = (v) => readTuples(v, more);
1046
+ if (cap <= 0)
1047
+ return emptyReadResult(at, cap);
1048
+ const ks = vars(own), ownTerms = ks.map((n, i) => ({ op: 'var', name: i === 0 ? n + '#' : n })), ownBody = substC(own.holds, { vars: Object.fromEntries(ks.map((n, i) => [n, ownTerms[i]])), maps: {}, flags: {} });
1049
+ const ownReads = boundedReads(ownBody), ownMaps = new Set(ownReads.map(([mp]) => mp)), anchors = [];
1050
+ for (const [i, [map, key]] of ownReads.entries())
1051
+ anchors.push({ kind: 'own', map, key, id: 'own:' + i });
1052
+ for (const [map, w] of Object.entries(m.step.maps ?? {}))
1053
+ if (ownMaps.has(map) && !('each' in w))
1054
+ anchors.push({ kind: 'write', map, key: w.key, id: 'write:' + map });
1055
+ const actual = boundedReads(goal.hyps).map(([map, key], i) => ({ kind: 'read', map, key, id: 'read:' + i })), writes = anchors.filter(s => s.kind === 'write'), writeVars = new Set(writes.flatMap(s => [...names(s.key)])), ownVars = names(ownTerms);
1056
+ const directCounts = new Set(boundedReads(rawNegatedPost).filter(([mp]) => !!m.counts?.[mp]).map(([mp]) => mp)), readMap = new Map(cert.reads.map(r => [r[0], r[1]])), witScore = new Map(cert.insts.map(i => [i.wit, i.terms.reduce((s, [k, r]) => s + (directCounts.has(readMap.get(r) ?? '') ? (k < 0 ? 4 : 1) : 0), 0)]));
1057
+ const candidates = [], mixed = [], selectedWitnesses = new Set(cert.insts.map(i => i.wit));
1058
+ let livePairWork = 0, livePairExhausted = false;
1059
+ const livePairLimit = 4096;
1060
+ const score = (tuple, sources) => { const ns = names(tuple); return [...writeVars].filter(n => ns.has(n)).length * 100 + [...ownVars].filter(n => ns.has(n)).length * 10 + Math.max(0, ...[...ns].map(n => witScore.get(n) ?? 0)) + (sources.some(s => s.source.kind === 'own') && sources.some(s => s.source.kind === 'write') ? 30 : 0); };
1061
+ sourceLaws: for (const l of laws) {
1062
+ if (!more())
1063
+ break;
1064
+ if (!l.forall || (at[l.name]?.length ?? 0) / (1 + (l.keys?.length ?? 0)) >= 4)
1065
+ continue;
1066
+ const ns = vars(l), oneKey = projectionEligible(m, l, more);
1067
+ if ((ns.length < 2 && !oneKey) || l === own)
1068
+ continue;
1069
+ const pats = lawReads(l, more).filter(([, key]) => [...names(key)].filter(n => ns.includes(n)).length >= (oneKey ? 1 : 2)), partials = [];
1070
+ for (const pattern of pats)
1071
+ for (const source of [...(mode === 'live' ? [] : anchors), ...actual.filter(s => s.map === pattern[0] && (mode !== 'live' || [...names(s.key)].some(n => selectedWitnesses.has(n))))]) {
1072
+ if (!more())
1073
+ break sourceLaws;
1074
+ const sameMap = source.map === pattern[0];
1075
+ if (oneKey && !sameMap)
1076
+ continue;
1077
+ const binding = matchRead(pattern[1], source.key, ns);
1078
+ const remainder = !binding && sameMap && source.kind === 'read' ? matchAffineRemainder(pattern[1], source.key, ns, selectedWitnesses) : undefined;
1079
+ if (binding)
1080
+ partials.push({ binding, source, pattern, sameMap });
1081
+ else if (remainder)
1082
+ partials.push({ binding: remainder.binding, source, pattern, sameMap, remainder });
1083
+ else if (oneKey && sameMap) {
1084
+ const projection = projectBoundCoordinate(m, pattern[1], source.key, ns[0]);
1085
+ if (projection)
1086
+ partials.push({ binding: projection.binding, source, pattern, sameMap, projection });
1087
+ }
1088
+ }
1089
+ const seen = new Set(), countLaw = lawReads(l, more).some(([mp]) => !!m.counts?.[mp]);
1090
+ const add = (binding, sources, conflicts) => { if (!ns.every(n => binding[n]))
1091
+ return; const tuple = ns.map(n => binding[n]), id = json([conflicts.length ? 'mixed' : 'coherent', tuple]); if (seen.has(id))
1092
+ return; seen.add(id); const s = score(tuple, sources); const joined = !conflicts.length && sources.length === 2 && sources.every(p => p.source.kind === 'read' && p.sameMap && !p.projection) && Object.entries(sources[0].binding).some(([slot, e]) => e.op === 'var' && selectedWitnesses.has(e.name) && json(e) === json(sources[1].binding[slot])); if (mode === 'live' && (!joined || sources[0].pattern[0] === sources[1].pattern[0]))
1093
+ return; if (s < 100 && !joined && !sources.some(x => x.source.kind === 'own') && !sources.some(x => x.remainder) && !(oneKey && tuple.some(t => t.op === 'var' && selectedWitnesses.has(t.name)) && sources.some(p => p.source.kind === 'read' && p.sameMap)))
1094
+ return; const c = { law: l.name, tuple, sources, coherent: !conflicts.length, conflicts, score: s, countLaw }; (conflicts.length ? mixed : candidates).push(c); };
1095
+ for (const p of partials) {
1096
+ if (!more())
1097
+ break sourceLaws;
1098
+ add(p.binding, [p], []);
1099
+ }
1100
+ if (mode !== 'live')
1101
+ for (let i = 0; i < partials.length; i++)
1102
+ for (let j = i + 1; j < partials.length; j++) {
1103
+ if (!more())
1104
+ break sourceLaws;
1105
+ const a = partials[i], b = partials[j];
1106
+ if (a.source.kind === 'read' && b.source.kind === 'read')
1107
+ continue;
1108
+ const overlap = Object.keys(a.binding).filter(n => b.binding[n] && json(a.binding[n]) !== json(b.binding[n]));
1109
+ if (!overlap.length)
1110
+ add({ ...a.binding, ...b.binding }, [a, b], []);
1111
+ else {
1112
+ add({ ...a.binding, ...b.binding }, [a, b], overlap);
1113
+ add({ ...b.binding, ...a.binding }, [a, b], overlap);
1114
+ }
1115
+ }
1116
+ // Index read/read joins by the SAME bound slot and CURRENT selected witness before pairing.
1117
+ const buckets = new Map(), indices = new Map(partials.map((p, i) => [p, i]));
1118
+ for (const p of partials)
1119
+ if (p.source.kind === 'read' && p.sameMap && !p.projection)
1120
+ for (const [slot, e] of Object.entries(p.binding))
1121
+ if (e.op === 'var' && selectedWitnesses.has(e.name)) {
1122
+ const id = json([slot, e.name]), bucket = buckets.get(id) ?? [];
1123
+ bucket.push(p);
1124
+ buckets.set(id, bucket);
1125
+ }
1126
+ const paired = new Set();
1127
+ livePairs: for (const bucket of buckets.values())
1128
+ for (let i = 0; i < bucket.length; i++)
1129
+ for (let j = i + 1; j < bucket.length; j++) {
1130
+ if (!more())
1131
+ break sourceLaws;
1132
+ const a = bucket[i], b = bucket[j], sameMap = a.pattern[0] === b.pattern[0];
1133
+ if (mode === 'live' && sameMap || mode === 'cold' && !sameMap)
1134
+ continue;
1135
+ if (pairBudget.work >= livePairLimit) {
1136
+ livePairExhausted = true;
1137
+ break livePairs;
1138
+ }
1139
+ const id = json([indices.get(a), indices.get(b)]);
1140
+ if (paired.has(id))
1141
+ continue;
1142
+ paired.add(id);
1143
+ livePairWork++;
1144
+ pairBudget.work++;
1145
+ const overlap = Object.keys(a.binding).filter(n => b.binding[n] && json(a.binding[n]) !== json(b.binding[n]));
1146
+ if (overlap.length)
1147
+ continue;
1148
+ add({ ...a.binding, ...b.binding }, [a, b], []);
1149
+ }
1150
+ }
1151
+ const out = { ...at }, added = [];
1152
+ const append = (c) => { if (added.length >= cap)
1153
+ return; const n = c.tuple.length, had = out[c.law] ?? []; if (!n || had.length % n || had.length / n >= 4)
1154
+ return; for (let i = 0; i < had.length; i += n)
1155
+ if (json(had.slice(i, i + n)) === json(c.tuple))
1156
+ return; out[c.law] = [...had, ...c.tuple]; added.push(c); };
1157
+ if (mode !== 'live' && own.forall)
1158
+ append({ law: own.name, tuple: ownTerms, sources: [], coherent: true, conflicts: [], score: Infinity, countLaw: false });
1159
+ const existed = (c) => { const old = at[c.law] ?? [], n = c.tuple.length; for (let i = 0; i < old.length; i += n)
1160
+ if (json(old.slice(i, i + n)) === json(c.tuple))
1161
+ return true; return false; };
1162
+ const witnessComplete = (c) => c.coherent && (c.sources.some(p => p.source.kind === 'read' && p.sameMap && !p.projection && Object.keys(p.binding).length === c.tuple.length && [...names(p.source.key)].some(n => selectedWitnesses.has(n))) || c.sources.length === 2 && c.sources.every(p => p.source.kind === 'read' && p.sameMap && !p.projection) && Object.entries(c.sources[0].binding).some(([slot, e]) => e.op === 'var' && selectedWitnesses.has(e.name) && json(e) === json(c.sources[1].binding[slot])));
1163
+ const ownAnchor = (c) => c.coherent && c.sources.some(p => p.source.kind === 'own');
1164
+ const compare = (a, b) => Number(witnessComplete(b)) - Number(witnessComplete(a)) || Number(ownAnchor(b)) - Number(ownAnchor(a)) || b.score - a.score;
1165
+ // Deduplicate against existing instances BEFORE the unchanged per-law4/global64 limits.
1166
+ // Count-read laws remain first; complete current witness/read bindings, then coherent own anchors.
1167
+ const byLaw = new Map();
1168
+ for (const c of candidates)
1169
+ if (c.law !== own.name && !existed(c)) {
1170
+ const row = byLaw.get(c.law) ?? [];
1171
+ row.push(c);
1172
+ byLaw.set(c.law, row);
1173
+ }
1174
+ const queues = [...byLaw.values()].map(q => q.sort(compare).slice(0, 4)).sort((a, b) => Number(b[0].countLaw) - Number(a[0].countLaw));
1175
+ for (const tier of [true, false])
1176
+ for (let round = 0; round < 4 && added.length < cap; round++)
1177
+ for (const q of queues)
1178
+ if (q[0].countLaw === tier && q[round])
1179
+ append(q[round]);
1180
+ const identity = (c) => json([c.law, c.tuple]), selectedIds = new Set(added.map(identity)), limited = new Set(queues.flat().map(identity));
1181
+ const proposals = candidates.slice(0, 128).map(c => ({ law: c.law, tuple: c.tuple, provenance: c.sources.map(p => ({ kind: p.projection ? 'coordinate-projection' : p.remainder ? 'affine-remainder-exact' : 'exact-read-match', pattern: p.pattern, source: p.source, binding: p.binding, ...(p.projection ? { unmatchedFixed: p.projection.unmatchedFixed, sourceCoordinates: p.projection.sourceCoordinates } : {}), ...(p.remainder ? { remainder: p.remainder } : {}) })), priority: [Number(witnessComplete(c)), Number(ownAnchor(c)), c.score], score: c.score, status: existed(c) ? 'already-existing' : selectedIds.has(identity(c)) ? 'admitted' : limited.has(identity(c)) ? 'global-cap-excluded' : 'per-law-cap-excluded' }));
1182
+ return { proposals, at: added.length ? out : at, added, mixed: mixed.sort((a, b) => b.score - a.score).slice(0, 128), summary: { provenanceLimit: 128, omittedProvenance: Math.max(0, candidates.length - 128), livePairWork, livePairLimit, livePairExhausted, anchors, candidates: candidates.length, mixedAlternatives: mixed.length, admitted: added.length, perLawLimit: 4, cap, rawFocusSupplied: rawNegatedPost !== undefined, selectedWitnesses: [...selectedWitnesses], directCountMaps: [...directCounts], writeVariables: [...writeVars], allTuplesGenuinePRE: true, noMixedTupleAdmitted: true } };
1183
+ }
1184
+ function presentPremises(hyps, more) { const out = new Set(); for (const h of hyps) {
1185
+ if (!more())
1186
+ break;
1187
+ out.add(json(h));
1188
+ } return out; }
1189
+ const hasVar = (v, n) => !!v && typeof v === 'object' && (v.op === 'var' && v.name === n || Object.values(v).some(x => hasVar(x, n)));
1190
+ // Recognize only range predicates on a primitive cell at the bare key. An implication's
1191
+ // guard is inspected structurally, NEVER removed from the law used by the kernel.
1192
+ export function bareRangeMap(m, l, more = candidateWork().tick) {
1193
+ if (!l.forall || l.keys?.length || l.some?.length)
1194
+ return;
1195
+ const n = l.forall, primitive = (mp) => Object.hasOwn(m.maps ?? {}, mp) && !Object.hasOwn(m.counts ?? {}, mp);
1196
+ const bound = (e) => e.op === 'const' ? Number.isSafeInteger(e.value) && e.value >= 0 : e.op === 'var' ? m.params.includes(e.name) : e.op === 'add' || e.op === 'sub' || e.op === 'min' || e.op === 'max' ? bound(e.a) && bound(e.b) : e.op === 'mul' ? Number.isSafeInteger(e.k) && e.k >= 0 && bound(e.a) : false;
1197
+ const range = (c) => {
1198
+ if (!more())
1199
+ return;
1200
+ if (c.op === 'or' && c.xs.length === 2) {
1201
+ const neg = c.xs.filter(x => x.op === 'not'), rest = c.xs.filter(x => x.op !== 'not');
1202
+ if (neg.length === 1 && rest.length === 1)
1203
+ return range(rest[0]);
1204
+ }
1205
+ if (c.op === 'and' || c.op === 'or') {
1206
+ const maps = c.xs.map(range);
1207
+ return maps.length && maps[0] && maps.every(mp => mp === maps[0]) ? maps[0] : undefined;
1208
+ }
1209
+ if (c.op !== '<' && c.op !== '<=' && c.op !== '=')
1210
+ return;
1211
+ const cell = (e) => e.op === 'get' && primitive(e.map) && e.key.op === 'var' && e.key.name === n ? e.map : undefined;
1212
+ return cell(c.a) && bound(c.b) ? cell(c.a) : cell(c.b) && bound(c.a) ? cell(c.b) : undefined;
1213
+ };
1214
+ return range(l.holds);
1215
+ }
1216
+ export function seededBoundMaps(m, laws, seeds) {
1217
+ const maps = new Set();
1218
+ for (const seed of seeds) {
1219
+ const law = laws.find(l => l.name === seed.law);
1220
+ if (!law || !vacuousCountBinder(m, law))
1221
+ throw Error('target source must be an actually seeded vacuous PRE law');
1222
+ for (const [map] of readTuples(law.holds)) {
1223
+ const d = m.counts?.[map];
1224
+ if (d && genuinelyKeyless(d))
1225
+ maps.add(map);
1226
+ }
1227
+ }
1228
+ return maps;
1229
+ }
1230
+ export function targetKeylessMeets(m, decls, cert, rawPost, sourceMaps, more = candidateWork().tick) {
1231
+ const directions = rawPost ? postDirections(rawPost, decls).filter(d => d.directions.includes('upper')) : [], reads = new Map(cert.reads.map(r => [r[0], r]));
1232
+ return cert.insts.filter(i => more() && i.unit === -1 && i.terms.length === 2 && i.terms.every(([k]) => k === 1) && i.terms.some(([, id]) => { const r = reads.get(id); return r && directions.some(d => r[1] === d.map.slice(0, -1) && keyId(r[2]) === keyId(d.key) && i.terms.some(([, other]) => { const s = reads.get(other), def = s && decls.find(d => d.map === s[1]); return other !== id && !!def && sourceMaps.has(def.map) && genuinelyKeyless(def); })); }));
1233
+ }
1234
+ export function targetKindMatches(m, laws, decls, cert, rawPost, sourceMaps, more = candidateWork().tick) {
1235
+ const boundedReads = (value) => readTuples(value, more);
1236
+ const out = [], seen = new Set();
1237
+ for (const i of targetKeylessMeets(m, decls, cert, rawPost, sourceMaps, more)) {
1238
+ if (!more())
1239
+ return out;
1240
+ // Reuse the kernel's exact CountInst substitution, not a recreated packed-key formula.
1241
+ const body = mcGoal([], decls, { reads: cert.reads, insts: [i], picks: [] })?.hyps.at(-1);
1242
+ if (!body)
1243
+ throw Error('selected target meet cannot reify');
1244
+ for (const [map, key] of boundedReads(body)) {
1245
+ if (!more())
1246
+ return out;
1247
+ if (!hasVar(key, i.wit))
1248
+ continue;
1249
+ for (const l of laws) {
1250
+ if (!more())
1251
+ return out;
1252
+ if (bareRangeMap(m, l, more) !== map)
1253
+ continue;
1254
+ const id = json([l.name, key]);
1255
+ if (seen.has(id))
1256
+ continue;
1257
+ seen.add(id);
1258
+ out.push({ law: l.name, tuple: [key], map, witness: i.wit, body, premise: substC(l.holds, { vars: { [l.forall]: key }, maps: {}, flags: {} }) });
1259
+ }
1260
+ }
1261
+ }
1262
+ return out;
1263
+ }
1264
+ // Root reads propose arguments to quantified flags. Temporary bindings of fixed
1265
+ // globals select the argument only; the emitted flag body retains those globals.
1266
+ export function rootFlagMatches(m, own, more = candidateWork().tick) {
1267
+ const ns = vars(own), binding = Object.fromEntries(ns.map((n, i) => [n, x(i === 0 ? n + '#' : n)])), root = substC(own.holds, { vars: binding, maps: {}, flags: {} }), rootReads = readTuples(root, more), live = names(root), globals = new Set([...m.params, ...m.inputs, ...Object.keys(m.state)]);
1268
+ const out = [], seen = new Set();
1269
+ for (const [name, q] of Object.entries(m.step.flags ?? {})) {
1270
+ if (!more())
1271
+ return out;
1272
+ if (q.op !== 'all' || q.keys?.length)
1273
+ continue;
1274
+ for (const [map, pattern] of readTuples(q.c, more))
1275
+ for (const [actualMap, actual] of rootReads) {
1276
+ if (!more())
1277
+ return out;
1278
+ if (map !== actualMap)
1279
+ continue;
1280
+ const fixed = [...names(pattern)].filter(n => n !== q.key && globals.has(n)), binders = [q.key, ...fixed];
1281
+ const matching = matchRead(pattern, actual, binders) ?? matchAffineRemainder(pattern, actual, binders, live)?.binding, term = matching?.[q.key];
1282
+ if (!matching || !term || keyId(substE(pattern, { vars: matching, maps: {}, flags: {} })) !== keyId(actual))
1283
+ continue;
1284
+ const law = '?' + name, id = json([law, keyId(term)]);
1285
+ if (seen.has(id))
1286
+ continue;
1287
+ seen.add(id);
1288
+ const originalBody = substC(q.c, { vars: { [q.key]: term }, maps: {}, flags: {} });
1289
+ out.push({ law, tuple: [term], map, pattern, actual, matchingOnly: matching, premise: { op: 'or', xs: [{ op: '=', a: x(law), b: { op: 'const', value: 0 } }, originalBody] } });
1290
+ }
1291
+ }
1292
+ return out;
1293
+ }
1294
+ export function targetFlagMatches(m, decls, cert, rawPost, sourceMaps, more = candidateWork().tick) {
1295
+ const boundedReads = (value) => readTuples(value, more);
1296
+ const out = [], seen = new Set();
1297
+ for (const i of targetKeylessMeets(m, decls, cert, rawPost, sourceMaps, more)) {
1298
+ if (!more())
1299
+ return out;
1300
+ const body = mcGoal([], decls, { reads: cert.reads, insts: [i], picks: [] })?.hyps.at(-1);
1301
+ if (!body)
1302
+ throw Error('target flag source cannot reify');
1303
+ for (const [name, q] of Object.entries(m.step.flags ?? {})) {
1304
+ if (!more())
1305
+ return out;
1306
+ if (q.op !== 'all' || q.keys?.length)
1307
+ continue;
1308
+ for (const [map, pattern] of boundedReads(q.c)) {
1309
+ if (!more())
1310
+ return out;
1311
+ const fixed = fixedStateCoordinates(m, pattern, q.key);
1312
+ if (!fixed.length)
1313
+ continue;
1314
+ for (const [actualMap, actual] of boundedReads(body)) {
1315
+ if (!more())
1316
+ return out;
1317
+ if (map !== actualMap)
1318
+ continue;
1319
+ const match = matchAffineRemainder(pattern, actual, [q.key, ...fixed.map(p => p.name)], new Set([i.wit])), term = match?.binding[q.key];
1320
+ if (!match || !term)
1321
+ continue;
1322
+ const law = '?' + name, id = json([law, term]);
1323
+ if (seen.has(id))
1324
+ continue;
1325
+ seen.add(id);
1326
+ // The kernel closes this instance with ?flag=0 OR its ORIGINAL body, not match.binding's fixed-state substitutions.
1327
+ const originalBody = substC(q.c, { vars: { [q.key]: term }, maps: {}, flags: {} });
1328
+ out.push({ law, tuple: [term], witness: i.wit, map, pattern, actual, matchingOnly: match.binding, fixed, domain: { op: '<=', a: x(law), b: { op: 'const', value: 1 } }, premise: { op: 'or', xs: [{ op: '=', a: x(law), b: { op: 'const', value: 0 } }, originalBody] } });
1329
+ }
1330
+ }
1331
+ }
1332
+ }
1333
+ return out;
1334
+ }
1335
+ export function targetReadMatches(m, laws, decls, cert, rawPost, sourceMaps, more = candidateWork().tick) {
1336
+ const boundedReads = (value) => readTuples(value, more);
1337
+ const out = [], seen = new Set();
1338
+ for (const i of targetKeylessMeets(m, decls, cert, rawPost, sourceMaps, more)) {
1339
+ if (!more())
1340
+ return out;
1341
+ const body = mcGoal([], decls, { reads: cert.reads, insts: [i], picks: [] })?.hyps.at(-1);
1342
+ if (!body)
1343
+ throw Error('priority target cannot reify');
1344
+ for (const [map, actual] of boundedReads(body)) {
1345
+ if (!more())
1346
+ return out;
1347
+ if (!hasVar(actual, i.wit) || Object.hasOwn(m.counts ?? {}, map))
1348
+ continue;
1349
+ for (const l of laws) {
1350
+ if (!more())
1351
+ return out;
1352
+ const ns = [l.forall, ...(l.keys ?? [])].filter((x) => !!x);
1353
+ if (ns.length < 2 || lawReads(l, more).some(([mp]) => Object.hasOwn(m.counts ?? {}, mp)))
1354
+ continue;
1355
+ for (const [patternMap, pattern] of lawReads(l, more)) {
1356
+ if (!more())
1357
+ return out;
1358
+ if (map !== patternMap)
1359
+ continue;
1360
+ const binding = matchRead(pattern, actual, ns);
1361
+ if (!binding || !ns.every(n => binding[n]) || !Object.values(binding).some(e => hasVar(e, i.wit)))
1362
+ continue;
1363
+ if (keyId(substE(pattern, { vars: binding, maps: {}, flags: {} })) !== keyId(actual))
1364
+ throw Error('complete current read did not reconstruct');
1365
+ const tuple = ns.map(n => binding[n]), id = json([l.name, tuple]);
1366
+ if (seen.has(id))
1367
+ continue;
1368
+ seen.add(id);
1369
+ out.push({ law: l.name, tuple, witness: i.wit, map, pattern, actual, premise: substC(l.holds, { vars: binding, maps: {}, flags: {} }) });
1370
+ }
1371
+ }
1372
+ }
1373
+ }
1374
+ return out;
1375
+ }
1376
+ // Actual free PRE reads reachable from the target's updates. Quantified bodies
1377
+ // and bulk-map binders are not free sources; disconnected flag definitions are
1378
+ // not traversed. This proposes terms only, never a transition or packed equality.
1379
+ export function transitionReads(m, own, more = candidateWork().tick) {
1380
+ const out = [], seen = new Set(), flags = new Set();
1381
+ const globals = new Set([...m.params, ...m.inputs, ...Object.keys(m.state)]), variables = names(own.holds), maps = new Set(readTuples(own.holds, more).map(([map]) => map)), expanded = new Set();
1382
+ for (const map of maps) {
1383
+ if (!more())
1384
+ return out;
1385
+ const d = m.counts?.[map];
1386
+ if (!d || expanded.has(map))
1387
+ continue;
1388
+ expanded.add(map);
1389
+ for (const [source] of readTuples(d.body, more))
1390
+ maps.add(source);
1391
+ }
1392
+ const visit = (value, path) => {
1393
+ if (!more() || !value || typeof value !== 'object')
1394
+ return;
1395
+ if (Array.isArray(value)) {
1396
+ value.forEach((v, i) => visit(v, [...path, String(i)]));
1397
+ return;
1398
+ }
1399
+ const o = value;
1400
+ if (o.op === 'all')
1401
+ return;
1402
+ if (o.op === 'flag' && typeof o.name === 'string' && !flags.has(o.name)) {
1403
+ flags.add(o.name);
1404
+ visit(m.step.flags?.[o.name], ['step', 'flags', o.name]);
1405
+ }
1406
+ if (o.op === 'get' && typeof o.map === 'string' && o.key) {
1407
+ const key = o.key, freeNames = [...names(key)], id = readKey(o.map, key);
1408
+ if (freeNames.every(n => globals.has(n)) && !seen.has(id)) {
1409
+ seen.add(id);
1410
+ out.push({ read: [o.map, key], path, freeNames });
1411
+ }
1412
+ }
1413
+ for (const [key, v] of Object.entries(o))
1414
+ if (v && typeof v === 'object')
1415
+ visit(v, [...path, key]);
1416
+ };
1417
+ for (const [name, value] of Object.entries(m.step.state ?? {}))
1418
+ if (variables.has(name))
1419
+ visit(value, ['step', 'state', name]);
1420
+ for (const [map, update] of Object.entries(m.step.maps ?? {}))
1421
+ if (maps.has(map) && !('each' in update))
1422
+ visit(update, ['step', 'maps', map]);
1423
+ return out;
1424
+ }
1425
+ function primitiveReadKinds(m, laws, values, more) {
1426
+ const out = [], seen = new Set(), byMap = new Map();
1427
+ for (const law of laws) {
1428
+ if (!more())
1429
+ return out;
1430
+ const map = bareRangeMap(m, law, more);
1431
+ if (map) {
1432
+ const rows = byMap.get(map) ?? [];
1433
+ rows.push(law);
1434
+ byMap.set(map, rows);
1435
+ }
1436
+ }
1437
+ for (const [map, key] of readTuples(values, more))
1438
+ for (const law of byMap.get(map) ?? []) {
1439
+ if (!more())
1440
+ return out;
1441
+ const id = json([law.name, keyId(key)]);
1442
+ if (seen.has(id))
1443
+ continue;
1444
+ seen.add(id);
1445
+ out.push({ law: law.name, tuple: [key], map, premise: substC(law.holds, { vars: { [law.forall]: key }, maps: {}, flags: {} }) });
1446
+ }
1447
+ return out;
1448
+ }
1449
+ // A SINGLE actual primitive read binds every coordinate. Index before optional
1450
+ // partial-coordinate/pair exploration; no invented terms, projections or aliases.
1451
+ export function completeReadMatches(m, laws, own, decls, cert, more = candidateWork().tick, includeSelected = true) {
1452
+ const out = [], seen = new Set(), primitive = (map) => Object.hasOwn(m.maps ?? {}, map) && !Object.hasOwn(m.counts ?? {}, map);
1453
+ const byMap = new Map();
1454
+ for (const law of laws) {
1455
+ if (!more())
1456
+ return out;
1457
+ const ns = vars(law);
1458
+ if (law === own || !law.forall || law.some?.length || new Set(ns).size !== ns.length)
1459
+ continue;
1460
+ const patterns = lawReads(law, more);
1461
+ if (!more())
1462
+ return out;
1463
+ if (patterns.some(([map]) => Object.hasOwn(m.counts ?? {}, map)))
1464
+ continue;
1465
+ for (const [map, pattern] of patterns) {
1466
+ if (!more())
1467
+ return out;
1468
+ if (!primitive(map))
1469
+ continue;
1470
+ const entries = byMap.get(map) ?? [];
1471
+ entries.push({ law, ns, pattern });
1472
+ byMap.set(map, entries);
1473
+ }
1474
+ }
1475
+ const match = (source) => {
1476
+ for (const { law, ns, pattern } of byMap.get(source.read[0]) ?? []) {
1477
+ if (!more())
1478
+ return;
1479
+ const binding = matchRead(pattern, source.read[1], ns) ?? (source.kind === 'selected' ? matchAffineRemainder(pattern, source.read[1], ns, new Set([source.witness]))?.binding : undefined);
1480
+ if (!binding || !ns.every(n => Object.hasOwn(binding, n)))
1481
+ continue;
1482
+ if (keyId(substE(pattern, { vars: binding, maps: {}, flags: {} })) !== keyId(source.read[1]))
1483
+ continue;
1484
+ const tuple = ns.map(n => binding[n]), id = json([law.name, tuple]);
1485
+ if (seen.has(id))
1486
+ continue;
1487
+ seen.add(id);
1488
+ out.push({ kind: 'complete-coherent-read', coherentReadMatch: true, law: law.name, tuple, source, pattern, binding, premise: substC(law.holds, { vars: binding, maps: {}, flags: {} }) });
1489
+ }
1490
+ };
1491
+ const rootNames = vars(own).map((n, i) => i === 0 ? n + '#' : n), root = substC(own.holds, { vars: Object.fromEntries(vars(own).map((n, i) => [n, x(rootNames[i])])), maps: {}, flags: {} });
1492
+ if (!own.some?.length)
1493
+ for (const read of readTuples(root, more)) {
1494
+ if (!more())
1495
+ return out;
1496
+ // Root-bound keys, not every cold constant/range read embedded in the law.
1497
+ if (primitive(read[0]) && rootNames.some(n => hasVar(read[1], n)))
1498
+ match({ kind: 'root', read });
1499
+ }
1500
+ for (const source of transitionReads(m, own, more)) {
1501
+ if (!more())
1502
+ return out;
1503
+ if (primitive(source.read[0]))
1504
+ match({ kind: 'transition', ...source });
1505
+ }
1506
+ if (!includeSelected)
1507
+ return out;
1508
+ const needed = new Set(cert.insts.flatMap(i => i.terms.map(([, id]) => id))), liveReads = cert.reads.filter(([id]) => needed.has(id));
1509
+ const witnesses = new Set(cert.insts.map(i => i.wit)), reserved = new Set([...m.params, ...m.inputs, ...Object.keys(m.state), ...names(root)]);
1510
+ // The optional pool may have hundreds of unused reads. Match only the exact
1511
+ // live certificate closure (at most three reads per selected instance), not
1512
+ // the pool; no pool witness or unused source is admitted by this projection.
1513
+ if (cert.insts.length > 10 || liveReads.length > 30 || liveReads.length !== needed.size || witnesses.size !== cert.insts.length || cert.insts.some(i => reserved.has(i.wit) || [...names(i.below)].some(n => witnesses.has(n))) || liveReads.some(([id, , key]) => witnesses.has(id) || [...names(key)].some(n => witnesses.has(n))))
1514
+ return out;
1515
+ for (const i of cert.insts) {
1516
+ if (!more())
1517
+ return out;
1518
+ const body = mcGoal([], decls, { reads: liveReads, insts: [i], picks: [] })?.hyps.at(-1);
1519
+ if (!body)
1520
+ continue;
1521
+ for (const read of readTuples(body, more)) {
1522
+ if (!more())
1523
+ return out;
1524
+ if (primitive(read[0]) && hasVar(read[1], i.wit))
1525
+ match({ kind: 'selected', read, witness: i.wit });
1526
+ }
1527
+ }
1528
+ return out;
1529
+ }
1530
+ export function ownPREMatches(m, laws, own, decls, cert, rawPost, sourceMaps, preHyps, more = candidateWork().tick) {
1531
+ const ns = [own.forall, ...(own.keys ?? [])].filter((n) => !!n), out = [], seen = new Set(), reads = new Map(cert.reads.map(r => [r[0], r]));
1532
+ if (ns.length < 2)
1533
+ return out;
1534
+ const present = presentPremises(preHyps, more), patterns = lawReads(own, more), sources = laws.filter(l => more() && l !== own && !l.forall && !l.keys?.length && !l.some?.length && present.has(json(l.holds)));
1535
+ for (const i of targetKeylessMeets(m, decls, cert, rawPost, sourceMaps, more))
1536
+ for (const [, id] of i.terms) {
1537
+ if (!more())
1538
+ return out;
1539
+ const count = reads.get(id);
1540
+ if (!count || !Object.hasOwn(m.counts ?? {}, count[1]))
1541
+ continue;
1542
+ for (const [map, pattern] of patterns) {
1543
+ if (!more())
1544
+ return out;
1545
+ if (map !== count[1])
1546
+ continue;
1547
+ const anchor = matchRead(pattern, count[2], ns);
1548
+ if (!anchor || !Object.keys(anchor).length)
1549
+ continue;
1550
+ if (keyId(substE(pattern, { vars: anchor, maps: {}, flags: {} })) !== keyId(count[2]))
1551
+ continue;
1552
+ for (const source of sources)
1553
+ for (const sourceRead of lawReads(source, more)) {
1554
+ if (!more())
1555
+ return out;
1556
+ if (!Object.hasOwn(m.maps ?? {}, sourceRead[0]))
1557
+ continue;
1558
+ for (const [otherMap, otherPattern] of patterns) {
1559
+ if (!more())
1560
+ return out;
1561
+ if (otherMap !== sourceRead[0])
1562
+ continue;
1563
+ const other = matchRead(otherPattern, sourceRead[1], ns);
1564
+ if (!other || !Object.keys(other).some(k => !anchor[k]) || Object.keys(anchor).some(k => other[k] && keyId(anchor[k]) !== keyId(other[k])))
1565
+ continue;
1566
+ const binding = { ...anchor, ...other };
1567
+ if (!ns.every(n => binding[n]))
1568
+ continue;
1569
+ if (keyId(substE(otherPattern, { vars: binding, maps: {}, flags: {} })) !== keyId(sourceRead[1]))
1570
+ continue;
1571
+ const tuple = ns.map(n => binding[n]), identity = json(tuple);
1572
+ if (seen.has(identity))
1573
+ continue;
1574
+ seen.add(identity);
1575
+ out.push({ law: own.name, tuple, witness: i.wit, countRead: [count[1], count[2]], sourceLaw: source.name, sourcePremise: source.holds, sourceRead, premise: substC(own.holds, { vars: binding, maps: {}, flags: {} }) });
1576
+ }
1577
+ }
1578
+ }
1579
+ }
1580
+ return out;
1581
+ }
1582
+ const nonnegative = (e) => { const a = linOfE(e); return !!a && Object.values(a).every(k => Number.isSafeInteger(k) && k >= 0); };
1583
+ export function remainingCoordinateProposals(m, laws, decls, cert, rawPost, sourceMaps, preHyps, more = candidateWork().tick, own) {
1584
+ const boundedReads = (value) => readTuples(value, more);
1585
+ const out = [], seen = new Set(), useful = new Map(), ownWriteKeys = new Set(), reads = new Map(cert.reads.map(r => [r[0], r])), directions = rawPost ? postDirections(rawPost, decls).filter(d => d.directions.includes('upper')) : [];
1586
+ const primitive = (map) => Object.hasOwn(m.maps ?? {}, map) && !Object.hasOwn(m.counts ?? {}, map);
1587
+ const present = presentPremises(preHyps, more), sources = [];
1588
+ for (const l of laws)
1589
+ if (more() && !l.forall && !l.keys?.length && !l.some?.length && present.has(json(l.holds)))
1590
+ for (const read of lawReads(l, more))
1591
+ sources.push({ read, law: l.name, premise: l.holds });
1592
+ const preReads = boundedReads(preHyps), anchors = [];
1593
+ if (own) {
1594
+ const ns = vars(own), binding = Object.fromEntries(ns.map((n, i) => [n, x(i === 0 ? n + '#' : n)])), rootReads = boundedReads(substC(own.holds, { vars: binding, maps: {}, flags: {} })), rootKeys = new Set(rootReads.map(([, key]) => keyId(key))), ownMaps = new Set(rootReads.map(([map]) => map));
1595
+ for (const [map, w] of Object.entries(m.step.maps ?? {}))
1596
+ if (more() && ownMaps.has(map) && !('each' in w))
1597
+ ownWriteKeys.add(keyId(w.key));
1598
+ // These are genuine concrete PRE terms, not inferred aliases between cells.
1599
+ // Other primitive maps must actually occur at the exact root key in PRE.
1600
+ for (const read of [...rootReads, ...preReads])
1601
+ if (more() && primitive(read[0]) && rootKeys.has(keyId(read[1])))
1602
+ anchors.push({ read, rootLinked: true });
1603
+ const scope = new Set([...m.params, ...m.inputs, ...Object.keys(m.state)]), concrete = (key) => [...names(key)].every(n => scope.has(n));
1604
+ const concreteStep = { ...m.step, maps: Object.fromEntries(Object.entries(m.step.maps ?? {}).filter(([, w]) => !('each' in w))) };
1605
+ for (const read of boundedReads(concreteStep))
1606
+ if (primitive(read[0]) && concrete(read[1]))
1607
+ sources.push({ read, kind: 'read' });
1608
+ for (const [map, w] of Object.entries(m.step.maps ?? {}))
1609
+ if (more() && primitive(map) && !('each' in w) && concrete(w.key))
1610
+ sources.push({ read: [map, w.key], kind: 'write' });
1611
+ }
1612
+ for (const i of targetKeylessMeets(m, decls, cert, rawPost, sourceMaps, more))
1613
+ for (const [, id] of i.terms) {
1614
+ if (!more())
1615
+ return out;
1616
+ const count = reads.get(id);
1617
+ if (!count || !directions.some(d => d.map === count[1] + '#' && keyId(d.key) === keyId(count[2])))
1618
+ continue;
1619
+ for (const read of preReads)
1620
+ if (more() && primitive(read[0]) && keyId(read[1]) === keyId(count[2]))
1621
+ anchors.push({ read, witness: i.wit, countRead: [count[1], count[2]] });
1622
+ }
1623
+ // Exact own-write keys rank genuine source terms; this NEVER equates cells.
1624
+ sources.sort((a, b) => Number(ownWriteKeys.has(keyId(b.read[1]))) - Number(ownWriteKeys.has(keyId(a.read[1]))) || Number(b.kind === 'write') - Number(a.kind === 'write') || json(a.read).localeCompare(json(b.read)));
1625
+ anchors.sort((a, b) => Number(!!b.rootLinked) - Number(!!a.rootLinked) || keyId(a.read[1]).localeCompare(keyId(b.read[1])) || json(a.read).localeCompare(json(b.read)));
1626
+ const anchorSeen = new Set(), patternsByLaw = new Map();
1627
+ for (const a of anchors) {
1628
+ if (!more())
1629
+ return out;
1630
+ const anchorRead = a.read, aid = json(anchorRead);
1631
+ if (anchorSeen.has(aid))
1632
+ continue;
1633
+ anchorSeen.add(aid);
1634
+ for (const law of laws) {
1635
+ if (!more())
1636
+ return out;
1637
+ const ns = vars(law), group = json([law.name, keyId(anchorRead[1])]);
1638
+ if (!law.forall || law.some?.length || ns.length < 2 || new Set(ns).size !== ns.length || (useful.get(group) ?? 0) >= 4)
1639
+ continue;
1640
+ let patterns = patternsByLaw.get(law);
1641
+ if (!patterns) {
1642
+ patterns = lawReads(law, more).slice().sort((a, b) => json(a).localeCompare(json(b)));
1643
+ patternsByLaw.set(law, patterns);
1644
+ }
1645
+ for (const [map, anchorPattern] of patterns) {
1646
+ if (!more())
1647
+ return out;
1648
+ if (map !== anchorRead[0])
1649
+ continue;
1650
+ const anchor = matchRead(anchorPattern, anchorRead[1], ns);
1651
+ if (!anchor || !Object.keys(anchor).length || keyId(substE(anchorPattern, { vars: anchor, maps: {}, flags: {} })) !== keyId(anchorRead[1]))
1652
+ continue;
1653
+ const missing = ns.filter(n => !Object.hasOwn(anchor, n));
1654
+ if (missing.length !== 1)
1655
+ continue;
1656
+ const remaining = missing[0];
1657
+ for (const [otherMap, sourcePattern] of patterns) {
1658
+ if (!more())
1659
+ return out;
1660
+ if (otherMap !== map || json(sourcePattern) === json(anchorPattern) || !nonnegative(sourcePattern))
1661
+ continue;
1662
+ // Fixed coordinates are used only to find the one missing term. A conflicting
1663
+ // counterpart is provenance, never a coherent match or an equality premise.
1664
+ const fixedView = { ...m, state: { ...m.state, ...anchor } };
1665
+ for (const source of sources) {
1666
+ if (!more())
1667
+ return out;
1668
+ if ((useful.get(group) ?? 0) >= 4)
1669
+ break;
1670
+ const sourceRead = source.read;
1671
+ if (sourceRead[0] !== map || !nonnegative(sourceRead[1]))
1672
+ continue;
1673
+ const projection = projectBoundCoordinate(fixedView, sourcePattern, sourceRead[1], remaining), term = projection?.binding[remaining];
1674
+ if (!projection || !term || Object.keys(projection.binding).length !== 1)
1675
+ continue;
1676
+ const binding = { ...anchor, [remaining]: term }, tuple = ns.map(n => binding[n]), identity = json([law.name, tuple]);
1677
+ if (seen.has(identity))
1678
+ continue;
1679
+ if (keyId(substE(anchorPattern, { vars: binding, maps: {}, flags: {} })) !== keyId(anchorRead[1]))
1680
+ throw Error('term proposal changed anchor');
1681
+ const counterpart = matchRead(sourcePattern, sourceRead[1], ns), ignoredCounterpartCoordinates = Object.entries(anchor).flatMap(([binder, retained]) => counterpart?.[binder] && keyId(counterpart[binder]) !== keyId(retained) ? [{ binder, retained, counterpart: counterpart[binder] }] : []);
1682
+ const premise = substC(law.holds, { vars: binding, maps: {}, flags: {} });
1683
+ if (structuralTruth(premise, more) !== true)
1684
+ useful.set(group, (useful.get(group) ?? 0) + 1);
1685
+ seen.add(identity);
1686
+ out.push({ kind: 'one-remaining-coordinate-term-proposal', coherentReadMatch: false, law: law.name, tuple, ...(a.rootLinked ? { rootLinked: true } : { witness: a.witness, countRead: a.countRead }), ownWriteKeyMatch: ownWriteKeys.has(keyId(sourceRead[1])), anchorRead, anchorPattern, anchor, remaining, term, ...(source.kind ? { sourceKind: source.kind } : { sourceLaw: source.law, sourcePremise: source.premise }), sourceRead, sourcePattern, projection, ignoredCounterpartCoordinates, sourceKeyReconstructed: keyId(substE(sourcePattern, { vars: binding, maps: {}, flags: {} })) === keyId(sourceRead[1]), premise });
1687
+ }
1688
+ }
1689
+ }
1690
+ }
1691
+ }
1692
+ // Admit one proposal per distinct actual key before symmetric/source extras.
1693
+ // The full anchored law and nonalias provenance travel with every candidate.
1694
+ const byLaw = new Map();
1695
+ for (const p of out) {
1696
+ const keys = byLaw.get(p.law) ?? new Map(), id = keyId(p.anchorRead[1]), q = keys.get(id) ?? [];
1697
+ q.push(p);
1698
+ keys.set(id, q);
1699
+ byLaw.set(p.law, keys);
1700
+ }
1701
+ const ordered = [];
1702
+ for (const keys of byLaw.values()) {
1703
+ const queues = [...keys.values()].sort((a, b) => Number(!!b[0].rootLinked) - Number(!!a[0].rootLinked) || keyId(a[0].anchorRead[1]).localeCompare(keyId(b[0].anchorRead[1])));
1704
+ for (const q of queues)
1705
+ q.sort((a, b) => Number(!!b.ownWriteKeyMatch) - Number(!!a.ownWriteKeyMatch) || json(a.anchorPattern).localeCompare(json(b.anchorPattern)) || json(a.sourceRead).localeCompare(json(b.sourceRead)) || json(a.tuple).localeCompare(json(b.tuple)));
1706
+ const rounds = Math.max(0, ...queues.map(q => q.length));
1707
+ for (let i = 0; i < rounds; i++)
1708
+ for (const q of queues)
1709
+ if (q[i])
1710
+ ordered.push(q[i]);
1711
+ }
1712
+ return ordered;
1713
+ }
1714
+ // Deliberately incomplete structural truth: no solver, path assumption, source
1715
+ // alias, or arithmetic inference. Unknown means KEEP the original instance.
1716
+ function structuralTruth(c, more) {
1717
+ if (!more())
1718
+ return;
1719
+ if (c.op === 'not') {
1720
+ const v = structuralTruth(c.x, more);
1721
+ return v === undefined ? undefined : !v;
1722
+ }
1723
+ if (c.op === 'and' || c.op === 'or') {
1724
+ const vs = c.xs.map(x => structuralTruth(x, more));
1725
+ return c.op === 'and' ? (vs.includes(false) ? false : vs.every(v => v === true) ? true : undefined) : (vs.includes(true) ? true : vs.every(v => v === false) ? false : undefined);
1726
+ }
1727
+ if (c.op === '=' || c.op === '<' || c.op === '<=') {
1728
+ if (json(c.a) === json(c.b))
1729
+ return c.op !== '<';
1730
+ if (c.a.op === 'const' && c.b.op === 'const')
1731
+ return c.op === '=' ? c.a.value === c.b.value : c.op === '<' ? c.a.value < c.b.value : c.a.value <= c.b.value;
1732
+ }
1733
+ return;
1734
+ }
1735
+ function prioritizeTerms(laws, at, proposals, room, newSources, more) {
1736
+ const out = { ...at }, added = [], replacements = [], skipped = [];
1737
+ let admissionCount = 0;
1738
+ for (const p of proposals) {
1739
+ if (!more())
1740
+ break;
1741
+ const law = laws.find(l => l.name === p.law), n = p.tuple.length, old = out[p.law] ?? [];
1742
+ if (!law || !n || old.length % n || old.length / n > 4 || structuralTruth(p.premise, more) === true) {
1743
+ skipped.push(p);
1744
+ continue;
1745
+ }
1746
+ if (duplicateTerm(law, old, p.tuple))
1747
+ continue;
1748
+ if (admissionCount < room && old.length / n < 4) {
1749
+ out[p.law] = [...old, ...p.tuple];
1750
+ newSources.add(json([p.law, p.tuple]));
1751
+ added.push(p);
1752
+ admissionCount++;
1753
+ continue;
1754
+ }
1755
+ // Replacement does not create budget: same-law when per-law-full, otherwise
1756
+ // any explicitly true slot. Only this recognizer authorizes removal.
1757
+ let replaced = false;
1758
+ for (const candidate of old.length / n >= 4 ? [law] : laws) {
1759
+ if (!more())
1760
+ break;
1761
+ const width = vars(candidate).length, had = out[candidate.name] ?? [];
1762
+ if (!width || had.length % width || candidate.some?.length)
1763
+ continue;
1764
+ for (let i = 0; i < had.length; i += width) {
1765
+ if (!more())
1766
+ break;
1767
+ const tuple = had.slice(i, i + width), premise = substC(candidate.holds, { vars: Object.fromEntries(vars(candidate).map((n, j) => [n, tuple[j]])), maps: {}, flags: {} });
1768
+ if (structuralTruth(premise, more) !== true)
1769
+ continue;
1770
+ const id = json([candidate.name, tuple]), origin = newSources.has(id) ? 'new-source' : 'initial', admissionDebit = origin === 'initial' ? 1 : 0;
1771
+ if (admissionCount + admissionDebit > room)
1772
+ continue;
1773
+ admissionCount += admissionDebit;
1774
+ newSources.delete(id);
1775
+ newSources.add(json([p.law, p.tuple]));
1776
+ out[candidate.name] = [...had.slice(0, i), ...had.slice(i + width)];
1777
+ out[p.law] = [...(out[p.law] ?? []), ...p.tuple];
1778
+ replacements.push({ law: candidate.name, tuple, premise, replacement: p, reason: 'structurally-true', origin, admissionDebit });
1779
+ replaced = true;
1780
+ break;
1781
+ }
1782
+ if (replaced)
1783
+ break;
1784
+ }
1785
+ }
1786
+ return { at: out, added, replacements, skipped, admissionCount };
1787
+ }
1788
+ // A single shared budget for the entire attempt, not a separate quota per phase.
1789
+ // Priorities only select terms. Even the projection-only proposal retains every
1790
+ // anchored coordinate and every guard of the original law.
1791
+ export function sparseReadInstances(m, laws, own, at, goal, cert, cap = 64, rawPost, decls = [], sourceMaps = new Set(), preHyps = [], budget = candidateWork(), completePriority = 'current') {
1792
+ budget.mark('sources:begin');
1793
+ cap = Math.max(0, Math.min(64, cap));
1794
+ const slots = (l) => !!l.forall && (at[l.name]?.length ?? 0) / (1 + (l.keys?.length ?? 0)) < 4;
1795
+ const available = cap > 0 && (laws.some(slots) || slots(own) || Object.keys(m.step.flags ?? {}).length > 0);
1796
+ const more = budget.tick, pairBudget = { work: 0 }, sources = available ? laws.filter(l => !l.forall || slots(l)) : [];
1797
+ // Reify indispensable own PRE/flag bindings before deriving downstream reads.
1798
+ // They often expose the very second read required by a live witness join.
1799
+ const foundationalOwn = available && cert.insts.length ? ownPREMatches(m, sources, own, decls, cert, rawPost, sourceMaps, preHyps, more) : undefined;
1800
+ const foundationalRoot = available && cert.insts.length ? rootFlagMatches(m, own, more) : undefined;
1801
+ const foundationalFlags = foundationalRoot ? [...foundationalRoot, ...targetFlagMatches(m, decls, cert, rawPost, sourceMaps, more)] : undefined;
1802
+ if (foundationalFlags && foundationalOwn) {
1803
+ const next = { ...at }, found = [];
1804
+ const add = (p) => { const width = p.tuple.length, old = next[p.law] ?? []; if (!width || old.length % width || old.length / width >= 4 || found.length >= cap)
1805
+ return; for (let i = 0; i < old.length; i += width)
1806
+ if (json(old.slice(i, i + width)) === json(p.tuple))
1807
+ return; next[p.law] = [...old, ...p.tuple]; found.push({ law: p.law, tuple: p.tuple, coherent: true, conflicts: [], score: Infinity, countLaw: false, sources: [] }); };
1808
+ for (const p of foundationalFlags)
1809
+ add(p);
1810
+ const flagAdmissions = found.length;
1811
+ for (const p of foundationalOwn)
1812
+ add(p);
1813
+ if (found.length) {
1814
+ const empty = emptyReadResult(next, cap);
1815
+ budget.mark('sources:foundation');
1816
+ return { ...empty, added: found, completeMatches: [], readKindMatches: [], termProposals: [], vacuousTermProposals: [], ownMatches: foundationalOwn, priorityMatches: [], rootFlags: foundationalRoot ?? [], flagMatches: foundationalFlags, kindMatches: [], summary: { ...empty.summary, foundationBarrier: true, completeReadAdmissions: 0, liveReadAdmissions: 0, readKindAdmissions: 0, termProposalAdmissions: 0, ownPREAdmissions: found.length - flagAdmissions, flagAdmissions, sharedGlobalBudget: true, generationWork: { ...budget.state } } };
1817
+ }
1818
+ }
1819
+ const completeMatches = available ? completeReadMatches(m, sources, own, decls, cert, more, completePriority === 'current') : [];
1820
+ budget.mark('sources:complete');
1821
+ const liveMatches = available && cert.insts.length ? baseReadInstances(m, sources, own, at, goal, cert, cap, rawPost, more, 'live', pairBudget) : emptyReadResult(at, cap);
1822
+ const readKindMatches = available ? primitiveReadKinds(m, sources, completeMatches.map(p => p.premise), more) : [];
1823
+ const termProposals = available ? remainingCoordinateProposals(m, sources, decls, cert, rawPost, sourceMaps, preHyps, more, own) : [];
1824
+ budget.mark('sources:terms');
1825
+ const ownMatches = foundationalOwn ?? (available ? ownPREMatches(m, sources, own, decls, cert, rawPost, sourceMaps, preHyps, more) : []);
1826
+ const priorityMatches = available ? targetReadMatches(m, sources.filter(l => l !== own), decls, cert, rawPost, sourceMaps, more) : [];
1827
+ const rootFlags = foundationalRoot ?? (available ? rootFlagMatches(m, own, more) : []);
1828
+ const flagMatches = foundationalFlags ?? (available ? [...rootFlags, ...targetFlagMatches(m, decls, cert, rawPost, sourceMaps, more)] : []);
1829
+ const kindMatches = available ? targetKindMatches(m, sources, decls, cert, rawPost, sourceMaps, more) : [];
1830
+ const out = { ...at }, added = [];
1831
+ const append = (p, coherent = true) => {
1832
+ const width = p.tuple.length, old = out[p.law] ?? [];
1833
+ const flag = p.law.startsWith('?'), prior = flag ? flagMatches.filter(f => f.law === p.law && old.some(t => json(t) === json(f.tuple[0]))).length : old.length / width;
1834
+ if (!width || old.length % width || prior >= 4 || added.length >= cap)
1835
+ return;
1836
+ if (!coherent && duplicateTerm(laws.find(l => l.name === p.law), old, p.tuple))
1837
+ return;
1838
+ for (let i = 0; i < old.length; i += width)
1839
+ if (json(old.slice(i, i + width)) === json(p.tuple))
1840
+ return;
1841
+ out[p.law] = [...old, ...p.tuple];
1842
+ added.push({ law: p.law, tuple: p.tuple, coherent, conflicts: [], score: Infinity, countLaw: false, sources: [] });
1843
+ };
1844
+ for (const p of completeMatches)
1845
+ if (p.source.kind === 'selected')
1846
+ append(p);
1847
+ const beforeLive = added.length;
1848
+ for (const p of liveMatches.added) {
1849
+ const before = added.length;
1850
+ append(p);
1851
+ if (added.length > before)
1852
+ added[added.length - 1] = p;
1853
+ }
1854
+ const liveReadAdmissions = added.length - beforeLive;
1855
+ for (const p of completeMatches)
1856
+ if (p.source.kind !== 'selected')
1857
+ append(p);
1858
+ const completeReadAdmissions = added.length - liveReadAdmissions;
1859
+ for (const p of readKindMatches)
1860
+ append(p);
1861
+ const readKindAdmissions = added.length - completeReadAdmissions;
1862
+ const vacuousTermProposals = [], writeAnchored = new Set(termProposals.filter(p => p.ownWriteKeyMatch).map(p => p.law));
1863
+ // Deduplication must not backfill its freed slots with lower-quality cold
1864
+ // sources when the current obligation supplies an exact write-key donor.
1865
+ for (const p of termProposals) {
1866
+ if (structuralTruth(p.premise, more) === true)
1867
+ vacuousTermProposals.push(p);
1868
+ else if (p.ownWriteKeyMatch || !writeAnchored.has(p.law))
1869
+ append(p, false);
1870
+ }
1871
+ const termProposalAdmissions = added.length - completeReadAdmissions - readKindAdmissions - liveReadAdmissions;
1872
+ for (const p of ownMatches)
1873
+ append(p);
1874
+ const ownPREAdmissions = added.length - completeReadAdmissions - readKindAdmissions - termProposalAdmissions - liveReadAdmissions;
1875
+ for (const p of priorityMatches)
1876
+ append(p);
1877
+ const beforeFlags = added.length;
1878
+ for (const p of flagMatches)
1879
+ append(p);
1880
+ const flagAdmissions = added.length - beforeFlags;
1881
+ for (const p of kindMatches)
1882
+ append(p);
1883
+ // Do not refill deduplicated preferred-source slots through the generic
1884
+ // partial-read fallback. Exact matches above remain eligible on every pass.
1885
+ const restSources = sources.filter(l => !writeAnchored.has(l.name));
1886
+ const rest = available ? baseReadInstances(m, restSources, own, added.length ? out : at, goal, cert, cap - added.length, rawPost, more, 'cold', pairBudget) : emptyReadResult(at, cap);
1887
+ budget.mark('sources:end');
1888
+ return { ...rest, added: [...added, ...rest.added], completeMatches, readKindMatches, termProposals, vacuousTermProposals, ownMatches, priorityMatches, rootFlags, flagMatches, kindMatches, summary: { ...rest.summary, foundationBarrier: false, cap, completeReadAdmissions, liveReadAdmissions, livePairWork: liveMatches.summary.livePairWork + rest.summary.livePairWork, livePairExhausted: liveMatches.summary.livePairExhausted || rest.summary.livePairExhausted, readKindAdmissions, termProposalAdmissions, ownPREAdmissions, flagAdmissions, sharedGlobalBudget: true, generationWork: { ...budget.state } } };
1889
+ }
1890
+ // Caller search keeps actual source roles and avoids high-arity/free-state
1891
+ // empirical guesses first. This is a context proposal, never an assumption.
1892
+ export function coarseContext(m, laws, caller, support) {
1893
+ const width = Math.max(1, ...Object.values(m.step.maps ?? {}).map(w => 'each' in w ? 0 : names(w.key).size));
1894
+ return laws.filter(l => { if (caller.includes(l) || support.has(l))
1895
+ return true; const rs = readTuples(l.holds); if (rs.some(([map]) => !!m.counts?.[map]))
1896
+ return true; const bound = new Set([l.forall, ...l.keys ?? [], ...l.some ?? []]), free = [...names(l.holds)].filter(v => !bound.has(v) && Object.hasOwn(m.state, v)); return !free.length && rs.length >= 2 && bound.size <= width; });
1897
+ }
1898
+ // Search context only, never an admitted invariant. Keep exact source laws and
1899
+ // order; every successful certificate must be widened and checked on the whole.
1900
+ export function sourceContext(m, laws, target, support) {
1901
+ const width = Math.max(1, ...Object.values(m.step.maps ?? {}).map(w => 'each' in w ? 0 : names(w.key).size));
1902
+ const maps = (value) => new Set(readTuples(value).map(([map]) => map)), demand = maps(target.holds);
1903
+ for (const map of demand) {
1904
+ const d = m.counts?.[map];
1905
+ if (d)
1906
+ for (const dep of maps([d.body, d.below]))
1907
+ demand.add(dep);
1908
+ }
1909
+ const countDemand = [...demand].some(map => !!m.counts?.[map]);
1910
+ const arity = (l) => Number(!!l.forall) + (l.keys?.length ?? 0), signature = (l) => json([arity(l), [...maps(l.holds)].sort()]);
1911
+ const direct = new Set(laws.filter(l => !support.has(l) && readTuples(l.holds).every(([map]) => !m.counts?.[map])).map(signature));
1912
+ return laws.filter(l => {
1913
+ if (l === target)
1914
+ return true;
1915
+ const reads = readTuples(l.holds);
1916
+ if (support.has(l))
1917
+ return maps(l.holds).size < 2 || !direct.has(signature(l));
1918
+ if (!reads.length)
1919
+ return true;
1920
+ if (reads.some(([map]) => !!m.counts?.[map]))
1921
+ return reads.some(([map]) => !!m.counts?.[map] && (demand.has(map) || countDemand && genuinelyKeyless(m.counts[map])));
1922
+ const bound = new Set([l.forall, ...l.keys ?? [], ...l.some ?? []]);
1923
+ if (arity(l) > width || [...names(l.holds)].some(v => !bound.has(v) && Object.hasOwn(m.state, v)))
1924
+ return false;
1925
+ return reads.every(([map]) => demand.has(map));
1926
+ });
1927
+ }
1928
+ export const countSignature = (c) => json([
1929
+ c.reads.map(r => [r[1], keyId(r[2])]).sort((a, b) => json(a).localeCompare(json(b))), ids(c).sort()
1930
+ ]);
1931
+ export const refinementSignature = (goal, c) => json([
1932
+ countSignature(c), [...new Set(readTuples(goal.hyps).map(([mp, key]) => json([mp, keyId(key)])))].sort(), c.insts.map(i => i.wit).sort()
1933
+ ]);
1934
+ // Keep selected picks on the ordinary, non-renaming path. Only the closed,
1935
+ // pick-free view may discard unused reads and stabilize witness identifiers.
1936
+ export function selectedCertificate(goal, decls, view, state, lazyRoom) {
1937
+ if (view.insts.length + (view.picks?.length ?? 0) > 10 || new Set(ids(view)).size !== ids(view).length)
1938
+ throw new UnsupportedCountProposal('selected semantic alias or live cap');
1939
+ if (!lazyRoom && !(view.picks?.length))
1940
+ return stableSelected(goal, decls, view, state, { lazyRoom: false, fullPoolUsed: false }).cert;
1941
+ if (new Set(view.reads.map(r => r[0])).size !== view.reads.length || new Set(view.insts.map(i => i.wit)).size !== view.insts.length)
1942
+ throw new UnsupportedCountProposal('nonunique selected read/witness');
1943
+ for (const i of view.insts)
1944
+ if (state.reserved.has(i.wit) || view.reads.some(r => r[0] === i.wit || names(r[2]).has(i.wit)) || decls.some(d => names([d.below, d.body]).has(i.wit)))
1945
+ throw new UnsupportedCountProposal('selected witness capture');
1946
+ if (!mcGoal(goal.hyps, decls, view))
1947
+ throw new UnsupportedCountProposal('selected view cannot reify');
1948
+ return { ...view, picks: view.picks ?? [], wits: view.insts.map(i => i.wit) };
1949
+ }
1950
+ export function sourceBoundMaps(m, laws, at, more = candidateWork().tick) {
1951
+ const maps = new Set();
1952
+ for (const l of laws) {
1953
+ if (!more())
1954
+ break;
1955
+ if (!at[l.name]?.some(t => t.op === 'const' && t.value === 0) || !vacuousCountBinder(m, l, more))
1956
+ continue;
1957
+ for (const [map] of readTuples(l.holds, more)) {
1958
+ const d = m.counts?.[map];
1959
+ if (d && genuinelyKeyless(d))
1960
+ maps.add(map);
1961
+ }
1962
+ }
1963
+ return maps;
1964
+ }
1965
+ // One shared generation budget covers preparation, pool construction and every
1966
+ // refinement in the target attempt. No fresh fuel is created by a source phase.
1967
+ export function prepareSupport(m, laws, own, initial, pass, budget = candidateWork()) {
1968
+ const more = budget.tick;
1969
+ budget.mark('prepare:begin');
1970
+ const limit = pass ? 32 : 64; // Keep half of the same 64 slots for actual selected witnesses.
1971
+ let at = { ...initial }, seedCount = 0;
1972
+ const newSources = new Set();
1973
+ const append = (name, tuple) => {
1974
+ const old = at[name] ?? [], width = tuple.length;
1975
+ if (!width || seedCount >= limit || old.length % width || old.length / width >= 4)
1976
+ return;
1977
+ for (let i = 0; i < old.length; i += width)
1978
+ if (json(old.slice(i, i + width)) === json(tuple))
1979
+ return;
1980
+ at[name] = [...old, ...tuple];
1981
+ newSources.add(json([name, tuple]));
1982
+ seedCount++;
1983
+ };
1984
+ const row = () => countedObligations(m, laws, { [own.name]: at }, laws.indexOf(own)).at(-1);
1985
+ if (!pass) {
1986
+ const cold = row(), ns = vars(own), root = substC(own.holds, { vars: Object.fromEntries(ns.map((n, i) => [n, x(i === 0 ? n + '#' : n)])), maps: {}, flags: {} });
1987
+ // The root and its reachable free transition reads claim range slots before
1988
+ // ambient scalar/flag witnesses. All terms still instantiate original laws.
1989
+ const reads = [...readTuples(root, more), ...transitionReads(m, own, more).map(s => s.read), ...readTuples(cold.goal.hyps, more)];
1990
+ for (const l of laws) {
1991
+ if (seedCount >= 64 || !more())
1992
+ break;
1993
+ const map = bareRangeMap(m, l, more);
1994
+ if (map)
1995
+ for (const [mp, key] of reads) {
1996
+ if (!more() || seedCount >= 64)
1997
+ break;
1998
+ if (mp === map)
1999
+ append(l.name, [key]);
2000
+ }
2001
+ }
2002
+ }
2003
+ if (pass) {
2004
+ const seeded = seedVacuousCounts(m, laws, at, limit - seedCount, more);
2005
+ at = seeded.at;
2006
+ seedCount += seeded.added.length;
2007
+ for (const s of seeded.added)
2008
+ newSources.add(json([s.law, s.tuple]));
2009
+ }
2010
+ const sourceMaps = sourceBoundMaps(m, laws, at, more);
2011
+ budget.mark('prepare:seeded');
2012
+ const cold = row(), empty = { reads: [], insts: [], picks: [], wits: [], loose: false }, cert = empty, goal = mcGoal(cold.goal.hyps, cold.decls, cert);
2013
+ budget.mark('prepare:certificate');
2014
+ const termAdmissions = [], replacements = [];
2015
+ if (goal && more()) {
2016
+ // Complete root/free-transition bindings and their exact range laws may
2017
+ // enter early. Count witnesses are deferred until a live view is selected.
2018
+ const seeds = sparseReadInstances(m, laws, own, at, goal, cert, limit - seedCount, cold.goal.hyps.at(-1), cold.decls, sourceMaps, cold.goal.hyps.slice(0, -1), budget, 'root');
2019
+ const roots = new Set([...seeds.completeMatches.filter(p => p.source.kind !== 'selected'), ...seeds.readKindMatches, ...seeds.rootFlags].map(p => json([p.law, p.tuple])));
2020
+ const proposals = new Map(seeds.termProposals.map(p => [json([p.law, p.tuple]), p]));
2021
+ for (const s of seeds.added) {
2022
+ const proposal = proposals.get(json([s.law, s.tuple]));
2023
+ // Primitive proposals keep their own provenance; they are NOT count laws.
2024
+ if (!pass || s.law === own.name || s.countLaw || proposal || roots.has(json([s.law, s.tuple]))) {
2025
+ const before = seedCount;
2026
+ append(s.law, s.tuple);
2027
+ if (proposal && seedCount > before)
2028
+ termAdmissions.push(proposal);
2029
+ }
2030
+ }
2031
+ }
2032
+ if (pass && more()) {
2033
+ // The just-produced PRE support exposes additional actual primitive anchors.
2034
+ // Revisit only this bounded term path BEFORE counts.ts's seedCount<64 gate.
2035
+ // A full law with no explicitly true slot cannot accept another term. Do
2036
+ // not enumerate it again; initial/new-source replacement debits stay below.
2037
+ const eligible = laws.filter(l => {
2038
+ if (!more())
2039
+ return false;
2040
+ if (!l.forall)
2041
+ return true;
2042
+ const ns = vars(l), old = at[l.name] ?? [], n = ns.length;
2043
+ if (n < 2 || l.some?.length || old.length % n || old.length / n > 4)
2044
+ return false;
2045
+ if (old.length / n < 4)
2046
+ return true;
2047
+ for (let i = 0; i < old.length; i += n)
2048
+ if (structuralTruth(substC(l.holds, { vars: Object.fromEntries(ns.map((name, j) => [name, old[i + j]])), maps: {}, flags: {} }), more) === true)
2049
+ return true;
2050
+ return false;
2051
+ });
2052
+ budget.mark('prepare:revisit');
2053
+ const current = eligible.some(l => !!l.forall) ? row() : undefined, proposals = current ? remainingCoordinateProposals(m, eligible, current.decls, cert, current.goal.hyps.at(-1), sourceMaps, current.goal.hyps.slice(0, -1), more, own) : [];
2054
+ const priority = prioritizeTerms(laws, at, proposals, limit - seedCount, newSources, more);
2055
+ at = priority.at;
2056
+ seedCount += priority.admissionCount;
2057
+ termAdmissions.push(...priority.added, ...priority.replacements.map(r => r.replacement));
2058
+ replacements.push(...priority.replacements);
2059
+ }
2060
+ const finalSourceMaps = replacements.length ? sourceBoundMaps(m, laws, at, more) : sourceMaps;
2061
+ budget.mark('prepare:end');
2062
+ return { at, seedCount, sourceMaps: finalSourceMaps, termAdmissions, replacements, generationWork: { ...budget.state } };
2063
+ }
2064
+ // The pool deliberately retains raw read aliases. A live selection does not:
2065
+ // one semantic id denotes one representative, never all of its raw spellings.
2066
+ export function chosenView(full, chosen, cap = 10) {
2067
+ const keys = ids(full), seen = new Set(), picks = [], insts = [];
2068
+ const admit = (id) => { if (!chosen.has(id) || seen.has(id))
2069
+ return false; if (seen.size >= Math.min(10, cap))
2070
+ throw new UnsupportedCountProposal('selected live cap'); seen.add(id); return true; };
2071
+ for (const [j, p] of (full.picks ?? []).entries())
2072
+ if (admit(keys[j]))
2073
+ picks.push(p);
2074
+ for (const [j, i] of full.insts.entries())
2075
+ if (admit(keys[j + (full.picks?.length ?? 0)]))
2076
+ insts.push(i);
2077
+ if (seen.size !== chosen.size)
2078
+ throw new UnsupportedCountProposal('selected semantic id missing');
2079
+ return { ...full, picks, insts, wits: insts.map(i => i.wit) };
2080
+ }