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
@@ -1,6 +1,7 @@
1
1
  import { Outside, constantsOf, draw, drive, evalTerm } from "./extract-check.js";
2
2
  import { buildCheck, builtEvidence, compileLimit, openHarness, stopped, stubbed } from "./extract-step.js";
3
3
  import { node } from "./extract-go.js";
4
+ import { nativeWireDecoder, snapshotNativeBindings } from "./native-wire.js";
4
5
  // --- the harness ------------------------------------------------------------------------------------------------------
5
6
  // Go source beside the package: a state set from JSON and read back as JSON, leaf by leaf; each method called with its
6
7
  // arguments made from JSON; a panic recovered; the left-out fields compared before and after.
@@ -67,6 +68,24 @@ function harness(pkg, read, m, discard) {
67
68
  case 'sink': break;
68
69
  }
69
70
  }
71
+ const nativeTree = { children: new Map(), leaf: false };
72
+ for (const l of read.leaves)
73
+ if (!['bignil', 'mapnil', 'frame', 'sink'].includes(l.kind)) {
74
+ let node = nativeTree;
75
+ for (const f of l.path) {
76
+ if (!node.children.has(f))
77
+ node.children.set(f, { children: new Map(), leaf: false });
78
+ node = node.children.get(f);
79
+ }
80
+ node.leaf = true;
81
+ }
82
+ const nativeNode = (node, path) => {
83
+ const value = path.length ? `o.${path.join('.')}` : 'o';
84
+ if (node.leaf)
85
+ return `e.value(reflect.ValueOf(${value}))`;
86
+ return `e.record(reflect.ValueOf(${path.length ? `&${value}` : value}), func() []any { return []any{${[...node.children].map(([f, child]) => `[]any{${JSON.stringify(f)}, ${nativeNode(child, [...path, f])}}`).join(', ')}} })`;
87
+ };
88
+ const nativeState = nativeNode(nativeTree, []);
70
89
  const frames = read.leaves.filter(l => l.kind === 'frame');
71
90
  // The methods: their arguments made from JSON (a struct the caller gives: a fresh one with the fields given).
72
91
  const calls = [];
@@ -113,7 +132,8 @@ function harness(pkg, read, m, discard) {
113
132
  const recv = meth.ptr ? 'o' : '(*o)';
114
133
  const invoke = outs.length ? `${outs.join(', ')} := ${recv}.${meth.name}(${argList})` : `${recv}.${meth.name}(${argList})`;
115
134
  const keptOut = kept.length ? (T(kept[0]).k === 'int' ? `res.Out = ${intGet('r0', kept[0])}; res.HasOut = true` : 'res.Out = r0; res.HasOut = true') : '';
116
- calls.push(`case ${JSON.stringify(meth.name)}:\n\t\t${lines.join('\n\t\t')}\n\t\treturn func(res *gdpRes) { ${invoke}; ${keptOut}${meth.err ? '; if err != nil { res.Err = err.Error() }' : ''} }, nil`);
135
+ const bindings = `gdpNativeFrame(func(e *gdpNativeEncoder) any { return e.record(reflect.Value{}, func() []any { return []any{${meth.params.map((pa, i) => `[]any{${JSON.stringify(pa.name)}, e.value(reflect.ValueOf(a${i}))}`).join(', ')}} }) })`;
136
+ calls.push(`case ${JSON.stringify(meth.name)}:\n\t\t${lines.join('\n\t\t')}\n\t\tbindings := ${bindings}\n\t\treturn func(res *gdpRes) { res.NativeBindings = bindings; ${invoke}; ${keptOut}${meth.err ? '; if err != nil { res.Err = err.Error() }' : ''} }, nil`);
117
137
  }
118
138
  const code = `// Generated by gdp-wired's Go check (core/extract-go-check.ts): the package's code is called as it is.
119
139
  package ${pkg.package}
@@ -165,7 +185,93 @@ func gdpAnswer[T any](name string, _ ...any) T {
165
185
  return v
166
186
  }
167
187
  ` : ''}
