gdp-wired 0.50.2 → 0.50.4

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 (69) hide show
  1. package/README.md +8 -2
  2. package/dist/core/agent-consult/cli.d.ts +2 -0
  3. package/dist/core/agent-consult/cli.js +19 -0
  4. package/dist/core/agent-consult/protocol.d.ts +93 -0
  5. package/dist/core/agent-consult/protocol.js +154 -0
  6. package/dist/core/agent-consult/service.d.ts +435 -0
  7. package/dist/core/agent-consult/service.js +84 -0
  8. package/dist/core/agent-consult/session.d.ts +13 -0
  9. package/dist/core/agent-consult/session.js +163 -0
  10. package/dist/core/agent-consult/source-service.d.ts +83 -0
  11. package/dist/core/agent-consult/source-service.js +51 -0
  12. package/dist/core/agent-consult/tsconfig.json +5 -0
  13. package/dist/core/agent-consult/worker.d.ts +1 -0
  14. package/dist/core/agent-consult/worker.js +17 -0
  15. package/dist/core/agent-consult/workspace.d.ts +27 -0
  16. package/dist/core/agent-consult/workspace.js +66 -0
  17. package/dist/core/agent-consult.d.ts +8 -0
  18. package/dist/core/agent-consult.js +6 -0
  19. package/dist/core/cli.d.ts +17 -1
  20. package/dist/core/cli.js +174 -68
  21. package/dist/core/discover.d.ts +6 -1
  22. package/dist/core/discover.js +54 -7
  23. package/dist/core/dsl-deadline.d.ts +3 -0
  24. package/dist/core/dsl-deadline.js +26 -2
  25. package/dist/core/dsl.d.ts +3 -1
  26. package/dist/core/dsl.js +93 -30
  27. package/dist/core/effect.d.ts +12 -0
  28. package/dist/core/effect.js +26 -9
  29. package/dist/core/ex/harness.exs +171 -5
  30. package/dist/core/extract-c.js +63 -6
  31. package/dist/core/extract-check.d.ts +5 -1
  32. package/dist/core/extract-check.js +28 -10
  33. package/dist/core/extract-go-check.js +127 -1
  34. package/dist/core/extract-go.js +8 -2
  35. package/dist/core/extract-jvm.js +2 -2
  36. package/dist/core/extract-rs.js +51 -5
  37. package/dist/core/extract-step.js +40 -6
  38. package/dist/core/extract-swift.js +47 -3
  39. package/dist/core/extract.d.ts +8 -0
  40. package/dist/core/infer.d.ts +8 -0
  41. package/dist/core/infer.js +133 -16
  42. package/dist/core/jvm/Harness.java +135 -3
  43. package/dist/core/jvm/Rt.java +66 -4
  44. package/dist/core/laws.js +51 -10
  45. package/dist/core/native-law.d.ts +3 -1
  46. package/dist/core/native-law.js +126 -14
  47. package/dist/core/native-observations.d.ts +20 -0
  48. package/dist/core/native-observations.js +41 -0
  49. package/dist/core/native-wire.d.ts +1 -0
  50. package/dist/core/native-wire.js +16 -2
  51. package/dist/core/py/harness.py +21 -4
  52. package/dist/core/rb/harness.rb +178 -9
  53. package/dist/core/search-termination.d.ts +35 -0
  54. package/dist/core/search-termination.js +13 -0
  55. package/dist/core/search-watchdog.d.ts +8 -0
  56. package/dist/core/search-watchdog.js +34 -0
  57. package/dist/core/source-check.d.ts +3 -0
  58. package/dist/core/swift/Harness.swift +65 -4
  59. package/dist/core/swift/Main.swift +27 -4
  60. package/dist/core/wall.d.ts +3 -1
  61. package/dist/core/wall.js +7 -4
  62. package/dist/core/work-refusal.d.ts +3 -0
  63. package/dist/core/work-refusal.js +8 -0
  64. package/dist/kernel/prove.d.ts +2 -0
  65. package/dist/kernel/prove.js +13 -5
  66. package/docs/agent-consult-workspace-check.md +118 -0
  67. package/docs/agent-consult.md +151 -0
  68. package/examples/agent-consult.json +22 -0
  69. package/package.json +11 -3
@@ -8,15 +8,175 @@
8
8
  Code.require_file("json.exs", __DIR__)
9
9
  import Bitwise
10
10
 
