gdp-wired 0.47.0 → 0.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/README.md +15 -4
  2. package/dist/core/carry.d.ts +15 -0
  3. package/dist/core/carry.js +651 -0
  4. package/dist/core/cli.d.ts +3 -1
  5. package/dist/core/cli.js +28 -8
  6. package/dist/core/count-cases.d.ts +24 -0
  7. package/dist/core/count-cases.js +320 -0
  8. package/dist/core/count-cert-grow.d.ts +4 -0
  9. package/dist/core/count-cert-grow.js +37 -0
  10. package/dist/core/count-cert-transport.d.ts +3 -0
  11. package/dist/core/count-cert-transport.js +58 -0
  12. package/dist/core/count-completion.d.ts +9 -0
  13. package/dist/core/count-completion.js +27 -0
  14. package/dist/core/count-cubes.d.ts +8 -0
  15. package/dist/core/count-cubes.js +69 -0
  16. package/dist/core/count-demand.d.ts +37 -0
  17. package/dist/core/count-demand.js +361 -0
  18. package/dist/core/count-facts.d.ts +52 -0
  19. package/dist/core/count-facts.js +247 -0
  20. package/dist/core/count-focus-proof.d.ts +8 -0
  21. package/dist/core/count-focus-proof.js +140 -0
  22. package/dist/core/count-focused.d.ts +22 -0
  23. package/dist/core/count-focused.js +676 -0
  24. package/dist/core/count-ranges.d.ts +5 -0
  25. package/dist/core/count-ranges.js +65 -0
  26. package/dist/core/count-recovery/action-guard.d.ts +5 -0
  27. package/dist/core/count-recovery/action-guard.js +51 -0
  28. package/dist/core/count-recovery/boolean-core.d.ts +16 -0
  29. package/dist/core/count-recovery/boolean-core.js +258 -0
  30. package/dist/core/count-recovery/carried-case.d.ts +2 -0
  31. package/dist/core/count-recovery/carried-case.js +24 -0
  32. package/dist/core/count-recovery/conditional-check-cache.d.ts +23 -0
  33. package/dist/core/count-recovery/conditional-check-cache.js +130 -0
  34. package/dist/core/count-recovery/conditional-cuts.d.ts +6 -0
  35. package/dist/core/count-recovery/conditional-cuts.js +318 -0
  36. package/dist/core/count-recovery/conditional-proof.d.ts +19 -0
  37. package/dist/core/count-recovery/conditional-proof.js +306 -0
  38. package/dist/core/count-recovery/derivability-closure.d.ts +14 -0
  39. package/dist/core/count-recovery/derivability-closure.js +533 -0
  40. package/dist/core/count-recovery/empty-count-source.d.ts +2 -0
  41. package/dist/core/count-recovery/empty-count-source.js +40 -0
  42. package/dist/core/count-recovery/field-bound-lemmas.d.ts +23 -0
  43. package/dist/core/count-recovery/field-bound-lemmas.js +640 -0
  44. package/dist/core/count-recovery/field-case.d.ts +5 -0
  45. package/dist/core/count-recovery/field-case.js +89 -0
  46. package/dist/core/count-recovery/field-demand.d.ts +46 -0
  47. package/dist/core/count-recovery/field-demand.js +47 -0
  48. package/dist/core/count-recovery/field-only.d.ts +3 -0
  49. package/dist/core/count-recovery/field-only.js +18 -0
  50. package/dist/core/count-recovery/fold-path.d.ts +6 -0
  51. package/dist/core/count-recovery/fold-path.js +35 -0
  52. package/dist/core/count-recovery/frame-lemmas.d.ts +9 -0
  53. package/dist/core/count-recovery/frame-lemmas.js +120 -0
  54. package/dist/core/count-recovery/guard-cases.d.ts +12 -0
  55. package/dist/core/count-recovery/guard-cases.js +138 -0
  56. package/dist/core/count-recovery/key-closure.d.ts +14 -0
  57. package/dist/core/count-recovery/key-closure.js +62 -0
  58. package/dist/core/count-recovery/leaf-allowance.d.ts +4 -0
  59. package/dist/core/count-recovery/leaf-allowance.js +7 -0
  60. package/dist/core/count-recovery/lift-count-proxies.d.ts +6 -0
  61. package/dist/core/count-recovery/lift-count-proxies.js +175 -0
  62. package/dist/core/count-recovery/live-dependencies.d.ts +6 -0
  63. package/dist/core/count-recovery/live-dependencies.js +76 -0
  64. package/dist/core/count-recovery/member-inclusions.d.ts +11 -0
  65. package/dist/core/count-recovery/member-inclusions.js +168 -0
  66. package/dist/core/count-recovery/member-premises.d.ts +29 -0
  67. package/dist/core/count-recovery/member-premises.js +114 -0
  68. package/dist/core/count-recovery/natural-cases.d.ts +6 -0
  69. package/dist/core/count-recovery/natural-cases.js +59 -0
  70. package/dist/core/count-recovery/ops.d.ts +6 -0
  71. package/dist/core/count-recovery/ops.js +8 -0
  72. package/dist/core/count-recovery/pre-state-source.d.ts +8 -0
  73. package/dist/core/count-recovery/pre-state-source.js +18 -0
  74. package/dist/core/count-recovery/rebase-path.d.ts +9 -0
  75. package/dist/core/count-recovery/rebase-path.js +70 -0
  76. package/dist/core/count-recovery/rename-proof.d.ts +2 -0
  77. package/dist/core/count-recovery/rename-proof.js +102 -0
  78. package/dist/core/count-recovery/row-cases.d.ts +16 -0
  79. package/dist/core/count-recovery/row-cases.js +291 -0
  80. package/dist/core/count-recovery/scalar-guards.d.ts +7 -0
  81. package/dist/core/count-recovery/scalar-guards.js +291 -0
  82. package/dist/core/count-recovery/source-memo.d.ts +12 -0
  83. package/dist/core/count-recovery/source-memo.js +67 -0
  84. package/dist/core/count-select.d.ts +16 -0
  85. package/dist/core/count-select.js +24 -0
  86. package/dist/core/count-support.d.ts +598 -0
  87. package/dist/core/count-support.js +2080 -0
  88. package/dist/core/count-unions.d.ts +2 -0
  89. package/dist/core/count-unions.js +139 -0
  90. package/dist/core/count-witness-flags.d.ts +9 -0
  91. package/dist/core/count-witness-flags.js +37 -0
  92. package/dist/core/count-write-frames.d.ts +12 -0
  93. package/dist/core/count-write-frames.js +206 -0
  94. package/dist/core/counts.d.ts +20 -2
  95. package/dist/core/counts.js +807 -156
  96. package/dist/core/dsl.d.ts +50 -6
  97. package/dist/core/dsl.js +307 -65
  98. package/dist/core/effect.js +8 -1
  99. package/dist/core/exists.d.ts +1 -1
  100. package/dist/core/exists.js +80 -15
  101. package/dist/core/extract-check.d.ts +7 -1
  102. package/dist/core/extract-check.js +130 -13
  103. package/dist/core/extract-read.d.ts +22 -8
  104. package/dist/core/extract-read.js +29 -11
  105. package/dist/core/extract-shapes.js +122 -41
  106. package/dist/core/extract-standalone.js +53 -9
  107. package/dist/core/extract.js +9 -3
  108. package/dist/core/field-laws.d.ts +2 -0
  109. package/dist/core/field-laws.js +100 -0
  110. package/dist/core/finite-frontiers.d.ts +5 -0
  111. package/dist/core/finite-frontiers.js +116 -0
  112. package/dist/core/finite-houdini.d.ts +52 -0
  113. package/dist/core/finite-houdini.js +460 -0
  114. package/dist/core/finite-model.d.ts +13 -0
  115. package/dist/core/finite-model.js +68 -0
  116. package/dist/core/finite-tiny.d.ts +72 -0
  117. package/dist/core/finite-tiny.js +1052 -0
  118. package/dist/core/infer.d.ts +1 -1
  119. package/dist/core/infer.js +32 -9
  120. package/dist/core/laws.d.ts +2 -1
  121. package/dist/core/laws.js +47 -14
  122. package/dist/core/lemma-cuts.d.ts +38 -0
  123. package/dist/core/lemma-cuts.js +365 -0
  124. package/dist/core/machine.d.ts +39 -2
  125. package/dist/core/machine.js +240 -35
  126. package/dist/core/mutate.d.ts +55 -0
  127. package/dist/core/mutate.js +210 -0
  128. package/dist/core/native-domain.d.ts +6 -0
  129. package/dist/core/native-domain.js +114 -0
  130. package/dist/core/native-law.d.ts +3 -0
  131. package/dist/core/native-law.js +174 -0
  132. package/dist/core/quorum-laws.d.ts +5 -0
  133. package/dist/core/quorum-laws.js +239 -0
  134. package/dist/core/relational.js +10 -2
  135. package/dist/core/relevance.d.ts +4 -0
  136. package/dist/core/relevance.js +79 -0
  137. package/dist/core/runtime-wall.d.ts +3 -0
  138. package/dist/core/runtime-wall.js +4 -0
  139. package/dist/core/sample-step.d.ts +16 -0
  140. package/dist/core/sample-step.js +28 -0
  141. package/dist/core/source-check.d.ts +44 -0
  142. package/dist/core/source-check.js +126 -0
  143. package/dist/core/source-diagnostic.d.ts +1 -0
  144. package/dist/core/source-diagnostic.js +34 -0
  145. package/dist/core/support-budget.d.ts +2 -0
  146. package/dist/core/support-budget.js +6 -0
  147. package/dist/core/system.js +2 -0
  148. package/dist/core/wall.d.ts +6 -0
  149. package/dist/core/wall.js +23 -0
  150. package/dist/core/watch.js +4 -0
  151. package/dist/kernel/cdcl.d.ts +4 -0
  152. package/dist/kernel/cdcl.js +20 -5
  153. package/dist/kernel/kernel.d.ts +10 -0
  154. package/dist/kernel/kernel.js +56 -3
  155. package/dist/kernel/model-sequence.d.ts +2 -2
  156. package/dist/kernel/model-sequence.js +4 -3
  157. package/dist/kernel/model-values.d.ts +2 -0
  158. package/dist/kernel/model-values.js +60 -0
  159. package/dist/kernel/prove.d.ts +10 -0
  160. package/dist/kernel/prove.js +56 -8
  161. package/dist/kernel/prover-rows.d.ts +29 -0
  162. package/dist/kernel/prover-rows.js +114 -0
  163. package/dist/lean-kernel/emit.d.ts +39 -2
  164. package/dist/lean-kernel/emit.js +136 -24
  165. package/dist/lean-kernel/lean-terms.d.ts +1 -0
  166. package/dist/lean-kernel/lean-terms.js +13 -5
  167. package/dist/lean-kernel/library.js +4 -0
  168. package/dist/lean-kernel/qalpha.d.ts +7 -0
  169. package/dist/lean-kernel/qalpha.js +40 -0
  170. package/package.json +5 -1
