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
@@ -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 {
@@ -400,7 +425,7 @@ export function check(code, file, m, r, sorts, opts = {}) {
400
425
  return retried(() => checkOnce(code, file, m, r, sorts, opts), noEvidence);
401
426
  }
402
427
  function checkOnce(code, file, m, r, sorts, opts) {
403
- const isClass = m.shape === 'class', fns = m.shape === 'class' ? [m.entry] : [...new Set(m.events.map(e => e.call))];
428
+ const isClass = m.shape === 'class', standalone = !!m.standalone, fns = m.shape === 'class' ? [m.entry] : [...new Set(m.events.map(e => e.call))];
404
429
  let answers = {};
405
430
  // (the modules whose functions the class calls: each export answers its input, or nothing, by the callee's name)
406
431
  const ans = (path) => () => { const n = Object.keys(m.answers ?? {}).find(k => m.answers[k] === path); return n === undefined ? undefined : answers[n]; };
@@ -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)
@@ -444,6 +472,8 @@ function checkOnce(code, file, m, r, sorts, opts) {
444
472
  at: (snap, params) => (box.call('$at', undefined, [valueOf(snap, m.layout, m, evalAt(params), box.ctx), ctorValues(params)]).ok ? box.ctx.__r.value : (() => { throw new Error(`could not make the object: ${box.ctx.__r.error}`); })()),
445
473
  snapOf: (self, params) => snapOf(stateOf(self), m.layout, m, evalAt(params)),
446
474
  call: (self, e, args) => {
475
+ if (standalone)
476
+ return box.call(e.call, undefined, args);
447
477
  for (const f of new Set(Object.values(m.answers ?? {})))
448
478
  if (!f.startsWith('import:'))
449
479
  self[f] = answering(f);
@@ -459,8 +489,8 @@ function checkOnce(code, file, m, r, sorts, opts) {
459
489
  args: (inputs, e) => {
460
490
  answers = inputs;
461
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]; };
462
- const build = (a) => (a.k === 'input' ? dateIn(a.name) : a.k === 'lit' ? a.value : a.k === 'rec' ? Object.fromEntries(a.fields.map(([f, x]) => [f, build(x)])) : a.k === 'lazy'
463
- ? 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]]))
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'
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]]))
464
494
  : undefined);
465
495
  return e.args.map(build);
466
496
  },
@@ -490,15 +520,42 @@ function checkOnce(code, file, m, r, sorts, opts) {
490
520
  // (through its side) and of the rule, and compared.
491
521
  export function drive(m, r, sorts, code, opts = {}) {
492
522
  const t0 = performance.now(), rand = seeded((opts.seed ?? 7) >>> 0 || 1), bound = opts.bound ?? 12;
493
- const isClass = m.shape === 'class';
523
+ const isClass = m.shape === 'class', standalone = !!m.standalone;
494
524
  const interp = r.interpreter(), gen = r.compiled(), machine = r.machine;
495
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 };
496
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
+ };
497
553
  const paramKinds = m.params.map(v => [v, kindOfVar(v, sorts)]), inputKinds = m.inputs.map(v => [v, kindOfVar(v, sorts)]);
498
554
  const fail = (what) => { ev.mismatch = what; return finish(); };
499
555
  const finish = () => {
500
556
  ev.coverage = code.coverage();
501
557
  ev.ms = Math.round(performance.now() - t0);
558
+ journal.complete = journal.enabled && !journal.reason && journal.observations.length > 0;
502
559
  return ev;
503
560
  };
504
561
  const draws = (st, params) => [...consts, ...Object.values(st.leaves).filter((x) => typeof x === 'number'), ...Object.values(params).filter((x) => typeof x === 'number')];
@@ -518,7 +575,8 @@ export function drive(m, r, sorts, code, opts = {}) {
518
575
  }
519
576
  const keys = Object.values(st.maps).flatMap(c => Object.keys(c));
520
577
  // An input given as a natural (domains) is drawn as one: the claim is for those, as the user said.
521
- const x = draw(v.sort, sorts, v.name, rand, near, bound, [...strs, ...keys]);
578
+ const finite = m.standaloneDomains?.[v.name];
579
+ const x = finite ? finite[rand(finite.length)] : draw(v.sort, sorts, v.name, rand, near, bound, [...strs, ...keys]);
522
580
  inputs[v.name] = code.input ? code.input(v, x, rand) : opts.given?.[v.name] === 'nat' && typeof x === 'number' ? Math.abs(x) : x;