11
+ # Immutable BEAM values have structural equality, not JS identity. Fresh wire IDs
12
+ # never unify equal maps. Container equality must be refused by native-law;
13
+ # this transport supports scalar/property laws only (nativeEquality: scalar).
14
+ defmodule GdpNative do
15
+ @table :gdp_native_observations
16
+ def init, do: :ets.new(@table, [:named_table, :public, :set])
17
+ def begin_call(mod, fun) do
18
+ :ets.delete_all_objects(@table)
19
+ invocation = Process.get(:gdp_native_invocation, 0) + 1
20
+ if invocation > 9007199254740991, do: raise(ArgumentError, "native invocation exceeds exact integer range")
21
+ Process.put(:gdp_native_invocation, invocation)
22
+ :ets.insert(@table, [{:target, {mod, fun, invocation}}, {:invocation, invocation}])
23
+ end
24
+ defp error(message) do
25
+ if active?(), do: :ets.insert_new(@table, {{:error, Process.get(:gdp_native_active)}, message})
26
+ end
27
+ def capture(mod, fun, bindings, names) do
28
+ invocation = case :ets.lookup(@table, :target) do [{:target, {^mod, ^fun, id}}] -> id; _ -> nil end
29
+ if is_integer(invocation) and :ets.insert_new(@table, {{:entered, invocation}, true}) do
30
+ result = try do
31
+ actual = Map.take(Map.new(bindings), names) |> Map.new(fn {k, v} -> {Atom.to_string(k), v} end)
32
+ %{"snapshot" => snapshot(actual, :object)}
33
+ rescue e -> %{"error" => Exception.message(e)} end
34
+ :ets.insert(@table, {{:bindings, invocation}, result})
35
+ previous = Process.get(:gdp_native_active)
36
+ Process.put(:gdp_native_active, invocation)
37
+ {invocation, previous}
38
+ end
39
+ end
40
+ def leave(nil), do: :ok
41
+ def leave({invocation, previous}) do
42
+ if Process.get(:gdp_native_active) == invocation do
43
+ if is_nil(previous), do: Process.delete(:gdp_native_active), else: Process.put(:gdp_native_active, previous)
44
+ end
45
+ :ok
46
+ end
47
+ defp active? do
48
+ invocation = Process.get(:gdp_native_active)
49
+ is_integer(invocation) and :ets.lookup(@table, :invocation) == [{:invocation, invocation}] and :ets.member(@table, :target)
50
+ end
51
+ # Instrument the original function head, not the reader's argument labels.
52
+ # The first instruction runs after pattern matching, guards and defaults.
53
+ def instrument(ast) do
54
+ Macro.prewalk(ast, fn
55
+ {kind, meta, [head, body]} = node when kind in [:def, :defp] and is_list(body) ->
56
+ plain = case head do {:when, _, [h | _]} -> h; h -> h end
57
+ case plain do
58
+ {name, _, args} when is_list(args) ->
59
+ request = if name in [:handle_call, :handle_cast], do: Enum.take(args, 1), else: Enum.drop(args, 1)
60
+ names = Enum.flat_map(request, &parameter_names/1) |> Enum.uniq()
61
+ body = Keyword.update!(body, :do, fn original ->
62
+ quote do
63
+ native_entry = GdpNative.capture(__MODULE__, unquote(name), binding(), unquote(names))
64
+ try do
65
+ unquote(original)
66
+ after
67
+ GdpNative.leave(native_entry)
68
+ end
69
+ end
70
+ end)
71
+ {kind, meta, [head, body]}
72
+ _ -> node
73
+ end
74
+ node -> node
75
+ end)
76
+ end
77
+ defp parameter_names({:\\, _, [pattern, _default]}), do: parameter_names(pattern)
78
+ defp parameter_names(pattern) do
79
+ {_, names} = Macro.prewalk(pattern, [], fn
80
+ {name, _, context} = node, acc when is_atom(name) and (is_atom(context) or is_nil(context)) ->
81
+ {node, if(String.starts_with?(Atom.to_string(name), "_"), do: acc, else: [name | acc])}
82
+ node, acc -> {node, acc}
83
+ end)
84
+ names
85
+ end
86
+ defp scalar(value) when is_nil(value) or is_boolean(value), do: value
87
+ defp scalar(value) when is_atom(value), do: Atom.to_string(value)
88
+ defp scalar(value) when is_binary(value) do
89
+ if not String.valid?(value) or Regex.match?(~r/[\x00-\x08\x0b\x0c\x0e-\x1f]/, value), do: raise(ArgumentError, "unsupported native binary")
90
+ value
91
+ end
92
+ defp scalar(value) when is_integer(value) and abs(value) <= 9007199254740991, do: value
93
+ defp scalar(value) when is_float(value) and abs(value) <= 9007199254740991 and trunc(value) == value, do: trunc(value)
94
+ defp scalar(_), do: raise(ArgumentError, "unsupported native scalar observation")
95
+ def snapshot(value, root_kind \\ :value) do
96
+ {root, _} = encode(value, root_kind, 0)
97
+ %{"version" => 1, "root" => root}
98
+ end
99
+ defp encode(_, _, count) when count >= 10000, do: raise(ArgumentError, "native snapshot exceeds node bound")
100
+ defp encode(value, kind, count) when is_map(value) do
101
+ if Map.get(value, :__struct__) in [Date, Time, DateTime, NaiveDateTime, MapSet, Range, Regex], do: raise(ArgumentError, "unsupported native snapshot struct")
102
+ fields = if is_struct(value), do: Map.from_struct(value), else: value
103
+ object = kind in [:object, :records] or is_struct(value)
104
+ {items, count} = Enum.map_reduce(fields, count + 1, fn {k, v}, n ->
105
+ key = if object and is_atom(k), do: Atom.to_string(k), else: k
106
+ if not (is_binary(key) or (not object and is_integer(key))), do: raise(ArgumentError, "unsupported native map key")
107
+ {key, n} = encode(key, :value, n)
108
+ {v, n} = encode(v, if(kind == :records, do: :records, else: :value), n)
109
+ {[key, v], n}
110
+ end)
111
+ {%{"id" => Integer.to_string(:erlang.unique_integer([:positive, :monotonic])), "kind" => if(object, do: "object", else: "map"), "items" => items}, count}
112
+ end
113
+ defp encode(value, _, count) when is_list(value) do
114
+ {items, count} = Enum.map_reduce(value, count + 1, &encode(&1, :value, &2))
115
+ {%{"id" => Integer.to_string(:erlang.unique_integer([:positive, :monotonic])), "kind" => "array", "items" => items}, count}
116
+ end
117
+ defp encode(value, _, count), do: {scalar(value), count + 1}
118
+ defp record(key, outcome) do
119
+ if active?() do
120
+ slot = {:call, Process.get(:gdp_native_active), key}
121
+ inserted = :ets.insert_new(@table, {slot, outcome})
122
+ if not inserted and :ets.lookup(@table, slot) != [{slot, outcome}], do: error("inconsistent native call #{key}")
123
+ end
124
+ :ok
125
+ end
126
+ def answered(key, call) do
127
+ try do
128
+ value = call.()
129
+ if active?() do
130
+ try do record(key, %{"kind" => "returned", "value" => scalar(value)}) rescue e -> error(Exception.message(e)) end
131
+ end
132
+ value
133
+ rescue e ->
134
+ if active?(), do: record(key, %{"kind" => "raised", "raised" => inspect(e.__struct__)})
135
+ reraise e, __STACKTRACE__
136
+ catch kind, reason ->
137
+ error("unsupported native call outcome #{kind}")
138
+ :erlang.raise(kind, reason, __STACKTRACE__)
139
+ end
140
+ end
141
+ def clock(value) do
142
+ if active?() do
143
+ try do
144
+ actual = scalar(value)
145
+ slot = {:clock, Process.get(:gdp_native_active)}
146
+ if not :ets.insert_new(@table, {slot, actual}) and :ets.lookup(@table, slot) != [{slot, actual}], do: error("inconsistent native clock reads")
147
+ rescue e -> error(Exception.message(e)) end
148
+ end
149
+ :ok
150
+ end
151
+ def finish_call do
152
+ [{:invocation, invocation}] = :ets.lookup(@table, :invocation)
153
+ bindings = case :ets.lookup(@table, {:bindings, invocation}) do [{_, b}] -> b; _ -> %{"error" => "native function entry was not observed"} end
154
+ observed = case :ets.lookup(@table, {:error, invocation}) do
155
+ [{_, message}] -> %{"error" => message}
156
+ [] ->
157
+ calls = Map.new(for {{:call, ^invocation, key}, outcome} <- :ets.tab2list(@table), do: {key, outcome})
158
+ base = %{"invocation" => invocation, "calls" => calls}
159
+ frame = case :ets.lookup(@table, {:clock, invocation}) do [{_, clock}] -> Map.put(base, "clock", clock); [] -> base end
160
+ %{"snapshot" => snapshot(frame, :records)}
161
+ end
162
+ :ets.delete(@table, :target)
163
+ %{"nativeBindings" => bindings, "nativeObservations" => observed}
164
+ end
165
+ end
166
+
11
167
  defmodule GdpClock do