188
+ // Native observations are independent of gdpGet's flattened model projection.
189
+ // Keep actual typed values and storage identities alive for the whole harness.
190
+ type gdpNativeKey struct { Type reflect.Type; Kind reflect.Kind; Address uintptr; Len int; Cap int }
191
+ var gdpNativeNext uint64
192
+ var gdpNativeIDs = map[gdpNativeKey]string{}
193
+ var gdpNativeKeep []reflect.Value
194
+ type gdpNativeEncoder struct { seen map[string]bool; nodes int }
195
+ func (e *gdpNativeEncoder) tick() {
196
+ e.nodes++; if e.nodes > 10000 { panic("native snapshot exceeds node bound") }
197
+ }
198
+ func (e *gdpNativeEncoder) identity(v reflect.Value) string {
199
+ var key gdpNativeKey
200
+ if v.IsValid() {
201
+ key.Type, key.Kind = v.Type(), v.Kind()
202
+ switch v.Kind() {
203
+ case reflect.Map: key.Address = uintptr(v.UnsafePointer())
204
+ case reflect.Slice: key.Address, key.Len, key.Cap = v.Pointer(), v.Len(), v.Cap()
205
+ case reflect.Struct, reflect.Array: if v.CanAddr() { key.Address = v.Addr().Pointer() }
206
+ }
207
+ }
208
+ if key.Address != 0 { if id, ok := gdpNativeIDs[key]; ok { return id } }
209
+ if len(gdpNativeKeep) >= 100000 || gdpNativeNext >= 1000000 { panic("native snapshot exceeds identity bound") }
210
+ gdpNativeNext++; id := strconv.FormatUint(gdpNativeNext, 10)
211
+ if key.Address != 0 { gdpNativeIDs[key] = id; gdpNativeKeep = append(gdpNativeKeep, v) }
212
+ return id
213
+ }
214
+ func (e *gdpNativeEncoder) container(v reflect.Value, kind string, items func() []any) any {
215
+ id := e.identity(v)
216
+ if e.seen[id] { return map[string]any{"kind":"ref", "id":id} }
217
+ e.seen[id] = true
218
+ return map[string]any{"kind":kind, "id":id, "items":items()}
219
+ }
220
+ func (e *gdpNativeEncoder) record(v reflect.Value, fields func() []any) any {
221
+ e.tick()
222
+ for v.IsValid() && (v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface) { if v.IsNil() { return nil }; v = v.Elem() }
223
+ return e.container(v, "object", fields)
224
+ }
225
+ func (e *gdpNativeEncoder) value(v reflect.Value) any {
226
+ e.tick()
227
+ if !v.IsValid() { return nil }
228
+ if v.Kind() == reflect.Interface { if v.IsNil() { return nil }; return e.value(v.Elem()) }
229
+ if v.Kind() == reflect.Ptr {
230
+ if v.IsNil() { return nil }
231
+ // The exact standard big.Int implementation, never an arbitrary Stringer.
232
+ if v.Type() == reflect.TypeOf((*big.Int)(nil)) {
233
+ n, err := strconv.ParseInt((*big.Int)(v.UnsafePointer()).String(), 10, 64)
234
+ if err != nil || n < -9007199254740991 || n > 9007199254740991 { panic("native big.Int outside exact integer range") }; return n
235
+ }
236
+ return e.value(v.Elem())
237
+ }
238
+ switch v.Kind() {
239
+ case reflect.Bool: return v.Bool()
240
+ case reflect.String: return v.String()
241
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
242
+ n := v.Int(); if n < -9007199254740991 || n > 9007199254740991 { panic("native integer outside exact integer range") }; return n
243
+ case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
244
+ n := v.Uint(); if n > 9007199254740991 { panic("native integer outside exact integer range") }; return n
245
+ case reflect.Struct:
246
+ return e.container(v, "object", func() []any {
247
+ items := []any{}; for i := 0; i < v.NumField(); i++ { items = append(items, []any{v.Type().Field(i).Name, e.value(v.Field(i))}) }; return items
248
+ })
249
+ case reflect.Array, reflect.Slice:
250
+ if v.Kind() == reflect.Slice && v.IsNil() { return nil }
251
+ return e.container(v, "array", func() []any {
252
+ items := []any{}; for i := 0; i < v.Len(); i++ { items = append(items, e.value(v.Index(i))) }; return items
253
+ })
254
+ case reflect.Map:
255
+ if v.IsNil() { return nil }
256
+ return e.container(v, "map", func() []any {
257
+ items := []any{}; iter := v.MapRange(); for iter.Next() {
258
+ k := iter.Key(); if k.Kind() != reflect.String && (k.Kind() < reflect.Int || k.Kind() > reflect.Uintptr) { panic("unsupported native map key") }
259
+ items = append(items, []any{e.value(k), e.value(iter.Value())})
260
+ }; return items
261
+ })
262
+ default: panic("unsupported native snapshot kind: " + v.Kind().String())
263
+ }
264
+ }
265
+ func gdpNativeFrame(root func(*gdpNativeEncoder) any) (frame map[string]any) {
266
+ defer func() { if r := recover(); r != nil { frame = map[string]any{"error":fmt.Sprint(r)} } }()
267
+ e := &gdpNativeEncoder{seen:map[string]bool{}}
268
+ return map[string]any{"snapshot":map[string]any{"version":1, "root":root(e)}}
269
+ }
270
+ func gdpNativeState(o *${read.entry}) map[string]any {
271
+ return gdpNativeFrame(func(e *gdpNativeEncoder) any { return ${nativeState} })
272
+ }
168
273
  type gdpRes struct {
274
+ NativeBindings map[string]any \`json:"nativeBindings,omitempty"\`
169
275
  State map[string]any \`json:"state,omitempty"\`
170
276
  Out any \`json:"out,omitempty"\`
171
277
  HasOut bool \`json:"hasOut,omitempty"\`
@@ -273,6 +379,8 @@ func GdpHarnessMain(in, out string) {
273
379
  panic(err)
274
380
  }
275
381
  switch c.Op {
382
+ case "hello": res = map[string]any{"nativeSnapshot":1, "nativeBindings":1, "nativeEquality":"scalar"}
383
+ case "native": res = gdpNativeState(objs[c.ID])
276
384
  case "new":
277
385
  objs[len(objs)+1] = new(${read.entry})
278
386
  res = map[string]any{"id": len(objs)}
@@ -436,6 +544,11 @@ export function speak(work, bin, env, pkg, read, r, sorts, opts, count) {
436
544
  throw new Error('the harness stopped');
437
545
  return stopped(JSON.parse(l));
438
546
  };
547
+ // Capability-gated transport of independently captured native values. Older
548
+ // harnesses retain their old replay/refusal behavior, never fabricated bindings.
549
+ const capabilities = ask({ op: 'hello' });
550
+ const decode = capabilities.nativeSnapshot === 1 || capabilities.nativeBindings === 1 ? nativeWireDecoder() : undefined;
551
+ let bindings;
439
552
  // A state from the harness as a snapshot (a number past the safe integers: the code leaves the rule's numbers).
440
553
  const toSnap = (s) => {
441
554
  const leaves = {}, maps = {}, lists = {};
@@ -502,6 +615,7 @@ export function speak(work, bin, env, pkg, read, r, sorts, opts, count) {
502
615
  let now = 0;
503
616
  const r0 = performance.now();
504
617
  const side = {
618
+ ...(capabilities.nativeEquality === 'scalar' ? { nativeEquality: 'scalar' } : {}),
505
619
  // (a constructor's arguments, C++'s: the rule's parameters)
506
620
  make: params => { const res = ask({ op: 'new', ...ctorArgs(params) }); return res.bad ? { ok: false, error: `the code can't be made with it (${res.bad})` } : { ok: true, value: res.id }; },
507
621
  at: (s, params) => { const res = ask({ op: 'at', state: snapJson(s), ...ctorArgs(params) }); return res.bad ? undefined : res.id; },
@@ -515,6 +629,7 @@ export function speak(work, bin, env, pkg, read, r, sorts, opts, count) {
515
629
  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 }]; }));
