gdp-wired 0.50.2 → 0.50.3

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 (49) hide show
  1. package/README.md +4 -2
  2. package/dist/core/cli.d.ts +12 -1
  3. package/dist/core/cli.js +62 -25
  4. package/dist/core/discover.d.ts +6 -1
  5. package/dist/core/discover.js +54 -7
  6. package/dist/core/dsl-deadline.d.ts +3 -0
  7. package/dist/core/dsl-deadline.js +26 -2
  8. package/dist/core/dsl.d.ts +3 -1
  9. package/dist/core/dsl.js +93 -30
  10. package/dist/core/effect.d.ts +12 -0
  11. package/dist/core/effect.js +26 -9
  12. package/dist/core/ex/harness.exs +171 -5
  13. package/dist/core/extract-c.js +63 -6
  14. package/dist/core/extract-check.d.ts +5 -1
  15. package/dist/core/extract-check.js +28 -10
  16. package/dist/core/extract-go-check.js +127 -1
  17. package/dist/core/extract-go.js +8 -2
  18. package/dist/core/extract-jvm.js +2 -2
  19. package/dist/core/extract-rs.js +51 -5
  20. package/dist/core/extract-step.js +40 -6
  21. package/dist/core/extract-swift.js +47 -3
  22. package/dist/core/extract.d.ts +8 -0
  23. package/dist/core/infer.d.ts +8 -0
  24. package/dist/core/infer.js +133 -16
  25. package/dist/core/jvm/Harness.java +135 -3
  26. package/dist/core/jvm/Rt.java +66 -4
  27. package/dist/core/laws.js +51 -10
  28. package/dist/core/native-law.d.ts +3 -1
  29. package/dist/core/native-law.js +126 -14
  30. package/dist/core/native-observations.d.ts +20 -0
  31. package/dist/core/native-observations.js +41 -0
  32. package/dist/core/native-wire.d.ts +1 -0
  33. package/dist/core/native-wire.js +16 -2
  34. package/dist/core/py/harness.py +21 -4
  35. package/dist/core/rb/harness.rb +178 -9
  36. package/dist/core/search-termination.d.ts +35 -0
  37. package/dist/core/search-termination.js +13 -0
  38. package/dist/core/search-watchdog.d.ts +8 -0
  39. package/dist/core/search-watchdog.js +34 -0
  40. package/dist/core/source-check.d.ts +3 -0
  41. package/dist/core/swift/Harness.swift +65 -4
  42. package/dist/core/swift/Main.swift +27 -4
  43. package/dist/core/wall.d.ts +3 -1
  44. package/dist/core/wall.js +7 -4
  45. package/dist/core/work-refusal.d.ts +3 -0
  46. package/dist/core/work-refusal.js +8 -0
  47. package/dist/kernel/prove.d.ts +2 -0
  48. package/dist/kernel/prove.js +13 -5
  49. package/package.json +1 -1
@@ -87,13 +87,14 @@ public final class Harness {
87
87
  for (int i = 0; i < urls.length; i++) urls[i] = cp.get(i).toURI().toURL();
88
88
  loader = new URLClassLoader(urls, Harness.class.getClassLoader());
89
89
  cls = Class.forName((String) req.get("jcls"), false, loader);
90
- return m("ok", true);
90
+ return m("ok", true, "nativeBindings", 1, "nativeSnapshot", 1, "nativeObservations", 1);
91
91
  }
92
92
  case "new": try { return m("id", make((List<?>) req.get("a"))); } catch (Throwable e) { return m("err", err(e)); }
93
93
  case "at":
94
94
  try { long i = make((List<?>) req.get("a")); setState(OBJS.get(i), (Map<?, ?>) req.get("state")); return m("id", i); }
95
95
  catch (Throwable e) { return m("bad", err(e)); }
96
96
  case "get": { long id = ((Number) req.get("id")).longValue(); ST = STORES.get(id); return m("state", stateOf(OBJS.get(id))); }
97
+ case "native": return m("snapshot", nativeState(OBJS.get(((Number) req.get("id")).longValue())));
97
98
  case "call": return call(req);
98
99
  case "coverage": return m("hit", List.of());
99
100
  default: return m("error", "no op " + op);
@@ -336,6 +337,129 @@ public final class Harness {
336
337
  STORES.put(id, ST);
337
338
  return id;
338
339
  }