12
- def now, do: :persistent_term.get(:gdp_now, 0)
168
+ def now do
169
+ value = :persistent_term.get(:gdp_now, 0)
170
+ GdpNative.clock(value)
171
+ value
172
+ end
13
173
  def int(_ \\ nil), do: now()
14
174
  def utc_now(_ \\ nil), do: DateTime.from_unix!(now())
15
175
  end
16
176
 
17
177
  # An answered call's value: the request's input for it, None (nil) where it says so; every process reads it.
18
178
  defmodule GdpAnswer do
19
- def a(key), do: (case Map.get(:persistent_term.get(:gdp_ans, %{}), key) do nil -> nil; %{"none" => true} -> nil; spec -> GdpHarness.arg(spec) end)
179
+ def a(key), do: GdpNative.answered(key, fn -> case Map.get(:persistent_term.get(:gdp_ans, %{}), key) do nil -> nil; %{"none" => true} -> nil; spec -> GdpHarness.arg(spec) end end)
20
180
  end
21
181
 
22
182
  defmodule GdpHarness do
@@ -37,9 +197,10 @@ defmodule GdpHarness do
37
197
  end
38
198
  x -> x
39
199
  end)
40
- Code.compile_quoted(ast, req["path"])
200
+ GdpNative.init()
201
+ Code.compile_quoted(GdpNative.instrument(ast), req["path"])
41
202
  Process.put(:s, req |> Map.put("mod", Module.concat([req["module"]])))
42
- %{"ok" => true}
203
+ %{"ok" => true, "nativeSnapshot" => 1, "nativeBindings" => 1, "nativeObservations" => 1, "nativeEquality" => "scalar"}
43
204
  end
44
205
  def s(k), do: Process.get(:s)[k]
45
206
  def leaf_t(l), do: (case l["t"] do %{"k" => "opt", "of" => o} -> o; t -> t || %{} end)