516
630
  }
517
631
  const res = ask({ op: 'call', id: self, m: e.call, now, a: args, ...(answers ? { answers } : {}) });
632
+ bindings = res.nativeBindings;
518
633
  if (res.frame)
519
634
  throw new Error(`the code changes ${res.frame}, a field the rule leaves out`);
520
635
  if (res.bad)
@@ -523,6 +638,17 @@ export function speak(work, bin, env, pkg, read, r, sorts, opts, count) {
523
638
  return { ok: false, error: res.err !== undefined ? `error: ${res.err}` : `panic: ${res.panic}` };
524
639
  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 };
525
640
  },
641
+ ...(capabilities.nativeSnapshot === 1 && decode ? { nativeState: (self) => {
642
+ const res = ask({ op: 'native', id: self });
643
+ if (res.error !== undefined && res.error !== null)
644
+ throw new Error(`native snapshot: ${typeof res.error === 'string' ? res.error : 'invalid non-string error payload'}`);
645
+ return decode(res.snapshot);
646
+ } } : {}),
647
+ ...(capabilities.nativeBindings === 1 && decode ? { nativeBindings: () => {
648
+ if (bindings?.error)
649
+ throw new Error(`native parameter capture: ${bindings.error}`);
650
+ return bindings?.snapshot ? snapshotNativeBindings(decode, bindings.snapshot) : undefined;
651
+ } } : {}),
526
652
  args: (inputs, e) => e.args.map(a => argJson(a, inputs)),
527
653
  setNow: n => { if (!Number.isSafeInteger(n))
528
654
  throw new Outside('Go clock outside the exact integer range'); now = n; },
@@ -1160,6 +1160,10 @@ export function goNames(read) {
1160
1160
  else
1161
1161
  out.push({ code, rule: '', role: 'state', none: l.name });
1162
1162
  }
1163
+ else if (l.kind === 'list') {
1164
+ const declaration = m.lists?.find(d => d.name === l.name);
1165
+ out.push({ code, rule: l.name, role: 'state', list: { scalar: true, ...(declaration?.len === undefined ? {} : { length: declaration.len }) } });
1166
+ }
1163
1167
  else if (l.kind === 'int' || l.kind === 'bool' || l.kind === 'str' || l.kind === 'big')
1164
1168
  out.push({ code, rule: l.name, role: 'state' });
1165
1169
  }
@@ -1176,13 +1180,15 @@ export function goNames(read) {
1176
1180
  for (const pa of mt.params)
1177
1181
  arg(pa.arg, pa.name, 'input', mt.name);
1178
1182
  for (const a of read.answers ?? [])
1179
- out.push({ code: a.key, rule: a.inputs.name, role: 'answer', ...(a.inputs.none ? { none: a.inputs.none } : {}) });
1183
+ out.push({ code: a.key, rule: a.inputs.name, role: 'answer', native: { kind: 'answer', key: a.key }, ...(a.inputs.none ? { none: a.inputs.none } : {}) });
1180
1184
  for (const [method, r] of Object.entries(m.results ?? {})) {
1181
1185
  if (r.k === 'scalar')
1182
1186
  out.push({ code: 'result', rule: r.name, role: 'result', method });
1183
1187
  else if (r.k === 'rec')
1184
- for (const [f, n] of r.fields)
1188
+ for (const [f, n] of r.fields) {
1185
1189
  out.push({ code: f === 'result' ? 'result' : f, rule: n, role: 'result', method });
1190
+ out.push({ code: `result.${f}`, rule: n, role: 'result', method });
1191
+ }
1186
1192
  }
1187
1193
  if (m.event)
1188
1194
  out.push({ code: 'method', rule: m.event, role: 'method' });
@@ -167,10 +167,10 @@ function compiled(lang, mod, read, o, made) {
167
167
  const build = (file, out, srcDir) => {
168
168
  if (kotlin) {
169
169
  const kt = kotlinLib(o);
170
- cp.execFileSync(jdk(o).java, ['-Xss8m', '-cp', `${kt}/kotlin-compiler.jar`, 'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler', '-kotlin-home', path.dirname(kt), '-nowarn', '-no-reflect', '-d', out, '-cp', [t, extra].filter(Boolean).join(':'), file, ...(o.sources ?? []).map(f => path.resolve(f))], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 1 << 26, timeout: limit, killSignal: 'SIGKILL' });
170
+ cp.execFileSync(jdk(o).java, ['-Xss8m', '-cp', `${kt}/kotlin-compiler.jar`, 'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler', '-kotlin-home', path.dirname(kt), '-nowarn', '-no-reflect', '-java-parameters', '-d', out, '-cp', [t, extra].filter(Boolean).join(':'), file, ...(o.sources ?? []).map(f => path.resolve(f))], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 1 << 26, timeout: limit, killSignal: 'SIGKILL' });
171
171
  return [out, `${kt}/kotlin-stdlib.jar`];
172
172
  }
173
- cp.execFileSync(jdk(o).javac, ['-nowarn', '-Xlint:none', '-proc:none', '-implicit:class', '-d', out, '-sourcepath', `${srcDir}:${mod.root}`, '-cp', [t, extra].filter(Boolean).join(':'), file], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 1 << 26, timeout: limit, killSignal: 'SIGKILL' });
173
+ cp.execFileSync(jdk(o).javac, ['-nowarn', '-Xlint:none', '-proc:none', '-implicit:class', '-parameters', '-d', out, '-sourcepath', `${srcDir}:${mod.root}`, '-cp', [t, extra].filter(Boolean).join(':'), file], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 1 << 26, timeout: limit, killSignal: 'SIGKILL' });
174
174
  return [out];