340
+ // Scalar arguments observed after JVM conversion and before invocation. Names
341
+ // come from the callable's bytecode, never from the symbolic request schema.
342
+ // Unsupported values or classes without parameter metadata remain unchecked.
343
+ static long nativeIdentity = 0;
344
+ static final IdentityHashMap<Object, String> nativeObjects = new IdentityHashMap<>();
345
+ static String nativeId(Object value) {
346
+ String id = nativeObjects.get(value);
347
+ if (id == null) {
348
+ if (nativeObjects.size() >= 100000) throw new IllegalArgumentException("native snapshot exceeds identity bound");
349
+ id = Long.toString(++nativeIdentity); nativeObjects.put(value, id);
350
+ }
351
+ return id;
352
+ }
353
+ static Object nativeValue(Object value, Set<Object> seen, int[] nodes, boolean root) throws Exception {
354
+ if (++nodes[0] > 10000) throw new IllegalArgumentException("native snapshot exceeds node bound");
355
+ if (value == null || value instanceof Boolean || value instanceof String) return value;
356
+ if (value instanceof Character c) return (int) c.charValue();
357
+ if (value instanceof Enum<?> e) return e.name();
358
+ if (value instanceof AtomicInteger a) return a.get();
359
+ if (value instanceof AtomicLong a) return nativeValue(a.get(), seen, nodes, false);
360
+ if (value instanceof AtomicBoolean a) return a.get();
361
+ if (value instanceof AtomicReference<?> a) return nativeValue(a.get(), seen, nodes, false);
362
+ if (value instanceof Optional<?> o) return nativeValue(o.orElse(null), seen, nodes, false);
363
+ if (value instanceof Number n) {
364
+ if (!(value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long || value instanceof Float || value instanceof Double))
365
+ throw new IllegalArgumentException("unsupported native snapshot number: " + value.getClass().getName());
366
+ double number = n.doubleValue();
367
+ if (!Double.isFinite(number) || Math.rint(number) != number || Math.abs(number) > 9007199254740991d)
368
+ throw new IllegalArgumentException("native snapshot number outside exact integer range");
369
+ return n.longValue();
370
+ }
371
+ String id = nativeId(value);
372
+ if (!seen.add(value)) return m("kind", "ref", "id", id);
373
+ List<Object> entries = new ArrayList<>();
374
+ String kind = "object";
375
+ if (value instanceof Map<?, ?> map) {
376
+ if (value.getClass().getClassLoader() != null) throw new IllegalArgumentException("unsupported native snapshot map implementation");
377
+ kind = "map";
378
+ for (Map.Entry<?, ?> entry : map.entrySet()) {
379
+ Object key = entry.getKey();
380
+ if (!(key instanceof String) && !(key instanceof Number)) throw new IllegalArgumentException("unsupported native snapshot map key");
381
+ entries.add(Arrays.asList(nativeValue(key, seen, nodes, false), nativeValue(entry.getValue(), seen, nodes, false)));
382
+ }
383
+ } else if (value instanceof List<?> list) {
384
+ if (value.getClass().getClassLoader() != null) throw new IllegalArgumentException("unsupported native snapshot list implementation");
385
+ kind = "array";
386
+ for (Object item : list) entries.add(nativeValue(item, seen, nodes, false));
387
+ } else if (value.getClass().isArray()) {
388
+ kind = "array";
389
+ for (int i = 0; i < Array.getLength(value); i++) entries.add(nativeValue(Array.get(value, i), seen, nodes, false));
390
+ } else {
391
+ Set<String> names = new LinkedHashSet<>();
392
+ if (root) {
393
+ for (Object leaf0 : list(S.get("leaves"))) {
394
+ Map<?, ?> leaf = (Map<?, ?>) leaf0;
395
+ List<?> path = list(leaf.get("path"));
396
+ if (!path.isEmpty() && !"frame".equals(leaf.get("kind"))) names.add((String) path.get(0));
397
+ }
398
+ } else {
399
+ if (value.getClass().getName().startsWith("java.")) throw new IllegalArgumentException("unsupported native snapshot value: " + value.getClass().getName());
400
+ for (Class<?> c = value.getClass(); c != null && c != Object.class; c = c.getSuperclass())
401
+ for (Field f : c.getDeclaredFields()) if (!Modifier.isStatic(f.getModifiers()) && !f.isSynthetic()) names.add(f.getName());
402
+ }
403
+ for (String name : names) entries.add(Arrays.asList(name, nativeValue(field(value.getClass(), name).get(value), seen, nodes, false)));
404
+ }
405
+ return m("kind", kind, "id", id, "items", entries);
406
+ }
407
+ static Object nativeState(Object value) throws Exception {
408
+ return m("version", 1, "root", nativeValue(value, Collections.newSetFromMap(new IdentityHashMap<>()), new int[]{0}, true));
409
+ }
410
+ static Object nativeBindings(Method method, Object[] args) {
411
+ Parameter[] parameters = method.getParameters();
412
+ if (parameters.length != args.length) throw new IllegalArgumentException("native parameter arity unavailable");
413
+ List<Object> entries = new ArrayList<>();
414
+ for (int i = 0; i < parameters.length; i++) {
415
+ Parameter parameter = parameters[i];
416
+ if (!parameter.isNamePresent()) throw new IllegalArgumentException("native parameter name unavailable: " + method.getName());
417
+ Object value = args[i];
418
+ if (value instanceof Character c) value = (int) c.charValue();
419
+ else if (value instanceof Enum<?> e) value = e.name();
420
+ else if (value instanceof Number n) {
421
+ if (!(value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long || value instanceof Float || value instanceof Double))
422
+ throw new IllegalArgumentException("unsupported native parameter number: " + parameter.getName());
423
+ double number = n.doubleValue();
424
+ if (!Double.isFinite(number) || Math.rint(number) != number || Math.abs(number) > 9007199254740991d)
425
+ throw new IllegalArgumentException("native parameter number outside exact integer range: " + parameter.getName());
426
+ value = n.longValue();
427
+ } else if (value != null && !(value instanceof String) && !(value instanceof Boolean))
428
+ throw new IllegalArgumentException("unsupported native parameter value: " + parameter.getName());
429
+ entries.add(Arrays.asList(parameter.getName(), value));
430
+ }
431
+ return m("version", 1, "root", m("kind", "object", "id", Long.toString(++nativeIdentity), "items", entries));
432
+ }
433
+
434
+ // Metadata objects are transport records, not native source maps. Actual
435
+ // answer values were captured and range-checked by Rt at the read occurrence.
436
+ static Object observationObject(Map<String, Object> fields) throws Exception {
437
+ List<Object> entries = new ArrayList<>();
438
+ for (Map.Entry<String, Object> entry : fields.entrySet()) {
439
+ Object value = entry.getValue();
440
+ if (value instanceof Map<?, ?> map) {
441
+ Map<String, Object> nested = new LinkedHashMap<>();
442
+ for (Map.Entry<?, ?> item : map.entrySet()) nested.put((String) item.getKey(), item.getValue());
443
+ value = observationObject(nested);
444
+ } else value = nativeValue(value, Collections.newSetFromMap(new IdentityHashMap<>()), new int[]{0}, false);
445
+ entries.add(Arrays.asList(entry.getKey(), value));
446
+ }
447
+ return m("kind", "object", "id", Long.toString(++nativeIdentity), "items", entries);
448
+ }
449
+ static Map<String, Object> nativeObservations(gdp.Rt.Observations observed) {
450
+ if (observed.error != null) return m("error", observed.error);
451
+ try {
452
+ Map<String, Object> calls = new LinkedHashMap<>();
453
+ for (Map.Entry<String, gdp.Rt.Call> entry : observed.calls.entrySet()) {
454
+ gdp.Rt.Call call = entry.getValue();
455
+ calls.put(entry.getKey(), call.kind.equals("returned") ? m("kind", "returned", "value", call.value) : m("kind", "raised", "raised", call.raised));
456
+ }
457
+ Map<String, Object> fields = m("invocation", observed.invocation, "calls", calls);
458
+ if (observed.clock != null) fields.put("clock", observed.clock);
459
+ return m("snapshot", m("version", 1, "root", observationObject(fields)));
460
+ } catch (Exception error) { return m("error", err(error)); }
461
+ }
462
+
339
463
  static Object call(Map<?, ?> req) throws Exception {
340
464
  long id = ((Number) req.get("id")).longValue();
341
465
  Object obj = OBJS.get(id);
@@ -351,17 +475,25 @@ public final class Harness {
351
475
  Object[] a = new Object[ts.length];
352
476
  try { for (int i = 0; i < ts.length; i++) a[i] = i < specs.size() ? build(((List<?>) specs.get(i)).get(1), ts[i], gs[i]) : inert(ts[i]); }
353
477
  catch (Exception e) { return m("bad", err(e)); }
478
+ Map<String, Object> bindings;
479
+ try { bindings = m("snapshot", nativeBindings(m, a)); }
480
+ catch (Exception e) { bindings = m("error", err(e)); }
354
481
  Map<String, String> before = frames(obj);
355
482
  Map<String, Object> snap = Boolean.TRUE.equals(S.get("discard")) ? stateOf(obj) : null;
356
483
  Object out = null;
357
484
  String err = null;
358
- try { out = m.invoke(Modifier.isStatic(m.getModifiers()) ? null : obj, a); } catch (InvocationTargetException e) { err = err(e); }
485
+ Set<String> observedKeys = new HashSet<>();
486
+ for (Object answer : list(S.get("answers"))) observedKeys.add((String) ((Map<?, ?>) answer).get("key"));
487
+ gdp.Rt.Observations observed = gdp.Rt.beginObservations(observedKeys);
488
+ try { out = m.invoke(Modifier.isStatic(m.getModifiers()) ? null : obj, a); }
489
+ catch (InvocationTargetException e) { err = err(e); }
490
+ finally { gdp.Rt.endObservations(observed); }
359
491
  if (err != null && snap != null) setState(obj, snap);
360
492
  // A method returning the object's next value (an immutable class's step): the object is that value.
361
493
  if (err == null && ((List<?>) S.get("reducers")).contains(key) && cls.isInstance(out)) { OBJS.put(id, out); obj = out; out = null; }
362
494
  Map<String, String> after = frames(obj);
363
495
  for (Map.Entry<String, String> e : before.entrySet()) if (!e.getValue().equals(after.get(e.getKey())) && !((List<?>) S.get("reducers")).contains(key)) return m("frame", e.getKey());
364
- Map<String, Object> res = m("out", tag(out));
496
+ Map<String, Object> res = m("out", tag(out), "nativeBindings", bindings, "nativeObservations", nativeObservations(observed));
365
497
  if (err != null) res.put("err", err);
366
498
  return res;
367
499
  }
@@ -1,10 +1,72 @@
1
- // What the check's copy of the code calls where the original reads the clock or makes a call the caller answered
2
- // (core/extract-jvm.ts rewrites those sites): the request's time and the request's answer, set by core/jvm/Harness.java.
1
+ // Runtime hooks used only by the check's instrumented copy of original code.
3
2
  package gdp;
4
3
 
4
+ import java.util.*;
5
+ import java.util.concurrent.atomic.AtomicLong;
6
+
5
7
  public final class Rt {
6
8
  public static volatile long NOW;
7
9
  public static java.util.function.BiFunction<String, Class<?>, Object> ANSWER = (k, c) -> null;
8
- public static long now() { return NOW; }
9
- public static Object answer(String key, Class<?> c) { return ANSWER.apply(key, c); }
10
+ private static final AtomicLong NEXT = new AtomicLong();
11
+ private static final ThreadLocal<Observations> ACTIVE = new ThreadLocal<>();
12
+ public static final class Call {
13
+ public final String kind, raised;
14
+ public final Object value;
15
+ private Call(String kind, Object value, String raised) { this.kind = kind; this.value = value; this.raised = raised; }
16
+ }
17
+ public static final class Observations {
18
+ public final long invocation;
19
+ public final Map<String, Call> calls = new LinkedHashMap<>();
20
+ public Long clock;
21
+ public String error;
22
+ private final Set<String> expected;
23
+ private Observations(Set<String> expected) { this.invocation = NEXT.incrementAndGet(); this.expected = Set.copyOf(expected); }
24
+ private void fail(String message) { if (error == null) error = message; }
25
+ }
26
+ public static Observations beginObservations(Set<String> expected) {
27
+ if (ACTIVE.get() != null) throw new IllegalStateException("nested native observation invocation");
28
+ Observations value = new Observations(expected); ACTIVE.set(value); return value;
29
+ }
30
+ public static void endObservations(Observations value) {
31
+ if (ACTIVE.get() != value) throw new IllegalStateException("native observation invocation changed");
32
+ ACTIVE.remove();
33
+ }
34
+ private static boolean scalar(Object value) {
35
+ if (value == null || value instanceof Boolean || value instanceof String || value instanceof Character || value instanceof Enum<?>) return true;
36
+ if (!(value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long || value instanceof Float || value instanceof Double)) return false;
37
+ if (value instanceof Double d && Double.doubleToRawLongBits(d) == Long.MIN_VALUE || value instanceof Float f && Float.floatToRawIntBits(f) == Integer.MIN_VALUE) return false;
38
+ double n = ((Number) value).doubleValue();
39
+ return Double.isFinite(n) && Math.rint(n) == n && Math.abs(n) <= 9007199254740991d;
40
+ }
41
+ private static void record(String key, Call call) {
42
+ Observations observations = ACTIVE.get();
43
+ if (observations == null) return;
44
+ if (!observations.expected.contains(key)) { observations.fail("unbound instrumented answer: " + key); return; }
45
+ if (call.kind.equals("returned") && !scalar(call.value)) { observations.fail("unsupported actual answer value: " + key); return; }
46
+ Call previous = observations.calls.get(key);
47
+ if (previous != null && (!previous.kind.equals(call.kind) || !Objects.equals(previous.value, call.value) || !Objects.equals(previous.raised, call.raised))) {
48
+ observations.fail("different actual answers in one invocation: " + key); return;
49
+ }
50
+ observations.calls.put(key, call);
51
+ }
52
+ public static long now() {
53
+ long value = NOW;
54
+ Observations observations = ACTIVE.get();
55
+ if (observations != null) {
56
+ if (value < -9007199254740991L || value > 9007199254740991L) observations.fail("actual clock outside exact integer range");
57
+ if (observations.clock != null && observations.clock.longValue() != value) observations.fail("different actual clock reads in one invocation");
58
+ else observations.clock = value;
59
+ }
60
+ return value;
61
+ }
62
+ public static Object answer(String key, Class<?> c) {
63
+ try {
64
+ Object value = ANSWER.apply(key, c);
65
+ record(key, new Call("returned", value, null));
66
+ return value;
67
+ } catch (RuntimeException | Error error) {
68
+ record(key, new Call("raised", null, error.getClass().getName()));
69
+ throw error;
70
+ }
71
+ }
10
72
  }
package/dist/core/laws.js CHANGED
@@ -27,7 +27,7 @@
27
27
  // every item of a list (o.price its field; `o in asks` whether that item is still
28
28
  // in it, the same item, not an equal one), at every two (or three) at once
29
29
  // mode == "closed", outcome == SLOW_ERROR, mode == :closed a choice by its value
30
- import { Choice, Int, Str, Term, all, any, forall, no, not, yes } from "./dsl.js";
30
+ import { Choice, Int, ItemsRef, Str, Term, all, any, forall, no, not, yes } from "./dsl.js";
31
31
  import { copyVariable } from "./dsl-binders.js";
32
32
  import { attachNativeLaw } from "./source-check.js";
33
33
  import { nativeLaw } from "./native-law.js";
@@ -256,8 +256,22 @@ export function parse(s) {
256
256
  // The extraction's names, with the request's time as `now` where the rule reads it and no name says so (a TypeScript
257
257
  // class's Date.now()).
258
258
  export function namesWithClock(x) {
259
- const ns = x.names ?? [], ins = x.rule?.parts?.inputs.map(([n]) => n) ?? [];
260
- return ns.some(n => n.role === 'clock') || !ins.includes('now') || ns.some(n => n.code === 'now') ? ns : [...ns, { code: 'now', rule: 'now', role: 'clock' }];
259
+ // Result names from the model are the actual lowered variables; source method
260
+ // spelling is not necessarily a valid rule identifier (for example Ruby `seen?`).
261
+ const original = x.names ?? [];
262
+ const ns = original.map(n => {
263
+ if (n.role !== 'result' || n.code !== 'result' || !n.method)
264
+ return n;
265
+ const result = x.model?.results?.[n.method];
266
+ if (!result)
267
+ return n;
268
+ const value = result.k === 'rec' ? result.fields.find(([field]) => field === 'value')?.[1] : result.name;
269
+ const none = result.k === 'rec' ? result.fields.find(([field]) => field === 'none')?.[1] : result.k === 'maybe' ? result.missing : undefined;
270
+ return value && (value !== n.rule || (n.none && none && n.none !== none)) ? { ...n, rule: value, ...(n.none && none ? { none } : {}) } : n;
271
+ });
272
+ const ins = x.rule?.parts?.inputs.map(([n]) => n) ?? [];
273
+ const named = ns.every((n, i) => n === original[i]) ? original : ns;
274
+ return named.some(n => n.role === 'clock') || !ins.includes('now') || named.some(n => n.code === 'now') ? named : [...named, { code: 'now', rule: 'now', role: 'clock', native: { kind: 'clock', key: 'now' } }];
261
275
  }
262
276
  const calendarOf = (opts) => {
263
277
  if (!opts.calendar)
@@ -309,7 +323,7 @@ export function buildLaw(x, l, opts = {}) {
309
323
  };
310
324
  // (a law of one step reads no function, so business days there pin each time's week to a key, ∀w. guard → law)
311
325
  const body = (b, a) => (step && probe.roles.has('bdays') ? pinned(b, a, (bb, aa, p) => body0(bb, aa, p)) : bitBody(b, a));
312
- const bind = (built) => { attachNativeLaw(x.rule, built.law, l.name, built.kind === 'step' ? gate ?? method : undefined, nativeLaw(e, opts, parse, { ...Object.fromEntries(names.filter(n => n.role === 'const' && n.value !== undefined).map(n => [n.code, n.value])), ...x.consts }, new Set(names.map(n => n.code.split('.')[0])))); return built; };
326
+ const bind = (built) => { attachNativeLaw(x.rule, built.law, l.name, built.kind === 'step' ? gate ?? method : undefined, nativeLaw(e, opts, parse, { ...Object.fromEntries(names.filter(n => n.role === 'const' && n.value !== undefined).map(n => [n.code, n.value])), ...x.consts }, new Set(names.map(n => n.code.split('.')[0])), names.flatMap(n => n.native ? [{ ...n.native, code: n.code, ...(n.method ? { method: n.method } : {}) }] : []), names)); return built; };
313
327
  if (!step)
314
328
  return bind({ kind: 'law', law: r.law(l.name, (env) => (x.quiet ? env[x.quiet].eq(0).implies(body0(env, env)) : body0(env, env))) });
315
329
  const mname = names.find(n => n.role === 'method')?.rule;
@@ -622,7 +636,7 @@ const constOf = (x) => (x.k === 'num' ? x.v : x.k === 'un' && x.op === '-' && x.
622
636
  function compare(op, a, b, e, strictOptional) {
623
637
  if (b.t === 'null' || a.t === 'null') {
624
638
  const literal = a.t === 'null' ? a : b;
625
- const o = a.t === 'null' ? b : a, none = o.t === 'opt' ? o.none : o.t === 'cell' ? not(o.rec.has) : undefined;
639
+ const o = a.t === 'null' ? b : a, none = o.t === 'opt' || o.t === 'map' ? o.none : o.t === 'cell' ? not(o.rec.has) : undefined;
626
640
  if (strictOptional && o.t === 'opt' && literal.absence && o.absence && literal.absence !== o.absence)
627
641
  return op === '==' ? no : op === '!=' ? yes : fail(`${op} with None`);
628
642
  if (!none)
@@ -760,7 +774,7 @@ function path(e, c, names, dry) {
760
774
  }
761
775
  const segs = e.segs.slice(skip + n - 1 + (hit.role === 'answer' && next && 'call' in next ? 1 : 0));
762
776
  // (a map read where it is named: old(m) is the map before the step wherever its cells are read, `k in old(m)`)
763
- return rest(segs, hit.map ? { t: 'map', n: hit, maps: names.filter(x => x.map && x.code === hit.code), env: c.a } : leaf(hit, c, dry), c, names, dry, e);
777
+ return rest(segs, hit.map ? { t: 'map', n: hit, maps: names.filter(x => x.map && x.code === hit.code), env: c.a, ...(hit.none ? { none: dry ? yes : c.a[hit.none] } : {}) } : leaf(hit, c, dry), c, names, dry, e);
764
778
  }
765
779
  }
766
780
  }
@@ -801,10 +815,21 @@ function find(code, names, c, stateOnly, called) {
801
815
  return inputs[0];
802
816
  throw new LawError(`${code} is an argument of ${inputs.map(n => n.method).join(', ')}: write the law on the method it is about (the line above it), or as <method>.${code}`);
803
817
  }
804
- return names.find(n => n.role === 'state' && at(n) && !called)
805
- ?? (stateOnly ? undefined : names.find(n => (n.role === 'param' || n.role === 'const' || n.role === 'clock') && n.code === code && !called))
806
- ?? names.find(n => n.role === 'answer' && last(n))
807
- ?? (stateOnly ? undefined : names.find(n => n.rule === code && !called));
818
+ const preferred = names.find(n => n.role === 'state' && at(n) && !called)
819
+ ?? (stateOnly ? undefined : names.find(n => (n.role === 'param' || n.role === 'const' || n.role === 'clock') && n.code === code && !called));
820
+ if (preferred)
821
+ return preferred;
822
+ const answers = names.filter(n => n.role === 'answer' && last(n));
823
+ const here = c.method ? answers.filter(n => n.method === c.method) : [];
824
+ const generic = answers.filter(n => n.method === undefined);
825
+ const candidates = here.length ? here : generic.length ? generic : c.method ? [] : answers;
826
+ if (candidates.length > 1)
827
+ throw new LawError(`${code}: ambiguous answered call of ${candidates.map(n => n.method ?? n.code).join(', ')}; write the law on its method or use its qualified name`);
828
+ if (candidates.length === 1)
829
+ return candidates[0];
830
+ if (answers.length && c.method)
831
+ throw new LawError(`${code}: no answer belongs to ${c.method} (its methods: ${answers.map(n => n.method).join(', ')})`);
832
+ return stateOnly ? undefined : names.find(n => n.rule === code && !called);
808
833
  }
809
834
  const results = (names, c) => {
810
835
  const rs = names.filter(n => n.role === 'result' && n.code === 'result');
@@ -815,6 +840,8 @@ const results = (names, c) => {
815
840
  };
816
841
  // A name's value: its variable in the environment (the state after the step where the law is a step's), its None-ness.
817
842
  function leaf(n, c, dry) {
843
+ if (n.list)
844
+ return { t: 'list', n, env: c.step && n.role === 'state' ? c.a : c.b };
818
845
  if (dry)
819
846
  return n.none && !n.rule ? { t: 'opt', none: yes } : n.none ? { t: 'opt', none: yes, v: DRY } : DRY;
820
847
  if (n.role === 'const')
@@ -829,6 +856,20 @@ function leaf(n, c, dry) {
829
856
  function rest(segs, v, c, names, dry, e) {
830
857
  for (let i = 0; i < segs.length; i++) {
831
858
  const s = segs[i];
859
+ if (v.t === 'list') {
860
+ if (!('i' in s))
861
+ throw new LawError(`${show(e)}: a scalar list is read at a position (xs[i])`);
862
+ const index = val(s.i, c, names, dry);
863
+ if (dry) {
864
+ v = DRY;
865
+ continue;
866
+ }
867
+ const value = v.env[v.n.rule];
868
+ if (!(value instanceof ItemsRef))
869
+ throw new LawError(`${v.n.code}: not a scalar item list in the rule's environment`);
870
+ v = wrap(value.at(key(index)));
871
+ continue;
872
+ }
832
873
  if (v.t === 'map') {
833
874
  const isGet = 'f' in s && ['get', 'fetch', 'getOrDefault', 'lookup'].includes(s.f) && segs[i + 1] && 'call' in segs[i + 1];
834
875
  const isHas = 'f' in s && ['has', 'contains', 'containsKey', 'has_key', 'key?', 'has_key?', 'include?'].includes(s.f);
@@ -1,3 +1,5 @@
1
1
  import type { X, LawOpts } from './laws.js';
2
2
  import { type NativeObservation } from './source-check.js';
3
- export declare function nativeLaw(expression: X, opts: LawOpts, parse: (text: string) => X, constants?: Record<string, number | string | boolean>, knownNames?: ReadonlySet<string>): (observation: NativeObservation) => boolean;
3
+ import type { NativeReading } from './native-observations.js';
4
+ import type { Name } from './extract.js';
5
+ export declare function nativeLaw(expression: X, opts: LawOpts, parse: (text: string) => X, constants?: Record<string, number | string | boolean>, knownNames?: ReadonlySet<string>, readings?: readonly NativeReading[], names?: readonly Name[]): (observation: NativeObservation) => boolean;
@@ -33,9 +33,76 @@ function businessDays(a, b, opts) {
33
33
  }
34
34
  return end >= start ? count : -count;
35
35
  }
36
- export function nativeLaw(expression, opts, parse, constants = {}, knownNames = new Set()) {
36
+ export function nativeLaw(expression, opts, parse, constants = {}, knownNames = new Set(), readings = [], names = []) {
37
37
  return observation => {
38
38
  const locals = new Map();
39
+ const scalarKey = (key) => { if (observation.nativeEquality === 'scalar' && object(key))
40
+ unsupported('foreign container equality or object keys'); };
41
+ const absent = (value) => value === NONE || value === null || value === undefined;
42
+ const same = (a, b) => {
43
+ // Nil presence does not compare container contents or identities.
44
+ if (!absent(a) && !absent(b)) {
45
+ scalarKey(a);
46
+ scalarKey(b);
47
+ }
48
+ return equal(a, b);
49
+ };
50
+ const at = (container, key) => { scalarKey(key); return get(container, key); };
51
+ const contains = (container, key) => { scalarKey(key); return has(container, key); };
52
+ const observedReading = (e, state) => {
53
+ // An observed external-call alias never changes lexical or reserved meaning.
54
+ // In particular Provider.result is not the method's result, and a forall
55
+ // binder named now/ttl is not an implicit clock/external call.
56
+ if (locals.has(e.head) || ['this', 'self', 'before', 'result', 'failed', 'method'].includes(e.head) || e.head.startsWith('@') || Object.hasOwn(constants, e.head) || e.head === observation.method && 'call' in (e.segs[0] ?? {}))
57
+ return undefined;
58
+ const fields = [e.head];
59
+ for (const segment of e.segs) {
60
+ if (!('f' in segment))
61
+ break;
62
+ fields.push(segment.f);
63
+ }
64
+ const ordinary = Object.hasOwn(observation.bindings, e.head) || object(state) && e.head in state || Object.hasOwn(observation.params, e.head);
65
+ const matches = readings.flatMap(reading => {
66
+ if (reading.method && reading.method !== observation.method)
67
+ return [];
68
+ const parts = reading.code.split('.');
69
+ let consumed;
70
+ if (parts.every((part, i) => fields[i] === part))
71
+ consumed = parts.length - 1;
72
+ else if (parts.at(-1) === e.head)
73
+ consumed = 0;
74
+ else
75
+ return [];
76
+ const next = e.segs[consumed], called = next && 'call' in next;
77
+ if (ordinary && !called || reading.kind === 'clock' && called)
78
+ return [];
79
+ if (called && next.args)
80
+ return unsupported('specific arguments on an observed one-value-per-step answer');
81
+ return [{ reading, consumed: consumed + (called ? 1 : 0) }];
82
+ }).sort((a, b) => b.consumed - a.consumed);
83
+ if (!matches.length)
84
+ return undefined;
85
+ const selected = matches[0];
86
+ if (matches.some(other => other.consumed === selected.consumed && (other.reading.key !== selected.reading.key || other.reading.kind !== selected.reading.kind)))
87
+ return unsupported(`ambiguous observed answer ${e.head}`);
88
+ const reading = selected.reading;
89
+ if (reading.kind === 'clock') {
90
+ if (reading.key !== 'now' || observation.observed?.clock === undefined)
91
+ return unsupported('unobserved native clock read');
92
+ return { value: observation.observed.clock, consumed: selected.consumed };
93
+ }
94
+ const expected = reading.kind === 'raises' ? `${reading.key}.raises` : reading.key;
95
+ if (reading.code !== expected)
96
+ return unsupported('native answer binding does not identify its original call');
97
+ const call = observation.observed?.calls[reading.key];
98
+ if (!call)
99
+ return unsupported(`unobserved native call ${reading.key}`);
100
+ if (reading.kind === 'raises')
101
+ return { value: call.kind === 'raised' ? call.raised : null, consumed: selected.consumed };
102
+ if (call.kind !== 'returned')
103
+ return unsupported(`native call ${reading.key} raised instead of returning`);
104
+ return { value: call.value, consumed: selected.consumed };
105
+ };
39
106
  const evaluate = (e, old = false) => {
40
107
  switch (e.k) {
41
108
  case 'num':
@@ -76,16 +143,61 @@ export function nativeLaw(expression, opts, parse, constants = {}, knownNames =
76
143
  }
77
144
  case 'path': {
78
145
  const state = old ? observation.before : observation.after;
79
- let value;
80
- if (['this', 'self'].includes(e.head))
146
+ // Match the symbolic resolver's reserved-name precedence from declarations.
147
+ const first = e.segs[0];
148
+ const resultFields = e.head === 'result' && first && 'f' in first ? names.filter(n => n.role === 'result' && n.code === `result.${first.f}`) : [];
149
+ const resultField = resultFields.find(n => n.method === observation.method) ?? (resultFields.length === 1 ? resultFields[0] : undefined);
150
+ if (resultFields.length > 1 && !resultField)
151
+ return unsupported('ambiguous native result field');
152
+ const shadow = (e.head === 'result' || e.head === 'failed') && names.some(n => n.code === e.head && n.role !== 'result' && n.role !== 'failed');
153
+ const reading = observedReading(e, state);
154
+ let value, consumed = 0;
155
+ if (reading)
156
+ value = reading.value;
157
+ else if (locals.has(e.head))
158
+ value = locals.get(e.head);
159
+ else if (['this', 'self'].includes(e.head))
81
160
  value = state;
82
161
  else if (e.head === 'before')
83
162
  value = observation.before;
84
163
  else if (e.head.startsWith('@') && object(state))
85
164
  value = state[e.head.slice(1)];
86
- else if (locals.has(e.head))
87
- value = locals.get(e.head);
88
- else if (Object.hasOwn(observation.bindings, e.head))
165
+ else if (resultField) {
166
+ if (old)
167
+ return unsupported('old(result), which is not native source state');
168
+ if (!object(observation.result) || !(first && 'f' in first) || !(first.f in observation.result))
169
+ return unsupported(`native value of ${resultField.code} is unavailable`);
170
+ value = observation.result;
171
+ }
172
+ else if (shadow) {
173
+ const fields = [e.head];
174
+ for (const seg of e.segs) {
175
+ if (!('f' in seg))
176
+ break;
177
+ fields.push(seg.f);
178
+ }
179
+ let selected;
180
+ for (let length = fields.length; length > 0 && !selected; length--) {
181
+ const code = fields.slice(0, length).join('.'), candidates = names.filter(n => n.code === code && n.role !== 'result' && n.role !== 'failed');
182
+ const inputs = candidates.filter(n => n.role === 'input');
183
+ selected = inputs.find(n => n.method === observation.method) ?? candidates.find(n => n.role === 'state') ?? (inputs.length && new Set(inputs.map(n => n.method)).size === 1 ? inputs[0] : undefined) ?? candidates.find(n => ['param', 'const', 'clock', 'answer'].includes(n.role));
184
+ }
185
+ if (!selected)
186
+ return unsupported(`native value of ${e.head} is unavailable`);
187
+ const parts = selected.code.split('.'), root = parts[0];
188
+ consumed = parts.length - 1;
189
+ const sources = selected.role === 'state' ? [state] : selected.role === 'param' ? [observation.params] : selected.role === 'input' ? [observation.bindings] : selected.role === 'const' ? [constants] : [observation.bindings];
190
+ const source = sources.find(s => object(s) && Object.hasOwn(s, root));
191
+ if (!object(source))
192
+ return unsupported(`native value of ${selected.code} is unavailable`);
193
+ value = source[root];
194
+ for (const part of parts.slice(1)) {
195
+ if (!object(value) || !(part in value))
196
+ return unsupported(`native value of ${selected.code} is unavailable`);
197
+ value = value[part];
198
+ }
199
+ }
200
+ else if (Object.hasOwn(observation.bindings, e.head) && (!names.length || (e.head !== 'result' && e.head !== 'failed')))
89
201
  value = observation.bindings[e.head];
90
202
  else if (e.head === 'result') {
91
203
  if (old)
@@ -112,25 +224,25 @@ export function nativeLaw(expression, opts, parse, constants = {}, knownNames =
112
224
  value = e.head; // A bare enum label; buildLaw already checked its domain.
113
225
  else
114
226
  return unsupported(`name ${e.head}`);
115
- for (let i = 0; i < e.segs.length; i++) {
227
+ for (let i = reading?.consumed ?? consumed; i < e.segs.length; i++) {
116
228
  const s = e.segs[i];
117
229
  if ('f' in s) {
118
230
  const next = e.segs[i + 1];
119
231
  if (next && 'call' in next && ((tag(value, 'Map') && ['get', 'has'].includes(s.f)) || (tag(value, 'Set') && s.f === 'has'))) {
120
232
  const key = next.args ? evaluate(parse(next.args), old) : undefined;
121
- value = s.f === 'get' ? get(value, key) : has(value, key);
233
+ value = s.f === 'get' ? at(value, key) : contains(value, key);
122
234
  i++;
123
235
  }
124
236
  else if (s.f === 'size' && (tag(value, 'Map') || tag(value, 'Set')))
125
237
  value = value.size;
126
238
  else
127
- value = get(value, s.f);
239
+ value = at(value, s.f);
128
240
  }
129
241
  else if ('i' in s)
130
- value = get(value, evaluate(s.i, old));
242
+ value = at(value, evaluate(s.i, old));
131
243
  else if (i === 0 && e.head === observation.method) {
132
244
  const expected = s.args ? s.args.split(',').map(a => evaluate(parse(a), old)) : [];
133
- if (expected.length && (expected.length !== observation.args.length || expected.some((v, k) => !equal(v, observation.args[k]))))
245
+ if (expected.length && (expected.length !== observation.args.length || expected.some((v, k) => !same(v, observation.args[k]))))
134
246
  return unsupported('a method call with different arguments');
135
247
  }
136
248
  else
@@ -149,8 +261,8 @@ export function nativeLaw(expression, opts, parse, constants = {}, knownNames =
149
261
  const calendar = e.a.k === 'bdur' || e.b.k === 'bdur';
150
262
  const a = calendar ? calendarOperand(e.a) : evaluate(e.a, old), b = calendar ? calendarOperand(e.b) : evaluate(e.b, old);
151
263
  switch (e.op) {
152
- case '==': return equal(a, b);
153
- case '!=': return !equal(a, b);
264
+ case '==': return same(a, b);
265
+ case '!=': return !same(a, b);
154
266
  case '<': return number(a) < number(b);
155
267
  case '<=': return number(a) <= number(b);
156
268
  case '>': return number(a) > number(b);
@@ -163,7 +275,7 @@ export function nativeLaw(expression, opts, parse, constants = {}, knownNames =
163
275
  case '%': return number(a) % number(b);
164
276
  case '&': return number(a) & number(b);
165
277
  case '|': return number(a) | number(b);
166
- case 'in': return has(b, a);
278
+ case 'in': return contains(b, a);
167
279
  default: return unsupported(`operator ${e.op}`);
168
280
  }
169
281
  }
@@ -0,0 +1,20 @@
1
+ export type NativeCallObservation = {
2
+ kind: 'returned';
3
+ value: unknown;
4
+ } | {
5
+ kind: 'raised';
6
+ raised: string;
7
+ };
8
+ export type NativeExecutionObservation = {
9
+ invocation: number;
10
+ calls: Record<string, NativeCallObservation>;
11
+ clock?: number;
12
+ };
13
+ export type NativeReading = {
14
+ code: string;
15
+ key: string;
16
+ kind: 'answer' | 'raises' | 'clock';
17
+ method?: string;
18
+ };
19
+ export declare function validateNativeObservations(value: unknown, allowedCalls: ReadonlySet<string>): NativeExecutionObservation;
20
+ export declare function nativeObservationSequence(allowedCalls: ReadonlySet<string>): (value: unknown) => NativeExecutionObservation;
@@ -0,0 +1,41 @@
1
+ const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) &&
2
+ (Object.getPrototypeOf(value) === null || Object.getPrototypeOf(value) === Object.prototype);
3
+ export function validateNativeObservations(value, allowedCalls) {
4
+ if (!record(value) || !Number.isSafeInteger(value.invocation) || value.invocation <= 0 || !record(value.calls))
5
+ throw new Error('native observation invocation/calls unavailable');
6
+ if (value.error !== undefined && value.error !== null)
7
+ throw new Error(`native observation unavailable: ${typeof value.error === 'string' ? value.error : 'invalid non-string error payload'}`);
8
+ if (value.clock !== undefined && (typeof value.clock !== 'number' || !Number.isSafeInteger(value.clock)))
9
+ throw new Error('native observed clock is outside the exact integer range');
10
+ for (const [key, call] of Object.entries(value.calls)) {
11
+ if (!allowedCalls.has(key))
12
+ throw new Error(`native observation of unbound call ${key}`);
13
+ if (!record(call))
14
+ throw new Error(`native observation of ${key} is not a record`);
15
+ if (call.kind === 'returned') {
16
+ if (!Object.hasOwn(call, 'value') || Object.hasOwn(call, 'raised'))
17
+ throw new Error(`ambiguous native return of ${key}`);
18
+ if (typeof call.value === 'number' && !Number.isSafeInteger(call.value))
19
+ throw new Error(`native return of ${key} is outside the exact integer range`);
20
+ }
21
+ else if (call.kind === 'raised') {
22
+ if (typeof call.raised !== 'string' || !call.raised || Object.hasOwn(call, 'value'))
23
+ throw new Error(`ambiguous native exception of ${key}`);
24
+ }
25
+ else
26
+ throw new Error(`native observation of ${key} has no outcome`);
27
+ }
28
+ return value;
29
+ }
30
+ // One reader per native harness. Repeated access to a current response is
31
+ // cached by its adapter; a later response must never reuse an old invocation.
32
+ export function nativeObservationSequence(allowedCalls) {
33
+ let previous = 0;
34
+ return value => {
35
+ const observed = validateNativeObservations(value, allowedCalls);
36
+ if (observed.invocation <= previous)
37
+ throw new Error('native execution observation is stale or repeated');
38
+ previous = observed.invocation;
39
+ return observed;
40
+ };
41
+ }