@@ -163,12 +324,17 @@ lines |> Enum.each(fn line ->
163
324
  "at" ->
164
325
  (try do o = GdpHarness.make(req["a"]) |> GdpHarness.set(req["state"]); i = :ets.info(objs, :size) + 1; :ets.insert(objs, {i, o}); %{"id" => i} rescue e -> %{"bad" => Exception.message(e)} catch :exit, r -> %{"bad" => inspect(r)} end)
165
326
  "get" -> [{_, o}] = :ets.lookup(objs, req["id"]); %{"state" => GdpHarness.state_of(GdpHarness.get(o))}
327
+ "native" -> [{_, o}] = :ets.lookup(objs, req["id"]); %{"snapshot" => GdpNative.snapshot(GdpHarness.get(o), :object)}
166
328
  "call" ->
167
329
  :persistent_term.put(:gdp_ans, req["answers"] || %{})
168
330
  [{_, o}] = :ets.lookup(objs, req["id"])
331
+ msg = GdpHarness.s("msgs")[req["m"]]
332
+ fun = case msg["kind"] do "handle_call" -> :handle_call; "handle_cast" -> :handle_cast; _ -> String.to_atom(msg["fun"]) end
333
+ GdpNative.begin_call(GdpHarness.s("mod"), fun)
169
334
  {o2, r} = GdpHarness.call(o, req["m"], req["a"])
170
335
  :ets.insert(objs, {req["id"], o2})
171
- case r do {:err, e} -> %{"out" => nil, "err" => e}; v -> %{"out" => GdpHarness.tag(v)} end
336
+ result = case r do {:err, e} -> %{"out" => nil, "err" => e}; v -> %{"out" => GdpHarness.tag(v)} end
337
+ Map.merge(result, GdpNative.finish_call())
172
338
  "coverage" -> %{"hit" => []}
173
339
  op -> %{"error" => "no op #{op}"}
174
340
  end
@@ -238,6 +238,32 @@ export function harnessC(file, c, read, opts, cpp) {
238
238
  set.push(`if ((v = gdp_key(st, ${k}))) { if (!strncmp(v, "true", 4)) ${a} = ${T(l.t).nullflag ? '(void *)1' : '1'}; else if (!strncmp(v, "false", 5)) ${a} = 0; else return "${l.name}: not a boolean"; }`);
239
239
  }
240
240
  }
241
+ const nativeTree = { children: new Map() };
242
+ for (const leaf of read.leaves)
243
+ if (['int', 'bool', 'list'].includes(leaf.kind)) {
244
+ let node = nativeTree;
245
+ for (const f of leaf.path) {
246
+ if (!node.children.has(f))
247
+ node.children.set(f, { children: new Map() });
248
+ node = node.children.get(f);
249
+ }
250
+ node.leaf = leaf;
251
+ }
252
+ const emit = (s) => `gdp_putf("%s", ${q(s)});`;
253
+ const nativeInt = (a, t) => T(t).signed === false ? `gdp_putf("%llu", (unsigned long long)(${a}));` : `gdp_putf("%lld", (long long)(${a}));`;
254
+ const nativeNode = (node, path) => {
255
+ const a = path.length ? acc(path) : '(*o)', l = node.leaf;
256
+ if (l?.kind === 'int')
257
+ return nativeInt(a, l.t);
258
+ if (l?.kind === 'bool')
259
+ return T(l.t).nullflag ? `if (${a}) gdp_native_bad = "unsupported native pointer field"; gdp_putf("null");` : `gdp_putf("%s", ${a} ? "true" : "false");`;
260
+ if (l?.kind === 'list') {
261
+ const t = T(l.t), et = T(t.elem);
262
+ return `${emit('{"kind":"array","id":"')} gdp_putf("%llu", gdp_native_id((const void *)&${a}, ${q(`array:${path.join('.')}`)})); ${emit('","items":[')} for (int ni = 0; ni < ${t.len}; ni++) { if (ni) gdp_putf(","); ${et.k === 'int' ? nativeInt(`${a}[ni]`, t.elem) : `gdp_putf("%s", ${a}[ni] ? "true" : "false");`} } ${emit(']}')}`;
263
+ }
264
+ return `${emit('{"kind":"object","id":"')} gdp_putf("%llu", gdp_native_id((const void *)&${a}, ${q(`object:${path.join('.')}`)})); ${emit('","items":[')} ${[...node.children].map(([f, child], i) => `${emit(`${i ? ',' : ''}[${q(f)},`)} ${nativeNode(child, [...path, f])} ${emit(']')}`).join(' ')} ${emit(']}')}`;
265
+ };
266
+ const nativeState = nativeNode(nativeTree, []);
241
267
  const frames = read.leaves.filter(l => l.kind === 'frame' && !T(l.t).mutex);
242
268
  // (a field left out that points to an object other code owns, a buffer: a zeroed one of its own, as the code's setup
243
269
  // would give)
@@ -277,6 +303,16 @@ export function harnessC(file, c, read, opts, cpp) {
277
303
  else
278
304
  lines.push(`return "an argument the harness can't make";`);
279
305
  });