175
175
  };
176
176
  // What the compiler says is wrong with the code (its error lines), none where it crashed, was killed or timed out.
@@ -129,6 +129,39 @@ function toJson(t, x) {
129
129
  return `json!(match ${x} { ${t.values.map(v => `${t.enum}::${v} => ${JSON.stringify(v)}`).join(', ')} })`;
130
130
  return 'json!(null)';
131
131
  }
132
+ // Wire values are read from typed native locals/fields, never the model's Snap.
133
+ // Foreign record equality is deliberately not advertised by the harness.
134
+ function nativeValue(t, x, mod, depth = 0) {
135
+ if (depth > 8)
136
+ return 'return Err("native value exceeds depth bound".into())';
137
+ if (t.k === 'int')
138
+ return `native_int(&(${t.unit === 'instant' ? `of_inst(*(${x}))` : t.unit === 'duration' ? `(${x}).as_nanos()` : `*(${x})`}).to_string())?`;
139
+ if (t.k === 'bool')
140
+ return `json!(*(${x}))`;
141
+ if (t.k === 'str')
142
+ return `json!(${x})`;
143
+ if (t.k === 'choice') {
144
+ // std Ordering is non-exhaustive even though the reader knows five variants.
145
+ // A future variant must refuse capture, never borrow a known label.
146
+ const other = t.enum === '::std::sync::atomic::Ordering' ? ', _ => return Err("unsupported native atomic ordering".into())' : '';
147
+ return `json!(match ${x} { ${t.values.map(v => `${t.enum}::${v} => ${JSON.stringify(v)}`).join(', ')}${other} })`;
148
+ }
149
+ if (t.k === 'opt')
150
+ return `match ${x} { Some(__v${depth}) => ${nativeValue(t.of, `__v${depth}`, mod, depth + 1)}, None => Value::Null }`;
151
+ if (t.k === 'none')
152
+ return 'Value::Null';
153
+ if (t.k === 'rec') {
154
+ const r = mod.recs[t.name];
155
+ if (r)
156
+ return `native_object(vec![${r.fields.map(f => {
157
+ const place = `(${x}).${f.name}`;
158
+ const at = f.t.atomic, lock = f.t.lock;
159
+ const actual = at ? `${place}.load(std::sync::atomic::Ordering::SeqCst)` : lock ? (lock === 'std' ? `(*${place}.lock().unwrap())` : `(*${place}.lock())`) : place;
160
+ return `(${JSON.stringify(f.name)}, ${nativeValue(f.t, `&(${actual})`, mod, depth + 1)})`;
161
+ }).join(', ')}])`;
162
+ }
163
+ return `return Err(${JSON.stringify(`unsupported native value: ${t.k}`)}.into())`;
164
+ }
132
165
  function harnessCode(mod, read, cls, name) {
133
166
  const leaves = read.leaves.filter(l => l.kind !== 'frame' && l.kind !== 'map');
134
167
  if (read.leaves.some(l => l.kind === 'map'))
@@ -161,11 +194,13 @@ function harnessCode(mod, read, cls, name) {
161
194
  const calls = Object.entries(read.args).map(([m]) => {
162
195
  const f = cls ? fn(cls.methods[m]) : fn(m);
163
196
  const ps = f.params.filter(p => !p.self);
164
- const args = ps.map((p, i) => { const rs = p.rs ?? ''; const v = fromJson(p.t, `(&a[${i}][1])`, mod); return /^&\s*mut/.test(rs) ? `&mut ${v}` : rs.startsWith('&') ? `&${v}` : v; });
197
+ const bound = ps.map((p, i) => `let mut __gdp_arg${i} = ${fromJson(p.t, `(&a[${i}][1])`, mod)};`);
198
+ const binding = `native_wire(native_object(vec![${ps.map((p, i) => `(${JSON.stringify(p.name)}, ${nativeValue(p.t, `&__gdp_arg${i}`, mod)})`).join(', ')}]))`;
199
+ const args = ps.map((p, i) => { const rs = p.rs ?? ''; return /^&\s*mut/.test(rs) ? `&mut __gdp_arg${i}` : rs.startsWith('&') ? `&__gdp_arg${i}` : `__gdp_arg${i}`; });
165
200
  const target = cls ? `o.${m}(${args.join(', ')})` : `super::${m}(${args.join(', ')})`;
166
201
  const ret = f.ret;
167
202
  const out = ret.k === 'res' ? `match r { Ok(v) => { let _ = &v; Ok(${ret.of.k === 'none' ? 'json!(null)' : tagged(ret.of, 'v')}) } Err(_) => Err("an Err".to_string()) }` : ret.k === 'opt' ? `Ok(match r { Some(v) => ${tagged(ret.of, 'v')}, None => json!(null) })` : ret.k === 'none' ? 'Ok(json!(null))' : `Ok(${tagged(ret, 'r')})`;
168
- return `${JSON.stringify(m)} => { let r = ${target}; ${out} }`;
203
+ return `${JSON.stringify(m)} => { ${bound.join(" ")} *BINDINGS.lock().unwrap_or_else(|e| e.into_inner()) = Some(binding_frame((|| -> Result<Value, String> { Ok(${binding}) })())); let r = ${target}; ${out} }`;
169
204
  });
170
205
  return `
171
206
  #[cfg(test)]
@@ -178,6 +213,8 @@ pub(crate) mod ${name} {
178
213
  static NOW: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(0);
179
214
  // An answered call's value: the request's input for it (each answered call rewritten to crate::__gdp_answer).
180
215
  static ANS: std::sync::Mutex<Option<Value>> = std::sync::Mutex::new(None);
216
+ static BINDINGS: std::sync::Mutex<Option<Value>> = std::sync::Mutex::new(None);
217
+ static NATIVE_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
181
218
  pub(crate) trait GdpAns { fn of(v: &Value) -> Self; }
182
219
  // (an answer outside the call's type, a type stated wider than the code's: a request the code can't be given)
183
220
  pub(crate) struct GdpOutside(pub(crate) String);
@@ -194,6 +231,11 @@ pub(crate) mod ${name} {
194
231
  fn of_inst(t: std::time::Instant) -> i128 { if t >= base() { t.duration_since(base()).as_nanos() as i128 } else { -(base().duration_since(t).as_nanos() as i128) } }
195
232
  fn val(v: &Value) -> &Value { v.get("in").unwrap_or(v) }
196
233
  fn int(v: &Value) -> Result<i128, String> { if let Some(s) = v.as_str() { s.parse::<i128>().map_err(|e| e.to_string()) } else if let Some(i) = v.as_i64() { Ok(i as i128) } else if let Some(u) = v.as_u64() { Ok(u as i128) } else { Err(format!("not a number: {v}")) } }
234
+ fn native_object(items: Vec<(&str, Value)>) -> Value { json!({"kind": "object", "id": NATIVE_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst).to_string(), "items": items}) }
235
+ fn native_wire(root: Value) -> Value { json!({"version": 1, "root": root}) }
236
+ fn native_int(s: &str) -> Result<Value, String> { let n = s.parse::<i128>().map_err(|_| "native integer outside safe range")?; if n < -9007199254740991 || n > 9007199254740991 { return Err("native integer outside safe range".into()); } Ok(json!(n as i64)) }
237
+ fn binding_frame(value: Result<Value, String>) -> Value { match value { Ok(snapshot) => json!({"snapshot": snapshot}), Err(error) => json!({"error": error}) } }
238
+ fn native(o: &${self}) -> Result<Value, String> { Ok(native_wire(native_object(vec![${(cls?.fields ?? []).map(f => `(${JSON.stringify(f.name)}, ${nativeValue(f.t, `&(${access([f.name], f.t).read})`, mod)})`).join(', ')}]))) }
197
239
  fn get(o: &${self}) -> Value { let mut s = serde_json::Map::new(); ${get.join(' ')} Value::Object(s) }
198
240
  fn set(o: &mut ${self}, st: &Value) -> Result<(), String> { ${set.join(' ')} Ok(()) }
199
241
  fn make(req: &Value) -> Result<${self}, String> { NOW.store(int(&req["now"]).unwrap_or(0) as i64, std::sync::atomic::Ordering::SeqCst); Ok(${make}) }
@@ -214,24 +256,28 @@ pub(crate) mod ${name} {
214
256
  let op = req["op"].as_str().unwrap_or("").to_string();
215
257
  let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> Value {
216
258
  match op.as_str() {
217
- "hello" => json!({"ok": true}),
259
+ "hello" => json!({"ok": true, "nativeSnapshot": 1, "nativeBindings": 1, "nativeEquality": "scalar"}),
218
260
  "new" => match make(&req) { Ok(o) => { objs.push(o); json!({"id": objs.len()}) } Err(e) => json!({"err": e}) },
219
261
  "at" => match make(&req) { Ok(mut o) => match set(&mut o, &req["state"]) { Ok(()) => { objs.push(o); json!({"id": objs.len()}) } Err(e) => json!({"bad": e}) }, Err(e) => json!({"bad": e}) },
220
262
  "get" => { let i = req["id"].as_u64().unwrap() as usize - 1; json!({"state": get(&objs[i])}) }
263
+ "native" => { let i = req["id"].as_u64().unwrap() as usize - 1; match native(&objs[i]) { Ok(snapshot) => json!({"snapshot": snapshot}), Err(error) => json!({"error": error}) } }
221
264
  "call" => {
265
+ *BINDINGS.lock().unwrap_or_else(|e| e.into_inner()) = None;
222
266
  let i = req["id"].as_u64().unwrap() as usize - 1;
223
267
  NOW.store(int(&req["now"]).unwrap_or(0) as i64, std::sync::atomic::Ordering::SeqCst);
224
268
  *ANS.lock().unwrap_or_else(|e| e.into_inner()) = Some(req["answers"].clone());
225
269
  let m = req["m"].as_str().unwrap().to_string();
226
270
  let a = req["a"].clone();
227
271
  let o = &mut objs[i];
228
- match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| call(o, &m, &a))) {
272
+ let mut result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| call(o, &m, &a))) {
229
273
  Ok(Ok(Ok(v))) => json!({"out": v}),
230
274
  Ok(Ok(Err(e))) => json!({"out": null, "err": e}),
231
275
  Ok(Err(bad)) => json!({"out": null, "bad": bad}),
232
276
  Err(p) if p.downcast_ref::<GdpOutside>().is_some() => json!({"out": null, "outside": p.downcast_ref::<GdpOutside>().unwrap().0}),
233
277
  Err(p) => json!({"out": null, "err": format!("panic: {}", p.downcast_ref::<String>().cloned().or_else(|| p.downcast_ref::<&str>().map(|s| s.to_string())).unwrap_or_default())}),
234
- }
278
+ };
279
+ result["nativeBindings"] = BINDINGS.lock().unwrap_or_else(|e| e.into_inner()).clone().unwrap_or_else(|| json!({"error": "native arguments were not bound"}));
280
+ result
235
281
  }
236
282
  "coverage" => json!({"hit": []}),
237
283
  _ => json!({"error": format!("no op {op}")}),
@@ -27,7 +27,8 @@
27
27
  import * as I from "./extract-ir.js";
28
28
  import { Refusal, mergeOps, mergeWrites } from "./extract-read.js";
29
29
  import { fromModel } from "./extract.js";
30
- import { nativeWireDecoder } from "./native-wire.js";
30
+ import { nativeWireDecoder, snapshotNativeBindings } from "./native-wire.js";
31
+ import { nativeObservationSequence } from "./native-observations.js";
31
32
  import { nonneg } from "./extract-print.js";
32
33
  import { HarnessFailure, Outside, constantsOf, draw, drive, evalTerm, noEvidence, retried, tiesIn } from "./extract-check.js";
33
34
  // Bitwise and, or and xor of two naturals below 2^53 (JavaScript's operators stop at 32 bits).
@@ -6633,7 +6634,15 @@ function checkStepOnce(h, read, r, sorts, opts) {
6633
6634
  const hi = ask({ op: 'hello', ...h.hello, naiveUtc: read.naiveUtc, leaves: read.leaves, ctor: read.ctor, answers: read.answers, kept: read.kept, cls: read.cls ?? null, stores: read.stores, arms: read.arms, discard: opts.onError === 'discard', ...(read.inject ? { inject: read.inject } : {}), ...(read.globals ? { globals: read.globals } : {}), ...(read.inert ? { inert: read.inert } : {}), ...(opts.fields ? { fields: opts.fields } : {}) });
6634
6635
  if (hi.error)
6635
6636
  return { ...empty, mismatch: `the code doesn't load with the check's harness: ${JSON.stringify(hi.error)}` };
6636
- const native = hi.nativeSnapshot === 1 && read.leaves.some(l => l.ordered) ? nativeWireDecoder() : undefined;
6637
+ if (hi.nativeEquality !== undefined && hi.nativeEquality !== 'scalar')
6638
+ return { ...empty, mismatch: 'unsupported native equality capability' };
6639
+ const decodeNative = hi.nativeSnapshot === 1 || hi.nativeBindings === 1 || hi.nativeObservations === 1 ? nativeWireDecoder() : undefined;
6640
+ const native = hi.nativeSnapshot === 1 ? decodeNative : undefined;
6641
+ const bindingDecoder = hi.nativeBindings === 1 ? decodeNative : undefined;
6642
+ let nativeBindings;
6643
+ const observationDecoder = hi.nativeObservations === 1 ? decodeNative : undefined;
6644
+ const acceptObservation = nativeObservationSequence(new Set(read.answers.map(a => a.key)));
6645
+ let nativeObservations, observedCache;
6637
6646
  const num = (x, at) => { const n = Number(x); if (typeof x === 'string' && Number.isSafeInteger(n) && String(n) === x)
6638
6647
  return n; throw new Outside(`${at} is ${String(x)}`); };
6639
6648
  const toSnap = (s) => {
@@ -6674,6 +6683,9 @@ function checkStepOnce(h, read, r, sorts, opts) {
6674
6683
  throw new Error(JSON.stringify(res.error)); return toSnap(res.state); },
6675
6684
  call: (self, e, args) => {
6676
6685
  const res = ask({ op: 'call', id: self, m: e.call, a: args, now, answers: answersOf(e.call) });
6686
+ nativeBindings = res.nativeBindings;
6687
+ nativeObservations = res.nativeObservations;
6688
+ observedCache = undefined;
6677
6689
  if (res.outside !== undefined)
6678
6690
  return { ok: false, outside: true, error: res.outside };
6679
6691
  if (res.frame)
@@ -6720,6 +6732,26 @@ function checkStepOnce(h, read, r, sorts, opts) {
6720
6732
  throw new Error(`native snapshot: ${JSON.stringify(result.error)}`);
6721
6733
  return native(result.snapshot);
6722
6734
  } } : {}),
6735
+ ...(bindingDecoder ? { nativeBindings: () => {
6736
+ if (nativeBindings?.error)
6737
+ throw new Error(`native parameter capture: ${nativeBindings.error}`);
6738
+ if (!nativeBindings?.snapshot)
6739
+ return undefined;
6740
+ // The decoder keeps canonical identities and mutates them on later
6741
+ // frames. Journal rows must retain history, not references to that cache.
6742
+ return snapshotNativeBindings(bindingDecoder, nativeBindings.snapshot);
6743
+ } } : {}),
6744
+ ...(observationDecoder ? { nativeObservations: () => {
6745
+ if (observedCache)
6746
+ return observedCache;
6747
+ if (nativeObservations?.error)
6748
+ throw new Error(`native execution observations: ${nativeObservations.error}`);
6749
+ if (!nativeObservations?.snapshot)
6750
+ return undefined;
6751
+ const observed = acceptObservation(snapshotNativeBindings(observationDecoder, nativeObservations.snapshot));
6752
+ return observedCache = observed;
6753
+ } } : {}),
6754
+ ...(hi.nativeEquality === 'scalar' ? { nativeEquality: 'scalar' } : {}),
6723
6755
  args: (inputs, e) => { inputsNow = inputs; return (read.args[e.call] ?? []).map(([n, a]) => [n, build(a, inputs)]); },
6724
6756
  setNow: n => { now = n; },
6725
6757
  coverage: () => (coverage ??= closeAndCount()),
@@ -6917,9 +6949,11 @@ export function stepNames(read) {
6917
6949
  arg(a, code, 'input', method);
6918
6950
  for (const a of read.answers) {
6919
6951
  if (!a.pass)
6920
- out.push({ code: a.key, rule: a.inputs.name, role: 'answer', ...(a.inputs.none ? { none: a.inputs.none } : {}) });
6921
- for (const r of a.raises ?? [])
6922
- out.push({ code: `${a.key} raises`, rule: r.name, role: 'answer', method: r.m });
6952
+ out.push({ code: a.key, rule: a.inputs.name, role: 'answer', native: { kind: 'answer', key: a.key }, ...(a.inputs.none ? { none: a.inputs.none } : {}) });
6953
+ for (const r of a.raises ?? []) {
6954
+ out.push({ code: `${a.key} raises`, rule: r.name, role: 'answer', method: r.m }); // retained display alias
6955
+ out.push({ code: `${a.key}.raises`, rule: r.name, role: 'answer', method: r.m, native: { kind: 'raises', key: a.key } });
6956
+ }
6923
6957
  }
6924
6958
  const vars = new Set([...m.state, ...m.inputs].map(v => v.name));
6925
6959
  for (const [method, k] of Object.entries(read.results))
@@ -6930,7 +6964,7 @@ export function stepNames(read) {
6930
6964
  for (const a of read.answers.filter(x => x.effect && !x.quiet))
6931
6965
  out.push({ code: `${a.key}.called`, rule: `${a.key.replace(/\W+/g, '_')}_called`, role: 'result' });
6932
6966
  if (vars.has('now'))
6933
- out.push({ code: 'now', rule: 'now', role: 'clock' });
6967
+ out.push({ code: 'now', rule: 'now', role: 'clock', native: { kind: 'clock', key: 'now' } });
6934
6968
  if (m.event)
6935
6969
  out.push({ code: 'method', rule: m.event, role: 'method' });
6936
6970
  return out;
@@ -306,7 +306,49 @@ function harnessCode(g, mod, read, cls) {
306
306
  });
307
307
  if (sw.refused)
308
308
  throw new Refusal(cls.p, sw.refused);
309
- // The requests: each method by its labels, its result as the protocol tags it.
309
+ const native = (t, x, depth = 0) => {
310
+ if (depth > 8)
311
+ return 'try __gdpNativeUnsupported("native value exceeds depth bound")';
312
+ if (t.k === 'int')
313
+ return `try __gdpNativeInt(${x})`;
314
+ if (t.k === 'bool')
315
+ return `__GdpJ.b(${x})`;
316
+ if (t.k === 'str')
317
+ return `__GdpJ.s(${x})`;
318
+ if (t.k === 'choice')
319
+ return `__GdpJ.s(${caseName(t, x)})`;
320
+ if (t.k === 'none')
321
+ return '__GdpJ.null';
322
+ if (t.k === 'opt')
323
+ return `(try (${x}).map { __v${depth} in ${native(t.of, `__v${depth}`, depth + 1)} } ?? __GdpJ.null)`;
324
+ if (t.k === 'map')
325
+ return `try __gdpNativeMap((${x}).map { __kv${depth} in __GdpJ.a([${native(t.key, `__kv${depth}.key`, depth + 1)}, ${native(t.val, `__kv${depth}.value`, depth + 1)}]) })`;
326
+ if (t.k === 'rec') {
327
+ const r = mod.recs[t.name];
328
+ if (r?.swift?.kind === 'struct') {
329
+ try {
330
+ return `try __gdpNativeObject([${r.fields.map(f => `(${JSON.stringify(f.name)}, ${native(f.t, `(${x}).${accessor(g, mod, t.name, f.name)}`, depth + 1)})`).join(', ')}])`;
331
+ }
332
+ catch { /* refuse native capture, not extraction */ }
333
+ }
334
+ }
335
+ return `try __gdpNativeUnsupported(${JSON.stringify(`unsupported native value: ${t.k}`)})`;
336
+ };
337
+ const nativeFields = cls.fields.map(f => {
338
+ let value;
339
+ try {
340
+ const fake = fakeOf.get(f.name), pr = protoOf(f.name);
341
+ if (fake && pr)
342
+ value = 'try __gdpNativeUnsupported("native dependency snapshot unavailable")';
343
+ else
344
+ value = native(f.t, place([f.name]));
345
+ }
346
+ catch {
347
+ value = 'try __gdpNativeUnsupported("native field has no declared type")';
348
+ }
349
+ return `(${JSON.stringify(f.name)}, ${value})`;
350
+ });
351
+ // Prepare immutable typed slots once; the original method consumes those captures.
310
352
  const calls = Object.keys(read.args).map(m => {
311
353
  const fid = cls.methods[m], fn = fid ? mod.funcs[fid] : undefined, sig = sw.sigs?.[m];
312
354
  if (!fn || !sig)
@@ -317,7 +359,8 @@ function harnessCode(g, mod, read, cls) {
317
359
  const lets = ps.map((p, i) => `let __a${i} = ${conv(p.t, `a?[${i}]?[1]`, mod)}`);
318
360
  const callArgs = ps.map((_, i) => (sig.labels[i] === '_' ? `__a${i}` : `${sig.labels[i]}: __a${i}`)).join(', ');
319
361
  const ret = fn.ret.k === 'none' || sig.ret === 'Void' ? 'none' : 'some';
320
- return `case ${JSON.stringify(m)}:\n ${lets.join('; ')}${lets.length ? '\n ' : ''}do { ${ret === 'none' ? `try self.${sig.name}(${callArgs}); return .null` : `let __r = try self.${sig.name}(${callArgs}); return ${out(fn.ret, '__r')}`} } catch { throw __GdpErr(why: "\\(error)") }`;
362
+ const capture = `try __gdpNativeObject([${ps.map((p, i) => `(${JSON.stringify(p.name)}, ${native(p.t, `__a${i}`)})`).join(', ')}])`;
363
+ return `case ${JSON.stringify(m)}:\n ${lets.join('; ')}${lets.length ? '\n ' : ''}__gdpS.binding = __gdpNativeFrame { ${capture} }; do { ${ret === 'none' ? `try self.${sig.name}(${callArgs}); return .null` : `let __r = try self.${sig.name}(${callArgs}); return ${out(fn.ret, '__r')}`} } catch { throw __GdpErr(why: "\\(error)") }`;
321
364
  });
322
365
  const entry = `
323
366
  // --- gdp-wired's check harness (generated in the check's copy; the code itself is never changed) ---
@@ -333,12 +376,13 @@ extension ${E} {
333
376
  }
334
377
  }
335
378
  ${fakes.join('\n')}
379
+ func __gdpNative(_ o: ${E}) throws -> __GdpJ { try __gdpNativeObject([${nativeFields.join(', ')}]) }
336
380
  func __gdpGet(_ o: ${E}) -> [String: __GdpJ] { var s: [String: __GdpJ] = [:]; ${get.join('\n ')}
337
381
  return s }
338
382
  func __gdpSet(_ o: inout ${E}, _ st: [String: __GdpJ]) throws { ${set.join('\n ')} }
339
383
  func __gdpFrames(_ o: ${E}) -> [String: String] { [${frames.map(p => `${JSON.stringify(p.join('.'))}: String(describing: ${place(p)})`).join(', ') || ':'}] }
340
384
  let __gdpTpls: [String: [String]] = [${Object.entries(tpls).map(([k, v]) => `${JSON.stringify(k)}: ${JSON.stringify(v)}`).join(', ') || ':'}]
341
- final class __GdpState: @unchecked Sendable { var objs: [${E}] = []; var stores: [[String: __GdpStore]] = []; var cur: [String: __GdpStore] = [:]; var answers: [String: __GdpJ] = [:]; var discard = false }
385
+ final class __GdpState: @unchecked Sendable { var objs: [${E}] = []; var stores: [[String: __GdpStore]] = []; var cur: [String: __GdpStore] = [:]; var answers: [String: __GdpJ] = [:]; var discard = false; var nativeID = 1; var binding: __GdpJ = .o(["error": .s("native arguments were not bound")]) }
342
386
  let __gdpS = __GdpState()
343
387
  typealias __GdpEntry = ${E}
344
388
  ${resource('Harness.swift')}`;
@@ -61,6 +61,14 @@ export type Name = {
61
61
  method?: string;
62
62
  none?: string;
63
63
  value?: number;
64
+ list?: {
65
+ scalar: true;
66
+ length?: number;
67
+ };
68
+ native?: {
69
+ kind: 'answer' | 'raises' | 'clock';
70
+ key: string;
71
+ };
64
72
  map?: {
65
73
  fields: string[];
66
74
  store?: string;
@@ -1,9 +1,15 @@
1
+ import { type SearchTermination } from './search-termination.js';
1
2
  import { type Law, type Machine, type Request, type State } from './machine.js';
2
3
  import { type StepLaw, type Verdict, type proveRule } from './dsl.js';
4
+ import { type WorkAmount } from './work-amount.js';
3
5
  type AnyRule = Parameters<typeof proveRule>[0];
4
6
  type Env = Record<string, number>;
5
7
  export type InferOptions = {
8
+ watchdogMs?: number;
9
+ /** Legacy counted-millisecond compatibility budget. Mutually exclusive with work. */
6
10
  ms?: number;
11
+ /** Exact full-work units, never a millisecond conversion. */
12
+ work?: number | WorkAmount;
7
13
  runs?: number;
8
14
  runsMs?: number;
9
15
  timed?: boolean;
@@ -36,7 +42,9 @@ export type Inferred = Verdict & {
36
42
  alive: number;
37
43
  proofs: number;
38
44
  ms: number;
45
+ work: number;
39
46
  stopped: boolean;
47
+ termination?: SearchTermination;
40
48
  };
41
49
  };
42
50
  export declare const inferRates: {