@@ -17,6 +17,7 @@
17
17
  import { carriedView, compileC, evalC, evalE, fastStep, interpret, n as k, walk, x as v } from "./machine.js";
18
18
  import { clock, proveLaw, proveLaws, withDeadline, withinDeadline } from "../kernel/prove.js";
19
19
  import { env } from "./solver.js";
20
+ import { WallExpired, checkWall } from "./wall.js";
20
21
  import { ghostedMachine, ghostedOk, substC } from "../kernel/kernel.js";
21
22
  const add = (a, b) => (a.op === 'const' && a.value === 0 ? b : b.op === 'const' && b.value === 0 ? a : { op: 'add', a, b });
22
23
  const sum = (es) => es.reduce((acc, e) => add(acc, e), k(0));
@@ -168,6 +169,7 @@ const pathTo = new WeakMap();
168
169
  export function small(m, p, b, cap = 3000, work = 300_000, walks = 0) {
169
170
  // (past a thousand steps, through the generated JavaScript, fastStep: the interpreter's states, as compile.test.ts holds
170
171
  // them; a small machine's few steps cost less than its compiling)
172
+ checkWall('sample setup');
171
173
  const run = interpret(m), start = run.init(p);
172
174
  let steps = 0, fast = run.step;
173
175
  const step = (p2, st, r) => { if (++steps === 1000)
@@ -180,13 +182,51 @@ export function small(m, p, b, cap = 3000, work = 300_000, walks = 0) {
180
182
  reqs = reqs.flatMap(r => Array.from({ length: below(i) }, (_, x) => ({ ...r, [i]: x })));
181
183
  for (const c of m.inputMaps ?? [])
182
184
  reqs = reqs.flatMap(r => subsets.map(s => ({ ...r, [c]: s })));
183
- const idOf = (s) => key([s.scalars, Object.entries(s.maps).map(([n, cs]) => [n, [...cs].filter(([, x]) => x).sort((a, c) => a[0] - c[0])])]);
184
- const seen = new Map([[idOf(start), start]]), queue = [start];
185
- const reached = (next, from, r) => { const id = idOf(next), had = seen.get(id); if (had)
186
- return had; seen.set(id, next); pathTo.set(next, [from, r]); return next; };
187
- while (queue.length && seen.size < cap && work > 0) {
185
+ // (a state once: by a hash of its scalars and nonzero cells, then a cell-by-cell comparison within the hash's bucket;
186
+ // the same classes as a sorted text of the state, without a sort or a text per step)
187
+ const scalarNames = Object.keys(start.scalars), mapNames = Object.keys(start.maps);
188
+ const hashOf = (s) => {
189
+ let h = 0x811C9DC5 | 0;
190
+ for (const n of scalarNames)
191
+ h = Math.imul(h ^ (s.scalars[n] | 0), 0x01000193);
192
+ for (const n of mapNames) {
193
+ let acc = 0;
194
+ for (const [k2, x2] of s.maps[n] ?? [])
195
+ if (x2)
196
+ acc = (acc + Math.imul((k2 * 0x85EBCA6B) ^ Math.imul(x2, 0xC2B2AE35), 0x27D4EB2F)) | 0;
197
+ h = Math.imul(h ^ acc, 0x01000193);
198
+ }
199
+ return h;
200
+ };
201
+ const sameCells = (a, b) => {
202
+ for (const [k2, x2] of a ?? [])
203
+ if (x2 !== (b?.get(k2) ?? 0))
204
+ return false;
205
+ for (const [k2, x2] of b ?? [])
206
+ if (x2 !== (a?.get(k2) ?? 0))
207
+ return false;
208
+ return true;
209
+ };
210
+ const equal = (a, b) => scalarNames.every(n => a.scalars[n] === b.scalars[n]) && mapNames.every(n => sameCells(a.maps[n], b.maps[n]));
211
+ const seen = new Map([[hashOf(start), [start]]]), all = [start], queue = [start];
212
+ const reached = (next, from, r) => {
213
+ const h = hashOf(next), bucket = seen.get(h);
214
+ if (bucket) {
215
+ for (const had of bucket)
216
+ if (equal(had, next))
217
+ return had;
218
+ bucket.push(next);
219
+ }
220
+ else
221
+ seen.set(h, [next]);
222
+ all.push(next);
223
+ pathTo.set(next, [from, r]);
224
+ return next;
225
+ };
226
+ while (queue.length && all.length < cap && work > 0) {
188
227
  const st = queue.shift();
189
228
  for (const r of reqs) {
229
+ checkWall('sample BFS');
190
230
  if (--work < 0)
191
231
  break;
192
232
  let next;
@@ -196,23 +236,24 @@ export function small(m, p, b, cap = 3000, work = 300_000, walks = 0) {
196
236
  catch {
197
237
  continue;
198
238
  }
199
- const n0 = seen.size;
200
- if (reached(next, st, r) && seen.size > n0)
239
+ const n0 = all.length;
240
+ if (reached(next, st, r) && all.length > n0)
201
241
  queue.push(next);
202
242
  }
203
243
  }
204
244
  if (!queue.length)
205
- return [...seen.values()];
245
+ return all;
206
246
  const cell = (s, n, x) => s.maps[n]?.get(x) ?? s.defaults?.[n] ?? 0;
207
247
  const kindOf = (a, c) => [...Object.keys(c.scalars).filter(n => a.scalars[n] !== c.scalars[n]),
208
248
  ...Object.keys(c.maps).filter(n => a.defaults?.[n] !== c.defaults?.[n] || [...a.maps[n]?.keys() ?? [], ...c.maps[n].keys()].some(x => cell(a, n, x) !== cell(c, n, x)))].join();
209
249
  let seed = 7;
210
250
  const rnd = (n) => { seed = (seed * 48271) % 2147483647; return seed % n; };
211
- for (let t = 0; walks > 0 && seen.size < 2 * cap; t++) {
212
- let st = t % 2 ? start : [...seen.values()][rnd(seen.size)];
251
+ for (let t = 0; walks > 0 && all.length < 2 * cap; t++) {
252
+ let st = t % 2 ? start : all[rnd(all.length)];
213
253
  for (let d = 0; d < 40 && walks > 0; d++) {
214
254
  const by = new Map();
215
255
  for (let i = 0; i < 48; i++, walks--) {
256
+ checkWall('sample walks');
216
257
  const r = reqs[rnd(reqs.length)];
217
258
  let next;
218
259
  try {
@@ -231,7 +272,7 @@ export function small(m, p, b, cap = 3000, work = 300_000, walks = 0) {
231
272
  st = reached(next, st, r);
232
273
  }
233
274
  }
234
- return [...seen.values()];
275
+ return all;
235
276
  }
236
277
  // A ghost for a law about no key with one value ∃x. P over maps (PCorrect's "some process not done, or its y is 1"): x a
237
278
  // state variable that starts at 0 or a param (or one less) and after each step keeps its value while P still holds there
@@ -260,13 +301,29 @@ export function ghostOf(m, law) {
260
301
  // the walks past it in a third as many; an instance whose params the machine refuses has no states. With no params,
261
302
  // 2 and 3 denote the same instance, so sample it only once. Read once a machine.
262
303
  const smalls = new WeakMap();
263
- export function smallOf(m) {
304
+ // Adding fresh, unreferenced count definitions cannot change any transition.
305
+ // Reuse the engine's original samples instead of enumerating that same graph
306
+ // with every speculative count attached to every request. The structural check
307
+ // rejects changed transitions, replaced counts, and shadowed map reads.
308
+ export function smallOf(m, source) {
309
+ checkWall('sample cache');
264
310
  let out = smalls.get(m);
311
+ if (!out && source && source !== m) {
312
+ const fields = new Set([...Object.keys(m), ...Object.keys(source)]);
313
+ const added = new Set(Object.keys(m.counts ?? {}).filter(k => !(k in (source.counts ?? {}))));
314
+ let safe = [...fields].every(k => k === 'counts' || m[k] === source[k]) && Object.entries(source.counts ?? {}).every(([k, d]) => m.counts?.[k] === d) && [...added].every(k => !(k in (source.maps ?? {})) && !(k in (source.fns ?? {})) && !source.inputMaps?.includes(k));
315
+ walk(source, o => { if (o.op === 'get' && added.has(o.map))
316
+ safe = false; });
317
+ if (safe)
318
+ smalls.set(m, (out = smallOf(source)));
319
+ }
265
320
  if (!out)
266
321
  smalls.set(m, (out = (m.params.length ? [2, 3] : [2]).map(x => { const p = Object.fromEntries(m.params.map(q => [q, x])); try {
267
322
  return { p, sts: small(m, p, 3, 3000, 300_000, 100_000) };
268
323
  }
269
- catch {
324
+ catch (e) {
325
+ if (e instanceof WallExpired)
326
+ throw e;
270
327
  return { p, sts: [] };
271
328
  } })));
272
329
  return out;
@@ -303,10 +360,13 @@ export function trueSmall(m, laws, ghosted) {
303
360
  const views = new WeakMap();
304
361
  const sampleTests = new WeakMap();
305
362
  export function holdsAt(m, law, p, st, b) {
306
- let view = views.get(st);
363
+ let machineViews = views.get(m);
364
+ if (!machineViews)
365
+ views.set(m, (machineViews = new WeakMap()));
366
+ let view = machineViews.get(st);
307
367
  if (!view) {
308
368
  const empty = Object.fromEntries((m.inputMaps ?? []).map(c => [c, new Map()]));
309
- views.set(st, (view = carriedView(m, st, empty, undefined, p)));
369
+ machineViews.set(st, (view = carriedView(m, st, empty, undefined, p)));
310
370
  }
311
371
  let tests = sampleTests.get(m);
312
372
  if (!tests)
@@ -322,7 +382,12 @@ export function holdsAt(m, law, p, st, b) {
322
382
  if (!fixed.has(name))
323
383
  Object.defineProperty(env, name, { value: env[name], writable: true, enumerable: true, configurable: true });
324
384
  const values = keys.length ? Array.from({ length: b }, (_, x) => x) : [];
385
+ // Poll at entry and every 256 visited tuple prefixes, rather than paying for
386
+ // a wall-clock read at every binding. Each new state/law starts with a poll.
387
+ let visited = 0;
325
388
  const go = (depth) => {
389
+ if ((visited++ & 255) === 0)
390
+ checkWall('sample law bindings');
326
391
  if (depth === keys.length)
327
392
  return test(env, view);
328
393
  const name = keys[depth], was = env[name];
@@ -5,6 +5,7 @@ import { type Model, type Var } from './extract-read.js';
5
5
  import * as I from './extract-ir.js';
6
6
  import type { B, N } from './extract-ir.js';
7
7
  import type { Sorts } from './extract-print.js';
8
+ import { type NativeInputs } from './native-domain.js';
8
9
  type Raw = number | boolean | string;
9
10
  export type Arm = {
10
11
  label: string;
@@ -57,8 +58,9 @@ export type Sandbox = {
57
58
  };
58
59
  setNow: (n: number) => void;
59
60
  get: (name: string) => unknown;
61
+ bindings: (method: string) => Record<string, unknown> | undefined;
60
62
  };
61
- export declare function sandbox(code: string, file: string, expose: string[], modules?: Record<string, unknown>, init?: string, files?: Record<string, string>, extra?: [number, string][]): Sandbox & {
63
+ export declare function sandbox(code: string, file: string, expose: string[], modules?: Record<string, unknown>, init?: string, files?: Record<string, string>, extra?: [number, string][], nativeMethods?: string[]): Sandbox & {
62
64
  arms: Arm[];
63
65
  };
64
66
  type Cells = Record<string, Record<string, Raw>>;
@@ -89,6 +91,7 @@ export type CheckOptions = {
89
91
  probeMs?: number;
90
92
  modules?: Record<string, unknown>;
91
93
  files?: Record<string, string>;
94
+ lawCrossCheck?: boolean;
92
95
  };
93
96
  type Ev = Model['events'][number];
94
97
  export type CodeSide = {
@@ -120,6 +123,9 @@ export type CodeSide = {
120
123
  setNow: (n: number) => void;
121
124
  init?: (snap: Snap, params: Record<string, Raw>) => string | undefined;
122
125
  coverage: () => Coverage;
126
+ nativeState?: (self: unknown, snap: Snap, params: Record<string, Raw>) => unknown;
127
+ nativeBindings?: (event: Ev) => Record<string, unknown> | undefined;
128
+ nativeInputs?: NativeInputs;
123
129
  input?: (v: Var, x: Raw, rand: Rand) => Raw;
124
130
  drawSnap?: (rand: Rand) => Snap;
125
131
  normalize?: (s: Snap) => Snap;
@@ -20,8 +20,10 @@ const vmOf = () => { const m = proc?.getBuiltinModule?.('node:vm'); if (!m)
20
20
  import { Int, Term, bool, int, intern, interned, nat, no, oneOf, str, proveSteps } from "./dsl.js";
21
21
  import { seeded, walk } from "./machine.js";
22
22
  import { allowed } from "./watch.js";
23
- import { normalize, resolveIn, scriptKind } from "./extract-read.js";
23
+ import { normalize, resolveIn, sameLazyRoot, scriptKind } from "./extract-read.js";
24
24
  import * as I from "./extract-ir.js";
25
+ import { nativeSnapshot, rememberNative } from "./source-check.js";
26
+ import { nativeCaptureEdits, nativeInputs } from "./native-domain.js";
25
27
  // The check's own failure, not the code's: a request past its time, the harness's transport (anvil's JSON-RPC) failing,
26
28
  // the harness gone. Never a difference and never a pass: the whole check runs once more, from a fresh harness, and a
27
29
  // second failure is the check's outcome (Evidence.harness).
@@ -89,9 +91,12 @@ export function instrument(code, file, tail = '', extra = []) {
89
91
  const js = ts.transpileModule(out, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, esModuleInterop: true, jsx: ts.JsxEmit.React }, fileName: file.replace(/\.js$/, '.ts').replace(/\.jsx$/, '.tsx') }).outputText;
90
92
  return { js, arms };
91
93
  }
92
- export function sandbox(code, file, expose, modules = {}, init, files = {}, extra = []) {
94
+ export function sandbox(code, file, expose, modules = {}, init, files = {}, extra = [], nativeMethods = []) {
93
95
  const vm = vmOf();
94
- const { js, arms } = instrument(code, file, init ? `\n;(globalThis as any).__gdpInit = () => (${init});\n` : '', extra);
96
+ // A final arrow can end exactly where a factory appends fields. Its capture
97
+ // must close first; instrument preserves the order of equal-position edits.
98
+ const { js, arms } = instrument(code, file, init ? `\n;(globalThis as any).__gdpInit = () => (${init});\n` : '', [...nativeCaptureEdits(code, file, nativeMethods), ...extra]);
99
+ const captured = new Map(), captureErrors = new Map();
95
100
  const counts = arms.map(() => 0);
96
101
  let now = 0;
97
102
  const stub = (name) => new Proxy({}, {
@@ -102,6 +107,16 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}, extr
102
107
  const module = { exports: {} };
103
108
  const ctx = vm.createContext({
104
109
  __cov: (i) => { counts[i]++; }, __now: () => now, module, exports: module.exports,
110
+ __gdp_native_capture: (name, value) => {
111
+ if (captured.has(name) || captureErrors.has(name))
112
+ return;
113
+ try {
114
+ captured.set(name, nativeSnapshot(value));
115
+ }
116
+ catch (e) {
117
+ captureErrors.set(name, String(e));
118
+ }
119
+ },
105
120
  // A relative import among the files given: loaded in this VM (not counted: the branches are the entry's). A module
106
121
  // the step doesn't name (React, for the component beside a reducer): a stub that throws when read, so a step that
107
122
  // reads it fails the check rather than running without it.
@@ -118,7 +133,10 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}, extr
118
133
  return loaded.get(at);
119
134
  const m = { exports: {} };
120
135
  loaded.set(at, m.exports);
121
- const js = ts.transpileModule(abs[at], { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, esModuleInterop: true, jsx: ts.JsxEmit.React }, fileName: at.replace(/\.js$/, '.ts').replace(/\.jsx$/, '.tsx') }).outputText;
136
+ let input = abs[at];
137
+ for (const [pos, text] of nativeCaptureEdits(input, at, nativeMethods).sort((a, b) => b[0] - a[0]))
138
+ input = input.slice(0, pos) + text + input.slice(pos);
139
+ const js = ts.transpileModule(input, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, esModuleInterop: true, jsx: ts.JsxEmit.React }, fileName: at.replace(/\.js$/, '.ts').replace(/\.jsx$/, '.tsx') }).outputText;
122
140
  // A file that doesn't load here (it reads import.meta, a browser's globals): a stub that throws when read, so a step
123
141
  // that reads it fails the check rather than running without it.
124
142
  try {
@@ -139,6 +157,11 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}, extr
139
157
  return 'default: module.exports.default'; const [h, ...rest] = n.split('.'); return `${JSON.stringify(n)}: (typeof ${h} !== 'undefined' ? ${h} : module.exports.${h})${rest.map(x => `.${x}`).join('')}`; }).join(', ')}};`, ctx, { timeout: 2000, filename: file });
140
158
  const script = new vm.Script('globalThis.__r = (() => { try { return {ok: true, value: __gdp[__f].apply(__self, __args)} } catch (e) { return {ok: false, error: String(e && e.message || e)} } })()');
141
159
  const call = (f, self, args) => {
160
+ // Reading/restoring a factory's closure is harness work, not a new request.
161
+ if (f !== '$get' && f !== '$at') {
162
+ captured.clear();
163
+ captureErrors.clear();
164
+ }
142
165
  Object.assign(ctx, { __f: f, __self: self, __args: args });
143
166
  try {
144
167
  script.runInContext(ctx, { timeout: 1000 });
@@ -150,7 +173,9 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}, extr
150
173
  }
151
174
  return ctx.__r;
152
175
  };
153
- return { ctx, counts, arms, call, setNow: n => { now = n; }, get: name => vm.runInContext(`__gdp[${JSON.stringify(name)}]`, ctx) };
176
+ return { ctx, counts, arms, call, setNow: n => { now = n; }, get: name => vm.runInContext(`__gdp[${JSON.stringify(name)}]`, ctx),
177
+ bindings: method => { if (captureErrors.has(method))
178
+ throw new Error(captureErrors.get(method)); return captured.get(method); } };
154
179
  }
155
180
  const isMap = (x) => Object.prototype.toString.call(x) === '[object Map]';
156
181
  export class Outside extends Error {
@@ -409,7 +434,7 @@ function checkOnce(code, file, m, r, sorts, opts) {
409
434
  // declared twice: no request runs, and the check says why)
410
435
  let box;
411
436
  try {
412
- box = sandbox(code, file, fns, mods, m.initSource, opts.files, m.factory ? [[m.factory.at, m.factory.text], ...(m.factory.extra ?? [])] : []);
437
+ box = sandbox(code, file, fns, mods, m.initSource, opts.files, m.factory ? [[m.factory.at, m.factory.text], ...(m.factory.extra ?? [])] : [], m.events.map(e => e.call));
413
438
  }
414
439
  catch (e) {
415
440
  return { runs: 0, requests: 0, fromStates: 0, probes: { conditions: 0, witnesses: 0, steps: 0 }, refusedBoth: 0, outside: 0, edge: 0, compiledAgreed: 0, coverage: { arms: 0, hit: 0, missed: [] }, ms: 0,
@@ -434,6 +459,9 @@ function checkOnce(code, file, m, r, sorts, opts) {
434
459
  const ctorValue = (n, params) => (n === '$fn' ? fnArg() : n.startsWith('$map:') ? vmOf().runInContext(n === '$map:Map' ? 'new Map()' : '({})', box.ctx) : params[n]);
435
460
  const ctorValues = (params) => (m.ctorArgs ?? []).filter(n => !m.params.find(v => v.name === n)?.note?.startsWith('Date.now()')).map(n => ctorValue(n, params));
436
461
  const side = {
462
+ nativeState: (self, snap, params) => standalone ? {} : isClass ? stateOf(self) : valueOf(snap, m.layout, m, evalAt(params), box.ctx),
463
+ nativeBindings: e => box.bindings(e.call),
464
+ ...(standalone ? { nativeInputs: nativeInputs(code, file, m.entry, opts.files) } : {}),
437
465
  make: params => {
438
466
  const now0 = m.params.find(v => v.note?.startsWith('Date.now()'));
439
467
  if (now0)
@@ -462,7 +490,7 @@ function checkOnce(code, file, m, r, sorts, opts) {
462
490
  answers = inputs;
463
491
  const dateIn = (n) => { const x = m.inputs.find(v => v.name === n); return x?.sort.k === 'num' && x.sort.date ? vmOf().runInContext(`new Date(${Number(inputs[n])})`, box.ctx) : inputs[n]; };
464
492
  const build = (a) => (a.k === 'input' ? dateIn(a.name) : a.k === 'maybe-bool' ? (inputs[a.missing] ? undefined : inputs[a.name]) : a.k === 'lit' ? a.value : a.k === 'rec' ? Object.fromEntries(a.fields.map(([f, x]) => [f, build(x)])) : a.k === 'lazy'
465
- ? Object.fromEntries([...m.inputs].filter(v => m.lazy?.get(v.name)?.prefix === a.prefix).map(v => [m.lazy.get(v.name).field, inputs[v.name]]))
493
+ ? Object.fromEntries([...m.inputs].filter(v => sameLazyRoot(m.lazy?.get(v.name), a)).map(v => [m.lazy.get(v.name).field, inputs[v.name]]))
466
494
  : undefined);
467
495
  return e.args.map(build);
468
496
  },
@@ -496,11 +524,38 @@ export function drive(m, r, sorts, code, opts = {}) {
496
524
  const interp = r.interpreter(), gen = r.compiled(), machine = r.machine;
497
525
  const ev = { runs: 0, requests: 0, fromStates: 0, probes: { conditions: 0, witnesses: 0, steps: 0 }, refusedBoth: 0, outside: 0, edge: 0, compiledAgreed: 0, coverage: { arms: 0, hit: 0, missed: [] }, ms: 0 };
498
526
  const consts = constantsOf(m), strs = stringsOf(m);
527
+ const disabled = opts.lawCrossCheck === false || (opts.runs === 0 && opts.states === 0 && opts.probes === false);
528
+ const finite = code.nativeInputs?.domains;
529
+ const exhaustive = finite !== undefined;
530
+ const journal = { enabled: !disabled, complete: false, scope: exhaustive ? 'exhaustive' : 'sampled', observations: [],
531
+ ...(disabled ? { reason: 'source replay or native-law cross-check was disabled' } : {}) };
532
+ if (code.nativeInputs?.reason)
533
+ journal.reason = code.nativeInputs.reason;
534
+ rememberNative(ev, journal);
535
+ const nativeContext = vmOf().createContext({});
536
+ const nativeState = (side, params) => nativeSnapshot(code.nativeState ? code.nativeState(side.self, side.snap, params) : valueOf(side.snap, m.layout, m, t => evalTerm(t, params), nativeContext));
537
+ const capture = (read) => {
538
+ if (!journal.enabled || journal.reason)
539
+ return undefined;
540
+ try {
541
+ return read();
542
+ }
543
+ catch (e) {
544
+ journal.reason = `native observation unavailable: ${e instanceof Error ? e.message : String(e)}`;
545
+ return undefined;
546
+ }
547
+ };
548
+ const recordInitial = (side, params) => {
549
+ const state = capture(() => nativeState(side, params));
550
+ if (journal.enabled && !journal.reason)
551
+ journal.observations.push({ where: 'initial native state', before: state, after: state, params: { ...params }, inputs: {}, bindings: {}, args: [], result: undefined, failed: false });
552
+ };
499
553
  const paramKinds = m.params.map(v => [v, kindOfVar(v, sorts)]), inputKinds = m.inputs.map(v => [v, kindOfVar(v, sorts)]);
500
554
  const fail = (what) => { ev.mismatch = what; return finish(); };
501
555
  const finish = () => {
502
556
  ev.coverage = code.coverage();
503
557
  ev.ms = Math.round(performance.now() - t0);
558
+ journal.complete = journal.enabled && !journal.reason && journal.observations.length > 0;
504
559
  return ev;
505
560
  };
506
561
  const draws = (st, params) => [...consts, ...Object.values(st.leaves).filter((x) => typeof x === 'number'), ...Object.values(params).filter((x) => typeof x === 'number')];
@@ -541,7 +596,7 @@ export function drive(m, r, sorts, code, opts = {}) {
541
596
  a.fields.forEach(([, x]) => walk(x));
542
597
  else if (a.k === 'lazy')
543
598
  for (const v of m.inputs)
544
- if (m.lazy?.get(v.name)?.prefix === a.prefix)
599
+ if (sameLazyRoot(m.lazy?.get(v.name), a))
545
600
  used.add(v.name); };
546
601
  e.args.forEach(walk);
547
602
  for (const v of m.inputs)
@@ -552,7 +607,7 @@ export function drive(m, r, sorts, code, opts = {}) {
552
607
  };
553
608
  // Steps the code and the rule from one state; undefined when they agree (the next state on both sides is returned
554
609
  // through `next`), else the difference.
555
- const step = (params, ps, side, st, inputs, e, next, where) => {
610
+ const step = (params, ps, side, st, inputs, e, next, where, reachable) => {
556
611
  // A source type's finite numeric domain is part of the standalone claim, not
557
612
  // behavior the source is alleged to reject. Never execute an out-of-domain probe.
558
613
  if (m.standalone && Object.entries(m.standaloneDomains ?? {}).some(([name, values]) => !values.includes(inputs[name]))) {
@@ -561,6 +616,8 @@ export function drive(m, r, sorts, code, opts = {}) {
561
616
  return undefined;
562
617
  }
563
618
  const args = code.args(inputs, e), raw = ruleInputs(inputs, e);
619
+ const before = reachable ? capture(() => nativeState(side, params)) : undefined;
620
+ const nativeArgs = reachable ? capture(() => nativeSnapshot(args)) : undefined;
564
621
  if (m.folds)
565
622
  carry(m, raw, inputs, side.snap, params, r.decode(st));
566
623
  const nowVar = m.inputs.find(v => v.note?.startsWith('Date.now()'));
@@ -703,7 +760,25 @@ export function drive(m, r, sorts, code, opts = {}) {
703
760
  return bad(`the rule's ${rk.name} is ${JSON.stringify(d[rk.name])}`);
704
761
  }
705
762
  }
706
- next.side = { snap: res.snap, ...(res.self ? { self: res.self } : {}) };
763
+ const afterSide = { snap: res.snap, ...(res.self ? { self: res.self } : {}) };
764
+ if (reachable && journal.enabled && !journal.reason) {
765
+ const after = capture(() => nativeState(afterSide, params)), result = capture(() => nativeSnapshot(res.out));
766
+ const bindings = capture(() => code.nativeBindings?.(e));
767
+ if (code.nativeBindings && !bindings)
768
+ journal.reason ??= `native parameter capture unavailable for ${e.call}`;
769
+ const fallback = Object.create(null);
770
+ e.names?.forEach((n, i) => {
771
+ const value = nativeArgs?.[i];
772
+ if (n === '__gdp_destructured' && value && typeof value === 'object')
773
+ Object.assign(fallback, value);
774
+ else
775
+ fallback[n] = value;
776
+ });
777
+ const rk = m.results?.[e.call];
778
+ journal.observations.push({ where, method: e.call, before, after, params: { ...params }, inputs: { ...inputs }, bindings: bindings ?? fallback,
779
+ args: nativeArgs ?? [], result, failed: false, legacyResult: !standalone && rk?.k === 'rec' && rk.fields.some(([field]) => field === 'value') });
780
+ }
781
+ next.side = afterSide;
707
782
  next.st = rule.st;
708
783
  return undefined;
709
784
  };
@@ -754,7 +829,9 @@ export function drive(m, r, sorts, code, opts = {}) {
754
829
  const diff = sameSnap(snap, ruleSnap(r, m, st, sorts));
755
830
  if (diff)
756
831
  return { problem: `new ${m.entry}(${JSON.stringify(params)}): ${diff}` };
757
- return { side: { snap, self: made.value }, st, ps: ps };
832
+ const side = { snap, self: made.value };
833
+ recordInitial(side, params);
834
+ return { side, st, ps: ps };
758
835
  }
759
836
  catch (x) {
760
837
  if (x instanceof HarnessFailure)
@@ -777,6 +854,7 @@ export function drive(m, r, sorts, code, opts = {}) {
777
854
  const problem = code.init?.(snap, params);
778
855
  if (problem)
779
856
  return { problem };
857
+ recordInitial({ snap }, params);
780
858
  return { side: { snap }, st, ps: ps ?? {} };
781
859
  };
782
860
  const runs = opts.runs ?? 200, depth = opts.depth ?? 12;
@@ -790,7 +868,7 @@ export function drive(m, r, sorts, code, opts = {}) {
790
868
  let side = s0.side, st = s0.st;
791
869
  for (let d = 0; d < depth; d++) {
792
870
  const { e, inputs } = drawRequest(side.snap, params), next = {};
793
- const diff = step(params, s0.ps, side, st, inputs, e, next, `run ${run + 1}, request ${d + 1}`);
871
+ const diff = step(params, s0.ps, side, st, inputs, e, next, `run ${run + 1}, request ${d + 1}`, true);
794
872
  ev.requests++;
795
873
  if (diff)
796
874
  return fail(diff);
@@ -871,7 +949,8 @@ export function drive(m, r, sorts, code, opts = {}) {
871
949
  if (isClass && self === undefined)
872
950
  return undefined;
873
951
  const side = { snap, ...(isClass ? { self: self } : {}) };
874
- return step(params, ps, side, st, inputs, e, {}, where);
952
+ // Drawn/prover states test translation conformance, not reachable source laws.
953
+ return step(params, ps, side, st, inputs, e, {}, where, false);
875
954
  };
876
955
  for (let i = 0; i < (opts.states ?? 400); i++) {
877
956
  const params = drawParams(), snap = drawSnap(params), { e, inputs } = drawRequest(snap, params);
@@ -929,6 +1008,44 @@ export function drive(m, r, sorts, code, opts = {}) {
929
1008
  return fail(diff);
930
1009
  }
931
1010
  }
1011
+ // Finite standalone inputs are not replaced by random sampling, even when a
1012
+ // particular request was already replayed above. The same native step supplies
1013
+ // both rule conformance and the independent source-law observation.
1014
+ if (exhaustive && journal.enabled && !journal.reason) {
1015
+ const params = {}, first = start(params);
1016
+ if (first.problem)
1017
+ return fail(`exhaustive native start: ${first.problem}`);
1018
+ if (!first.side || !first.st || !first.ps)
1019
+ journal.reason = 'finite native entry could not start';
1020
+ else {
1021
+ let ordinal = 0;
1022
+ const event = m.events[0];
1023
+ const visit = (at, args) => {
1024
+ if (journal.reason)
1025
+ return;
1026
+ if (at === finite.length) {
1027
+ const returned = code.call(undefined, event, args);
1028
+ if (!returned.ok) {
1029
+ journal.reason = `native finite input ${++ordinal} throws: ${returned.error}`;
1030
+ return;
1031
+ }
1032
+ const bindings = capture(() => code.nativeBindings?.(event));
1033
+ if (!bindings) {
1034
+ journal.reason ??= 'independent native parameter capture unavailable';
1035
+ return;
1036
+ }
1037
+ const result = capture(() => nativeSnapshot(returned.value)), savedArgs = capture(() => nativeSnapshot(args));
1038
+ if (!journal.reason)
1039
+ journal.observations.push({ where: `exhaustive native input ${++ordinal}`, method: event.call,
1040
+ before: {}, after: {}, params: {}, inputs: {}, bindings, args: savedArgs, result, failed: false });
1041
+ return;
1042
+ }
1043
+ for (const value of finite[at])
1044
+ visit(at + 1, [...args, value]);
1045
+ };
1046
+ visit(0, []);
1047
+ }
1048
+ }
932
1049
  return finish();
933
1050
  }
934
1051
  const mapReplacer = (_, v) => (isMap(v) ? { $map: [...v.entries()] } : v);
@@ -90,6 +90,23 @@ export type Term = {
90
90
  s: 'str';
91
91
  e: K;
92
92
  };
93
+ export type LazyRoot = readonly [scope: string, argument: number];
94
+ export type LazyField = {
95
+ prefix: string;
96
+ root?: LazyRoot;
97
+ field: string;
98
+ };
99
+ export declare const lazyKey: (record: {
100
+ prefix: string;
101
+ root?: LazyRoot;
102
+ }, field: string) => string;
103
+ export declare const sameLazyRoot: (a: {
104
+ prefix: string;
105
+ root?: LazyRoot;
106
+ } | undefined, b: {
107
+ prefix: string;
108
+ root?: LazyRoot;
109
+ }) => boolean;
93
110
  export type Arg = {
94
111
  k: 'input';
95
112
  name: string;
@@ -108,6 +125,7 @@ export type Arg = {
108
125
  } | {
109
126
  k: 'lazy';
110
127
  prefix: string;
128
+ root?: LazyRoot;
111
129
  };
112
130
  export type Event = {
113
131
  select: Record<string, string>;
@@ -175,10 +193,7 @@ export type Model = {
175
193
  notes: string[];
176
194
  hints: WeakMap<object, string>;
177
195
  ctorArgs?: string[];
178
- lazy?: Map<string, {
179
- prefix: string;
180
- field: string;
181
- }>;
196
+ lazy?: Map<string, LazyField>;
182
197
  initSource?: string;
183
198
  spans?: [number, number][];
184
199
  factory?: {
@@ -286,6 +301,7 @@ type Rec = {
286
301
  origin: 'fresh' | 'input' | 'this' | 'shared';
287
302
  lazy?: {
288
303
  prefix: string;
304
+ root?: LazyRoot;
289
305
  };
290
306
  };
291
307
  type MapObj = {
@@ -379,10 +395,8 @@ export type Setup = {
379
395
  nowRole: 'input' | 'param';
380
396
  hints: WeakMap<object, string>;
381
397
  notes: Set<string>;
382
- lazy: Map<string, {
383
- prefix: string;
384
- field: string;
385
- }>;
398
+ lazy: Map<string, LazyField>;
399
+ lazySelections?: Set<string>;
386
400
  ctor?: boolean;
387
401
  ours: (sf: ts.SourceFile) => boolean;
388
402
  spans?: [number, number][];
@@ -26,6 +26,13 @@ export class Retype extends Error {
26
26
  this.sort = sort;
27
27
  }
28
28
  }
29
+ export const lazyKey = (record, field) => JSON.stringify([record.root ?? [record.prefix, 0], [field]]);
30
+ export const sameLazyRoot = (a, b) => {
31
+ if (!a)
32
+ return false;
33
+ const x = a.root ?? [a.prefix, 0], y = b.root ?? [b.prefix, 0];
34
+ return x[0] === y[0] && x[1] === y[1];
35
+ };
29
36
  export const unparen = (x) => (ts.isParenthesizedExpression(x) ? unparen(x.expression) : x);
30
37
  // An expression without its parentheses, casts and `!` (what it is, as the front ends read it).
31
38
  export const bare = (x) => (ts.isParenthesizedExpression(x) || ts.isAsExpression(x) || ts.isSatisfiesExpression(x) || ts.isNonNullExpression(x) ? bare(x.expression) : x);
@@ -392,8 +399,11 @@ export class Exec {
392
399
  return { has: { op: 'cell', map: m.name, key, field: 'has' }, vals: new Map(m.fields.map(f => [f.name, Exec.cellOf(m, key, f)])) };
393
400
  }
394
401
  asChoice(v, values, at) {
395
- if (v.t === 'choice')
402
+ if (v.t === 'choice') {
403
+ if (v.values.length !== values.length || v.values.some((value, i) => value !== values[i]))
404
+ return refuse(at, 'a join or assignment between different ordered choice domains');
396
405
  return v.e;
406
+ }
397
407
  if (v.t === 'str' && v.e.op === 'slit') {
398
408
  if (!values.includes(v.e.value))
399
409
  return refuse(at, `'${v.e.value}' is not one of ${values.map(x => `'${x}'`).join(', ')}`);
@@ -528,7 +538,7 @@ export class Exec {
528
538
  // where it is there.
529
539
  narrow(e, pt, pe) {
530
540
  const strip = (x) => (ts.isParenthesizedExpression(x) ? strip(x.expression) : x);
531
- let x = strip(e), present = true, absenceTest = false;
541
+ let x = strip(e), present = true, absenceTest = false, comparedNull = false, loose = false;
532
542
  if (ts.isPrefixUnaryExpression(x) && x.operator === ts.SyntaxKind.ExclamationToken) {
533
543
  x = strip(x.operand);
534
544
  present = false;
@@ -536,6 +546,8 @@ export class Exec {
536
546
  else if (ts.isBinaryExpression(x) && (x.right.kind === ts.SyntaxKind.UndefinedKeyword || (ts.isIdentifier(x.right) && x.right.text === 'undefined') || x.right.kind === ts.SyntaxKind.NullKeyword)) {
537
547
  const op = x.operatorToken.kind;
538
548
  absenceTest = true;
549
+ comparedNull = x.right.kind === ts.SyntaxKind.NullKeyword;
550
+ loose = op === ts.SyntaxKind.EqualsEqualsToken || op === ts.SyntaxKind.ExclamationEqualsToken;
539
551
  if (op === ts.SyntaxKind.EqualsEqualsEqualsToken || op === ts.SyntaxKind.EqualsEqualsToken)
540
552
  present = false;
541
553
  else if (op !== ts.SyntaxKind.ExclamationEqualsEqualsToken && op !== ts.SyntaxKind.ExclamationEqualsToken)
@@ -547,10 +559,14 @@ export class Exec {
547
559
  const v = pt.locals.get(x.text);
548
560
  if (v?.t !== 'opt')
549
561
  return [pt, pe];
550
- const set = (p, there) => ({ ...p, locals: new Map(p.locals).set(x.text, there ? v.v : { t: 'undef' }) });
562
+ // A strict comparison to the other absence kind is constant, not a presence test.
563
+ if (absenceTest && !loose && !!v.null !== comparedNull)
564
+ return [pt, pe];
565
+ const absent = { t: 'undef', ...(v.null ? { null: true } : {}) };
566
+ const set = (p, there) => ({ ...p, locals: new Map(p.locals).set(x.text, there ? v.v : absent) });
551
567
  // A falsy optional scalar can be present (false or 0), not just absent.
552
568
  // Preserve the opt value on that arm; only an explicit absence comparison narrows both arms.
553
- if (this.standalone && !absenceTest)
569
+ if (!absenceTest)
554
570
  return present ? [set(pt, true), pe] : [pt, set(pe, true)];
555
571
  return present ? [set(pt, true), set(pe, false)] : [set(pt, false), set(pe, true)];
556
572
  }
@@ -626,6 +642,10 @@ export class Exec {
626
642
  return I.cmp('=', a.e, b.e);
627
643
  if (a.t === 'bool' && b.t === 'bool')
628
644
  return I.or(I.and(a.e, b.e), I.and(I.not(a.e), I.not(b.e)));
645
+ // Choices are encoded by position. Standalone arguments may have different
646
+ // domains or orders, so comparing their indices would equate different strings.
647
+ if (this.standalone && a.t === 'choice' && b.t === 'choice')
648
+ return I.or(...a.values.filter(x => b.values.includes(x)).map(x => I.and(I.is(a.e, x), I.is(b.e, x))));
629
649
  if (a.t === 'choice' && (b.t === 'choice' || b.t === 'str'))
630
650
  return I.leq(a.e, b.t === 'str' && b.e.op === 'slit' && !a.values.includes(b.e.value) ? I.llit(b.e.value, [...a.values, b.e.value]) : this.asChoice(b, a.values, at));
631
651
  if (b.t === 'choice' && a.t === 'str')
@@ -993,8 +1013,6 @@ export class Exec {
993
1013
  return { t: 'num', e: I.nite(c, x.e, y.e) };
994
1014
  if (x.t === 'bool' && y.t === 'bool')
995
1015
  return { t: 'bool', e: I.bite(c, x.e, y.e) };
996
- if (x.t === 'choice' && y.t === 'choice')
997
- return { t: 'choice', e: I.lite(c, x.e, y.e), values: x.values };
998
1016
  if ((x.t === 'choice' || x.t === 'str') && (y.t === 'choice' || y.t === 'str')) {
999
1017
  if (x.t === 'str' && y.t === 'str')
1000
1018
  return { t: 'str', e: I.kite(c, x.e, y.e) };
@@ -1080,11 +1098,11 @@ export class Exec {
1080
1098
  })();
1081
1099
  if (opaque)
1082
1100
  return [{ t: 'opaque', what: opaque }, p];
1083
- const path = `${o.lazy.prefix}${f}`, sort = this.s.lazySorts.get(path) ?? typed ?? { k: 'num' };
1084
- // The same field read again (in another guard or action, say) is the same input.
1085
- const seen = [...this.s.lazy].find(([, l]) => l.prefix === o.lazy.prefix && l.field === f)?.[0];
1086
- const nvar = seen ? this.s.vars.get(seen) : this.newVar(path, sort, 'input'), nv = Exec.valueOf(nvar);
1087
- this.s.lazy.set(nvar.name, { prefix: o.lazy.prefix, field: f });
1101
+ const key = lazyKey(o.lazy, f), sort = this.s.lazySorts.get(key) ?? typed ?? { k: 'num' };
1102
+ // Repeated reads share one input, independently of its readable scalar name.
1103
+ const seen = [...this.s.lazy].find(([, l]) => lazyKey(l, l.field) === key)?.[0];
1104
+ const nvar = seen ? this.s.vars.get(seen) : this.newVar(`${o.lazy.prefix}${f}`, sort, 'input'), nv = Exec.valueOf(nvar);
1105
+ this.s.lazy.set(nvar.name, { ...o.lazy, field: f });
1088
1106
  const fields = new Map(o.fields).set(f, nv);
1089
1107
  return [nv, { ...p, heap: new Map(p.heap).set(v.id, { ...o, fields }) }];
1090
1108
  }