306
+ const nativeArgs = meth.params.map((pa, i) => {
307
+ const t = T(pa.t), a = `a${i}`;
308
+ const scalar = (v, ty) => T(ty).k === 'int' ? nativeInt(v, ty) : T(ty).k === 'bool' ? `gdp_putf("%s", ${v} ? "true" : "false");` : 'gdp_native_bad = "unsupported native parameter type"; gdp_putf("null");';
309
+ const body = pa.arg.k === 'input' ? scalar(a, pa.t) : pa.arg.k === 'rec'
310
+ ? `${emit('{"kind":"object","id":"')} gdp_putf("%llu", ++gdp_native_next); ${emit('","items":[')} ${(t.k === 'ptr' && T(t.elem).box ? [['value', T(t.elem).fields[0].t, a]] : pa.arg.fields.map(([f]) => { const st = t.k === 'ptr' ? T(t.elem) : t; return [f, st.fields.find(g => g.name === f).t, `${a}.${f}`]; })).map(([f, ft, v], j) => `${emit(`${j ? ',' : ''}[${q(f)},`)} ${scalar(v, ft)} ${emit(']')}`).join(' ')} ${emit(']}')}`
311
+ : 'gdp_native_bad = "unsupported native parameter shape"; gdp_putf("null");';
312
+ return `${emit(`${i ? ',' : ''}[${q(pa.name)},`)} ${body} ${emit(']')}`;
313
+ }).join(' ');
314
+ // These are the converted native locals BEFORE invocation/reassignment.
315
+ const bindings = `${emit(',"nativeBindings":{"snapshot":{"version":1,"root":{"kind":"object","id":"')} gdp_putf("%llu", ++gdp_native_next); ${emit('","items":[')} ${nativeArgs} ${emit(']}}')} if (gdp_native_bad) { ${emit(',"error":"')} gdp_putf("%s", gdp_native_bad); ${emit('"')} } ${emit('}')}`;
280
316
  const rt = meth.results[0], fails = opts.fails?.[meth.name]?.trim();
281
317
  const callee = G ? `${meth.name}(${args.slice(1).join(', ')})` : cpp ? `o->${meth.name}(${args.slice(1).join(', ')})` : `${meth.name}(${args.join(', ')})`;
282
318
  const invoke = rt === undefined ? `${callee};` : `${cpp ? 'auto' : T(rt).go} r0 = ${callee}; gdp_has = 1; ${T(rt).k === 'int' ? `gdp_outv = ${T(rt).signed === false ? '(long long)' : ''}r0; gdp_outu = ${T(rt).signed === false ? 1 : 0};` : 'gdp_outb = r0; gdp_isb = 1;'}`;
@@ -284,7 +320,7 @@ export function harnessC(file, c, read, opts, cpp) {
284
320
  // (with out-parameters, the result is a record: the value returned and what each holds)
285
321
  const rec = outs.length ? `gdp_rec = 1; gdp_putf(",\\"out\\":{"); ${[...(rt !== undefined ? [['result', 'r0', rt]] : []), ...outs].map(([n, v, et], j) => `gdp_putf("${j ? ',' : ''}\\"${n}\\":"); ${T(et).k === 'int' ? `gdp_putf(${T(et).signed === false ? '"%llu", (unsigned long long)' : '"%lld", (long long)'}(${v}))` : `gdp_putf("%s", ${v} ? "true" : "false")`};`).join(' ')} gdp_putf("},\\"hasOut\\":true");` : '';
286
322
  const load = G ? `gdp_load(o); ${given.map(([n, a]) => `memcpy((void *)&${n}, (const void *)&${a}, sizeof ${n});`).join(' ')}\n ` : '';
287
- return `if (!strcmp(m, ${q(meth.name)})) {\n ${lines.join('\n ')}\n memcpy(gdp_pre, (void *)o, sizeof(gdp_T));\n ${load}int sg = sigsetjmp(gdp_jb, 1);\n if (!sg) { gdp_armed = 1; gdp_watch(1); ${cpp ? 'try { ' : ''}${invoke} ${failed} gdp_watch(0); gdp_armed = 0; ${rec}${cpp ? ' } catch (...) { gdp_watch(0); gdp_armed = 0; gdp_sig = SIGUSR2; }' : ''} } else { gdp_watch(0); gdp_sig = sg; }\n ${G ? 'gdp_store(o);\n ' : ''}return gdp_after(o);\n }`;
323
+ return `if (!strcmp(m, ${q(meth.name)})) {\n ${lines.join('\n ')}\n ${bindings}\n memcpy(gdp_pre, (void *)o, sizeof(gdp_T));\n ${load}int sg = sigsetjmp(gdp_jb, 1);\n if (!sg) { gdp_armed = 1; gdp_watch(1); ${cpp ? 'try { ' : ''}${invoke} ${failed} gdp_watch(0); gdp_armed = 0; ${rec}${cpp ? ' } catch (...) { gdp_watch(0); gdp_armed = 0; gdp_sig = SIGUSR2; }' : ''} } else { gdp_watch(0); gdp_sig = sg; }\n ${G ? 'gdp_store(o);\n ' : ''}return gdp_after(o);\n }`;
288
324
  });
289
325
  const frameLines = frames.map(l => { const e = acc(l.path); return `if (memcmp((char *)&${e}, (char *)gdp_pre + ((char *)&${e} - (char *)o), sizeof ${e})) return ${q(l.path.join('.'))};`; });
290
326
  // The object, made as the code makes it: C's zeroed; C++'s constructed (in zeroed memory) with the rule's parameters.
@@ -329,9 +365,22 @@ static unsigned char gdp_pre[sizeof(gdp_T)];
329
365
  ${robs.length ? `template <typename Tag, auto M> struct gdp_rob { friend auto gdp_ptr(Tag) { return M; } };\n${robs.map((k, i) => `struct gdp_tag${i} { friend auto gdp_ptr(gdp_tag${i}); };\ntemplate struct gdp_rob<gdp_tag${i}, ${k}>;`).join('\n')}` : ''}
330
366
  static char *gdp_buf; static size_t gdp_n, gdp_cap;