523
581
  }
524
582
  // (a list the request carries: up to 4 items, mostly, each field drawn by its sort)
@@ -530,11 +588,15 @@ export function drive(m, r, sorts, code, opts = {}) {
530
588
  const used = new Set();
531
589
  const walk = (a) => { if (a.k === 'input')
532
590
  used.add(a.name);
591
+ else if (a.k === 'maybe-bool') {
592
+ used.add(a.name);
593
+ used.add(a.missing);
594
+ }
533
595
  else if (a.k === 'rec')
534
596
  a.fields.forEach(([, x]) => walk(x));
535
597
  else if (a.k === 'lazy')
536
598
  for (const v of m.inputs)
537
- if (m.lazy?.get(v.name)?.prefix === a.prefix)
599
+ if (sameLazyRoot(m.lazy?.get(v.name), a))
538
600
  used.add(v.name); };
539
601
  e.args.forEach(walk);
540
602
  for (const v of m.inputs)
@@ -545,8 +607,17 @@ export function drive(m, r, sorts, code, opts = {}) {
545
607
  };
546
608
  // Steps the code and the rule from one state; undefined when they agree (the next state on both sides is returned
547
609
  // through `next`), else the difference.
548
- const step = (params, ps, side, st, inputs, e, next, where) => {
610
+ const step = (params, ps, side, st, inputs, e, next, where, reachable) => {
611
+ // A source type's finite numeric domain is part of the standalone claim, not
612
+ // behavior the source is alleged to reject. Never execute an out-of-domain probe.
613
+ if (m.standalone && Object.entries(m.standaloneDomains ?? {}).some(([name, values]) => !values.includes(inputs[name]))) {
614
+ ev.outside++;
615
+ next.stop = true;
616
+ return undefined;
617
+ }
549
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;
550
621
  if (m.folds)
551
622
  carry(m, raw, inputs, side.snap, params, r.decode(st));
552
623
  const nowVar = m.inputs.find(v => v.note?.startsWith('Date.now()'));
@@ -555,7 +626,18 @@ export function drive(m, r, sorts, code, opts = {}) {
555
626
  // The code.
556
627
  let res;
557
628
  try {
558
- if (isClass) {
629
+ if (standalone) {
630
+ const c = code.call(undefined, e, args);
631
+ if (!c.ok && c.outside) {
632
+ next.stop = true;
633
+ ev.outside++;
634
+ return undefined;
635
+ }
636
+ // Result fields in a prover witness are not state held by a pure
637
+ // function. Compare the returned value below, never carry those fields.
638
+ res = c.ok ? { snap: { leaves: {}, maps: {} }, out: c.value } : { refused: c.error };
639
+ }
640
+ else if (isClass) {
559
641
  const self = side.self, c = code.call(self, e, args);
560
642
  if (!c.ok && c.outside) {
561
643
  next.stop = true;
@@ -656,7 +738,7 @@ export function drive(m, r, sorts, code, opts = {}) {
656
738
  const ruleSide = ruleSnap(r, m, rule.st, sorts), diff = sameSnap(res.snap, ruleSide);
657
739
  if (diff)
658
740
  return `${where}: ${req} ${from}: ${diff}`;
659
- if (isClass) {
741
+ if (isClass || standalone) {
660
742
  // The method's result, as the rule keeps it: a value, a record's fields, or a value and whether it is missing.
661
743
  const rk = m.results?.[e.call], d = r.decode(rule.st);
662
744
  const bad = (what) => `${where}: ${req} ${from}: ${e.call} returns ${JSON.stringify(res.out)}, ${what}`;
@@ -678,7 +760,25 @@ export function drive(m, r, sorts, code, opts = {}) {
678
760
  return bad(`the rule's ${rk.name} is ${JSON.stringify(d[rk.name])}`);
679
761
  }
680
762
  }
681
- 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;
682
782
  next.st = rule.st;
683
783
  return undefined;
684
784
  };
@@ -729,7 +829,9 @@ export function drive(m, r, sorts, code, opts = {}) {
729
829
  const diff = sameSnap(snap, ruleSnap(r, m, st, sorts));
730
830
  if (diff)
731
831
  return { problem: `new ${m.entry}(${JSON.stringify(params)}): ${diff}` };
732
- 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 };
733
835
  }
734
836
  catch (x) {
735
837
  if (x instanceof HarnessFailure)
@@ -752,6 +854,7 @@ export function drive(m, r, sorts, code, opts = {}) {
752
854
  const problem = code.init?.(snap, params);
753
855
  if (problem)
754
856
  return { problem };
857
+ recordInitial({ snap }, params);
755
858
  return { side: { snap }, st, ps: ps ?? {} };
756
859
  };
757
860
  const runs = opts.runs ?? 200, depth = opts.depth ?? 12;
@@ -765,7 +868,7 @@ export function drive(m, r, sorts, code, opts = {}) {
765
868
  let side = s0.side, st = s0.st;
766
869
  for (let d = 0; d < depth; d++) {
767
870
  const { e, inputs } = drawRequest(side.snap, params), next = {};
768
- 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);
769
872
  ev.requests++;
770
873
  if (diff)
771
874
  return fail(diff);
@@ -846,7 +949,8 @@ export function drive(m, r, sorts, code, opts = {}) {
846
949
  if (isClass && self === undefined)
847
950
  return undefined;
848
951
  const side = { snap, ...(isClass ? { self: self } : {}) };
849
- 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);
850
954
  };
851
955
  for (let i = 0; i < (opts.states ?? 400); i++) {
852
956
  const params = drawParams(), snap = drawSnap(params), { e, inputs } = drawRequest(snap, params);
@@ -904,6 +1008,44 @@ export function drive(m, r, sorts, code, opts = {}) {
904
1008
  return fail(diff);
905
1009
  }
906
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
+ }
907
1049
  return finish();
908
1050
  }
909
1051
  const mapReplacer = (_, v) => (isMap(v) ? { $map: [...v.entries()] } : v);
@@ -7,6 +7,8 @@ import { node } from "./extract-go.js";
7
7
  function harness(pkg, read, m, discard) {
8
8
  const T = (t) => pkg.ttab[t] ?? { k: 'invalid' };
9
9
  const imports = new Set(['bufio', 'encoding/json', 'fmt', 'os', 'reflect', 'strconv', 'math/big']);
10
+ if (read.clocks?.length)
11
+ imports.add('time');
10
12
  const qual = (t) => { const x = T(t); if (x.pkg && !x.own && x.pkg !== '')
11
13
  imports.add(x.pkg); };
12
14
  const acc = (path) => `o.${path.join('.')}`;
@@ -120,12 +122,17 @@ import (
120
122
  ${[...imports].sort().map(p => `\t${p.split('/')[0].includes('.') ? `${p.replace(/[^A-Za-z0-9]/g, '_').replace(/^/, 'gdp_')} ` : ''}${JSON.stringify(p)}`).join('\n')}
121
123
  )
122
124
 
125
+ ${read.clocks?.length ? `// Only the time source is substituted; Unix/UnixMilli run in Go unchanged.
126
+ var gdpNow int64
127
+ func gdpTimeNow(_ func() time.Time) time.Time { return time.UnixMilli(gdpNow) }
128
+ ` : ''}
123
129
  type gdpStep struct {
124
130
  M string \`json:"m"\`
125
131
  A []json.RawMessage \`json:"a"\`
126
132
  }
127
133
  type gdpCmd struct {
128
134
  Op string \`json:"op"\`
135
+ Now int64 \`json:"now"\`
129
136
  ID int \`json:"id"\`
130
137
  State map[string]json.RawMessage \`json:"state"\`
131
138
  M string \`json:"m"\`
@@ -280,7 +287,7 @@ func GdpHarnessMain(in, out string) {
280
287
  case "get":
281
288
  res = map[string]any{"state": gdpGet(objs[c.ID])}
282
289
  case "call":
283
- ${read.answers?.length ? 'gdpAnswers = c.Answers\n\t\t\t' : ''}res = gdpRun(objs[c.ID], gdpStep{M: c.M, A: c.A})
290
+ ${read.clocks?.length ? 'gdpNow = c.Now\n\t\t\t' : ''}${read.answers?.length ? 'gdpAnswers = c.Answers\n\t\t\t' : ''}res = gdpRun(objs[c.ID], gdpStep{M: c.M, A: c.A})
284
291
  }
285
292
  b, _ := json.Marshal(res)
286
293
  wr.Write(b)
@@ -332,7 +339,18 @@ export function checkGo(dir, pkg, read, r, sorts, gopts) {
332
339
  }
333
340
  // (each answered call rewritten to the harness's answer in a copy of its file, the build told by an overlay)
334
341
  const over = {};
335
- for (const [f, t] of stubbed(read, f => fs.readFileSync(`${dir}/${f}`, 'utf8'), (a, _i, t) => `gdpAnswer[${a.ty}](${JSON.stringify(a.key)}, ${t.slice(0, t.indexOf('('))}, ${t.slice(t.indexOf('(') + 1)}`)) {
342
+ const answers = read.answers ?? [], clocks = read.clocks ?? [];
343
+ // Go positions count UTF-8 bytes; explicit stub spans count JS code units.
344
+ const byteSpan = (p, end) => {
345
+ const m = /^(.*):(\d+):(\d+)$/.exec(p), lines = fs.readFileSync(`${dir}/${m[1]}`, 'utf8').split('\n');
346
+ const offset = (line, column) => lines.slice(0, line - 1).reduce((n, s) => n + s.length + 1, 0) + new TextDecoder('utf-8', { fatal: true }).decode(new TextEncoder().encode(lines[line - 1]).slice(0, column - 1)).length;
347
+ const e = end.split(':').map(Number);
348
+ return [offset(Number(m[2]), Number(m[3])), offset(e[0], e[1])];
349
+ };
350
+ const clockSites = clocks.map(c => ({ key: 'Go wall clock', at: [{ p: c.p, span: byteSpan(c.p, c.end) }] }));
351
+ // A Unicode clock prefix also moves any answer later on the same line.
352
+ const answerSites = !clocks.length ? answers : answers.map(a => ({ ...a, at: a.at?.map(s => s.span || !s.end ? s : { ...s, span: byteSpan(s.p, s.end) }) }));
353
+ for (const [f, t] of stubbed({ ...read, answers: [...answerSites, ...clockSites] }, f => fs.readFileSync(`${dir}/${f}`, 'utf8'), (a, i, t) => i >= answers.length ? `gdpTimeNow(${clocks[i - answers.length].callee})` : `gdpAnswer[${a.ty}](${JSON.stringify(a.key)}, ${t.slice(0, t.indexOf('('))}, ${t.slice(t.indexOf('(') + 1)}`)) {
336
354
  const o = node('node:path').resolve(dir, f);
337
355
  fs.writeFileSync(`${work}/${f}`, t);
338
356
  over[o] = over[node('node:fs').realpathSync(o)] = `${work}/${f}`;
@@ -481,6 +499,7 @@ export function speak(work, bin, env, pkg, read, r, sorts, opts, count) {
481
499
  return s;
482
500
  };
483
501
  let coverage;
502
+ let now = 0;
484
503
  const r0 = performance.now();
485
504
  const side = {
486
505
  // (a constructor's arguments, C++'s: the rule's parameters)
@@ -495,7 +514,7 @@ export function speak(work, bin, env, pkg, read, r, sorts, opts, count) {
495
514
  answers = Object.fromEntries(read.answers.map(a => { const x = v[a.inputs.name] ?? 0; if (a.fit && a.range && (Number(x) < a.range[0] || Number(x) > a.range[1]))
496
515
  throw new Outside(`${a.key} answers ${String(x)}, outside its type`); return [a.key, a.inputs.none && v[a.inputs.none] === true ? { none: true } : { in: x }]; }));
497
516
  }
498
- const res = ask({ op: 'call', id: self, m: e.call, a: args, ...(answers ? { answers } : {}) });
517
+ const res = ask({ op: 'call', id: self, m: e.call, now, a: args, ...(answers ? { answers } : {}) });
499
518
  if (res.frame)
500
519
  throw new Error(`the code changes ${res.frame}, a field the rule leaves out`);
501
520
  if (res.bad)
@@ -505,7 +524,8 @@ export function speak(work, bin, env, pkg, read, r, sorts, opts, count) {
505
524
  return { ok: true, value: typeof res.out === 'string' && /^-?\d+$/.test(res.out) && m.results?.[e.call] && m.state.find(v => v.name === m.results[e.call].name)?.sort.k === 'num' ? Number(res.out) : res.out };
506
525
  },
507
526
  args: (inputs, e) => e.args.map(a => argJson(a, inputs)),
508
- setNow: () => { },
527
+ setNow: n => { if (!Number.isSafeInteger(n))
528
+ throw new Outside('Go clock outside the exact integer range'); now = n; },
509
529
  coverage: () => (coverage ??= closeAndCount()),
510
530
  input: (v, x, rand) => { const y = rand(8) === 0 ? x : fit(x, v.name, rand); return typeof y === 'number' && y < 0 && sorts.get(v.name) === 'nat' ? -y : y; },
511
531
  drawSnap: rand => {