331
367
  static void gdp_putf(const char *f, ...) {
332
- va_list ap; va_start(ap, f); char tmp[512]; int k = vsnprintf(tmp, sizeof tmp, f, ap); va_end(ap);
333
- if (gdp_n + k + 1 > gdp_cap) { gdp_cap = (gdp_n + k + 1) * 2; gdp_buf = (char *)realloc(gdp_buf, gdp_cap); }
334
- memcpy(gdp_buf + gdp_n, tmp, k + 1); gdp_n += k;
368
+ va_list ap, copy; va_start(ap, f); va_copy(copy, ap); int k = vsnprintf(0, 0, f, copy); va_end(copy);
369
+ if (k < 0 || gdp_n > (size_t)-1 - (size_t)k - 1) abort();
370
+ size_t need = gdp_n + (size_t)k + 1;
371
+ if (need > gdp_cap) { gdp_cap = need <= (size_t)-1 / 2 ? need * 2 : need; char *next = (char *)realloc(gdp_buf, gdp_cap); if (!next) abort(); gdp_buf = next; }
372
+ vsnprintf(gdp_buf + gdp_n, gdp_cap - gdp_n, f, ap); va_end(ap); gdp_n += (size_t)k;
373
+ }
374
+ // Stable identities for original native storage and typed field views.
375
+ static unsigned long long gdp_native_next;
376
+ static const char *gdp_native_bad;
377
+ struct gdp_native_ident { const void *address; const char *view; unsigned long long id; };
378
+ static struct gdp_native_ident *gdp_native_ids; static size_t gdp_native_count;
379
+ static unsigned long long gdp_native_id(const void *address, const char *view) {
380
+ for (size_t i = 0; i < gdp_native_count; i++) if (gdp_native_ids[i].address == address && !strcmp(gdp_native_ids[i].view, view)) return gdp_native_ids[i].id;
381
+ if (gdp_native_count >= 100000) { gdp_native_bad = "native identity bound exceeded"; return 1; }
382
+ gdp_native_ids = (struct gdp_native_ident *)realloc(gdp_native_ids, (gdp_native_count + 1) * sizeof *gdp_native_ids);
383
+ struct gdp_native_ident *entry = &gdp_native_ids[gdp_native_count++]; entry->address = address; entry->view = view; entry->id = ++gdp_native_next; return entry->id;
335
384
  }
336
385
  static const char *gdp_ws(const char *p) { while (*p == ' ' || *p == '\\t' || *p == '\\n' || *p == '\\r') p++; return p; }
337
386
  static const char *gdp_skip(const char *p) {
@@ -372,6 +421,12 @@ static void gdp_get(gdp_T *o) {
372
421
  ${get.join('\n ')}
373
422
  gdp_putf("}");
374
423
  }
424
+ static void gdp_native(gdp_T *o) {
425
+ gdp_native_bad = 0;
426
+ ${emit('{"snapshot":{"version":1,"root":')} ${nativeState} ${emit('}')}
427
+ if (gdp_native_bad) { ${emit(',"error":"')} gdp_putf("%s", gdp_native_bad); ${emit('"')} }
428
+ ${emit('}')}
429
+ }
375
430
  static const char *gdp_set(gdp_T *o, const char *st) {
376
431
  const char *v; (void)v; (void)o; (void)st;
377
432
  ${set.join('\n ')}
@@ -403,7 +458,7 @@ static const char *gdp_after(gdp_T *o) {
403
458
  ${make}
404
459
  static const char *gdp_call(gdp_T *o, const char *m, const char *a) {
405
460
  const char *v; (void)v; (void)a;
406
- gdp_sig = gdp_err = gdp_has = gdp_outu = gdp_isb = gdp_rec = 0; gdp_outv = 0;
461
+ gdp_sig = gdp_err = gdp_has = gdp_outu = gdp_isb = gdp_rec = 0; gdp_outv = 0; gdp_native_bad = 0;
407
462
  ${calls.join('\n ')}
408
463
  return "no such function";
409
464
  }
@@ -425,7 +480,9 @@ int main(int argc, char **argv) {
425
480
  const char *op = gdp_key(line, "op"), *id = gdp_key(line, "id");
426
481
  long long k = 0; unsigned long long ku; if (id) gdp_int(id, 64, 1, &k, &ku);
427
482
  gdp_n = 0;
428
- if (op && !strncmp(op, "\\"new\\"", 5)) { const char *bad = 0; gdp_T *o = gdp_make(line, &bad); if (!o) gdp_putf("{\\"bad\\":\\"%s\\"}", bad); else { objs = (gdp_T **)realloc(objs, ++nobj * sizeof *objs); objs[nobj - 1] = o; gdp_putf("{\\"id\\":%zu}", nobj); } }
483
+ if (op && !strncmp(op + 1, "hello", 5) && op[6] == '"') { ${emit('{"nativeSnapshot":1,"nativeBindings":1,"nativeEquality":"scalar"}')} }
484
+ else if (op && !strncmp(op + 1, "native", 6) && op[7] == '"') { gdp_native(objs[k - 1]); }
485
+ else if (op && !strncmp(op, "\\"new\\"", 5)) { const char *bad = 0; gdp_T *o = gdp_make(line, &bad); if (!o) gdp_putf("{\\"bad\\":\\"%s\\"}", bad); else { objs = (gdp_T **)realloc(objs, ++nobj * sizeof *objs); objs[nobj - 1] = o; gdp_putf("{\\"id\\":%zu}", nobj); } }
429
486
  else if (op && !strncmp(op, "\\"at\\"", 4)) {
430
487
  const char *bad = 0; gdp_T *o = gdp_make(line, &bad); const char *st = gdp_key(line, "state");
431
488
  if (o) bad = st ? gdp_set(o, st) : "no state";
@@ -6,6 +6,7 @@ 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
8
  import { type NativeInputs } from './native-domain.js';
9
+ import { type NativeExecutionObservation } from './native-observations.js';
9
10
  type Raw = number | boolean | string;
10
11
  export type Arm = {
11
12
  label: string;
@@ -49,7 +50,7 @@ export declare function instrument(code: string, file: string, tail?: string, ex
49
50
  export type Sandbox = {
50
51
  ctx: Context;
51
52
  counts: number[];
52
- call: (f: string, self: unknown, args: unknown[]) => {
53
+ call: (f: string, self: unknown, args: unknown[], housekeeping?: boolean) => {
53
54
  ok: true;
54
55
  value: unknown;
55
56
  } | {
@@ -59,6 +60,7 @@ export type Sandbox = {
59
60
  setNow: (n: number) => void;
60
61
  get: (name: string) => unknown;
61
62
  bindings: (method: string) => Record<string, unknown> | undefined;
63
+ observations: () => NativeExecutionObservation;
62
64
  };
63
65
  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 & {
64
66
  arms: Arm[];
@@ -125,6 +127,8 @@ export type CodeSide = {
125
127
  coverage: () => Coverage;
126
128
  nativeState?: (self: unknown, snap: Snap, params: Record<string, Raw>) => unknown;
127
129
  nativeBindings?: (event: Ev) => Record<string, unknown> | undefined;
130
+ nativeObservations?: (event: Ev) => NativeExecutionObservation | undefined;
131
+ nativeEquality?: 'scalar';
128
132
  nativeInputs?: NativeInputs;
129
133
  input?: (v: Var, x: Raw, rand: Rand) => Raw;
130
134
  drawSnap?: (rand: Rand) => Snap;
@@ -24,6 +24,7 @@ import { normalize, resolveIn, sameLazyRoot, scriptKind } from "./extract-read.j
24
24
  import * as I from "./extract-ir.js";
25
25
  import { nativeSnapshot, rememberNative } from "./source-check.js";
26
26
  import { nativeCaptureEdits, nativeInputs } from "./native-domain.js";
27
+ import { validateNativeObservations } from "./native-observations.js";
27
28
  // The check's own failure, not the code's: a request past its time, the harness's transport (anvil's JSON-RPC) failing,
28
29
  // the harness gone. Never a difference and never a pass: the whole check runs once more, from a fresh harness, and a
29
30
  // second failure is the check's outcome (Evidence.harness).
@@ -98,7 +99,7 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}, extr
98
99
  const { js, arms } = instrument(code, file, init ? `\n;(globalThis as any).__gdpInit = () => (${init});\n` : '', [...nativeCaptureEdits(code, file, nativeMethods), ...extra]);
99
100
  const captured = new Map(), captureErrors = new Map();
100
101
  const counts = arms.map(() => 0);
101
- let now = 0;
102
+ let now = 0, invocation = 0, observedClock, observing = false;
102
103
  const stub = (name) => new Proxy({}, {
103
104
  get: (_, k) => { if (k === '__esModule' || typeof k === 'symbol')
104
105
  return undefined; throw new Error(`the check loads no module ${name} (its ${String(k)} was read)`); },
@@ -106,7 +107,8 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}, extr
106
107
  });
107
108
  const module = { exports: {} };
108
109
  const ctx = vm.createContext({
109
- __cov: (i) => { counts[i]++; }, __now: () => now, module, exports: module.exports,
110
+ __cov: (i) => { counts[i]++; }, __now: () => { if (observing)
111
+ observedClock = now; return now; }, module, exports: module.exports,
110
112
  __gdp_native_capture: (name, value) => {
111
113
  if (captured.has(name) || captureErrors.has(name))
112
114
  return;
@@ -156,12 +158,16 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}, extr
156
158
  vm.runInContext(`${js}\n;globalThis.__gdp = {${expose.map(n => { if (n === 'default')
157
159
  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 });
158
160
  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)} } })()');
159
- const call = (f, self, args) => {
161
+ const call = (f, self, args, housekeeping = false) => {
160
162
  // Reading/restoring a factory's closure is harness work, not a new request.
161
- if (f !== '$get' && f !== '$at') {
163
+ const request = !housekeeping;
164
+ if (request) {
162
165
  captured.clear();
163
166
  captureErrors.clear();
167
+ invocation++;
168
+ observedClock = undefined;
164
169
  }
170
+ observing = request;
165
171
  Object.assign(ctx, { __f: f, __self: self, __args: args });
166
172
  try {
167
173
  script.runInContext(ctx, { timeout: 1000 });
@@ -171,9 +177,12 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}, extr
171
177
  throw new HarnessFailure(`a request ran past the check's 1000 ms (${e.message})`);
172
178
  throw e;
173
179
  }
180
+ finally {
181
+ observing = false;
182
+ }
174
183
  return ctx.__r;
175
184
  };
176
- return { ctx, counts, arms, call, setNow: n => { now = n; }, get: name => vm.runInContext(`__gdp[${JSON.stringify(name)}]`, ctx),
185
+ return { ctx, counts, arms, call, observations: () => validateNativeObservations({ invocation, calls: {}, ...(observedClock === undefined ? {} : { clock: observedClock }) }, new Set()), setNow: n => { now = n; }, get: name => vm.runInContext(`__gdp[${JSON.stringify(name)}]`, ctx),
177
186
  bindings: method => { if (captureErrors.has(method))
178
187
  throw new Error(captureErrors.get(method)); return captured.get(method); } };
179
188
  }
@@ -442,7 +451,7 @@ function checkOnce(code, file, m, r, sorts, opts) {
442
451
  }
443
452
  // An object a factory makes: its state is what its functions close over, read and set through the two functions the
444
453
  // check added to it.
445
- const stateOf = (self) => (m.factory ? box.call('$get', self, []).value : self);
454
+ const stateOf = (self) => (m.factory ? box.call('$get', self, [], true).value : self);
446
455
  const evalAt = (env) => (t) => evalTerm(t, env);
447
456
  // The arms of the code the step reads (the entry, its methods, the functions it inlines; a class's constructor too).
448
457
  const inSpan = (a) => !m.spans || m.spans.some(([s0, e0]) => a.pos >= s0 && a.pos < e0);
@@ -461,6 +470,7 @@ function checkOnce(code, file, m, r, sorts, opts) {
461
470
  const side = {
462
471
  nativeState: (self, snap, params) => standalone ? {} : isClass ? stateOf(self) : valueOf(snap, m.layout, m, evalAt(params), box.ctx),
463
472
  nativeBindings: e => box.bindings(e.call),
473
+ nativeObservations: () => box.observations(),
464
474
  ...(standalone ? { nativeInputs: nativeInputs(code, file, m.entry, opts.files) } : {}),
465
475
  make: params => {
466
476
  const now0 = m.params.find(v => v.note?.startsWith('Date.now()'));
@@ -469,7 +479,7 @@ function checkOnce(code, file, m, r, sorts, opts) {
469
479
  // A Map the constructor is given: an empty one, made in the code's realm.
470
480
  return box.call('$new', undefined, (m.ctorArgs ?? []).filter(n => n !== now0?.name).map(n => ctorValue(n, params)));
471
481
  },
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}`); })()),
482
+ at: (snap, params) => (box.call('$at', undefined, [valueOf(snap, m.layout, m, evalAt(params), box.ctx), ctorValues(params)], true).ok ? box.ctx.__r.value : (() => { throw new Error(`could not make the object: ${box.ctx.__r.error}`); })()),
473
483
  snapOf: (self, params) => snapOf(stateOf(self), m.layout, m, evalAt(params)),
474
484
  call: (self, e, args) => {
475
485
  if (standalone)
@@ -548,7 +558,7 @@ export function drive(m, r, sorts, code, opts = {}) {
548
558
  const recordInitial = (side, params) => {
549
559
  const state = capture(() => nativeState(side, params));
550
560
  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 });
561
+ journal.observations.push({ where: 'initial native state', before: state, after: state, params: { ...params }, inputs: {}, bindings: {}, args: [], result: undefined, failed: false, ...(code.nativeEquality ? { nativeEquality: code.nativeEquality } : {}) });
552
562
  };
553
563
  const paramKinds = m.params.map(v => [v, kindOfVar(v, sorts)]), inputKinds = m.inputs.map(v => [v, kindOfVar(v, sorts)]);
554
564
  const fail = (what) => { ev.mismatch = what; return finish(); };
@@ -766,6 +776,9 @@ export function drive(m, r, sorts, code, opts = {}) {
766
776
  const bindings = capture(() => code.nativeBindings?.(e));
767
777
  if (code.nativeBindings && !bindings)
768
778
  journal.reason ??= `native parameter capture unavailable for ${e.call}`;
779
+ const observed = capture(() => code.nativeObservations ? nativeSnapshot(code.nativeObservations(e)) : undefined);
780
+ if (code.nativeObservations && !observed)
781
+ journal.reason ??= `native execution observations unavailable for ${e.call}`;
769
782
  const fallback = Object.create(null);
770
783
  e.names?.forEach((n, i) => {
771
784
  const value = nativeArgs?.[i];
@@ -776,7 +789,7 @@ export function drive(m, r, sorts, code, opts = {}) {
776
789
  });
777
790
  const rk = m.results?.[e.call];
778
791
  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') });
792
+ args: nativeArgs ?? [], result, failed: false, ...(observed ? { observed } : {}), ...(code.nativeEquality ? { nativeEquality: code.nativeEquality } : {}), legacyResult: !standalone && rk?.k === 'rec' && rk.fields.some(([field]) => field === 'value') });
780
793
  }
781
794
  next.side = afterSide;
782
795
  next.st = rule.st;
@@ -1035,9 +1048,14 @@ export function drive(m, r, sorts, code, opts = {}) {
1035
1048
  return;
1036
1049
  }
1037
1050
  const result = capture(() => nativeSnapshot(returned.value)), savedArgs = capture(() => nativeSnapshot(args));
1051
+ const observed = capture(() => code.nativeObservations ? nativeSnapshot(code.nativeObservations(event)) : undefined);
1052
+ if (code.nativeObservations && !observed) {
1053
+ journal.reason ??= 'independent native execution observations unavailable';
1054
+ return;
1055
+ }
1038
1056
  if (!journal.reason)
1039
1057
  journal.observations.push({ where: `exhaustive native input ${++ordinal}`, method: event.call,
1040
- before: {}, after: {}, params: {}, inputs: {}, bindings, args: savedArgs, result, failed: false });
1058
+ before: {}, after: {}, params: {}, inputs: {}, bindings, args: savedArgs, result, failed: false, ...(observed ? { observed } : {}), ...(code.nativeEquality ? { nativeEquality: code.nativeEquality } : {}) });
1041
1059
  return;
1042
1060
  }
1043
1061
  for (const value of finite[at])