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,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
+ }
@@ -1 +1,2 @@
1
+ export declare const snapshotNativeBindings: (decode: (wire: unknown) => unknown, wire: unknown) => Record<string, unknown>;
1
2
  export declare function nativeWireDecoder(maxObjects?: number, maxNodes?: number): (wire: unknown) => unknown;
@@ -1,3 +1,7 @@
1
+ import { nativeSnapshot } from "./source-check.js";
2
+ // Bindings are retained directly by the journal. Snapshot the decoder's mutable
3
+ // canonical objects before any later state/binding frame can update them.
4
+ export const snapshotNativeBindings = (decode, wire) => nativeSnapshot(decode(wire));
1
5
  // Decode identity-bearing snapshots returned by the real native harness. This
2
6
  // is observation transport only: no model values or proof results are supplied.
3
7
  export function nativeWireDecoder(maxObjects = 100000, maxNodes = 10000) {
@@ -30,7 +34,7 @@ export function nativeWireDecoder(maxObjects = 100000, maxNodes = 10000) {
30
34
  throw Error('unbound native snapshot reference');
31
35
  return objects.get(id).value;
32
36
  }
33
- if (kind !== 'object' && kind !== 'array' && kind !== 'map')
37
+ if (kind !== 'object' && kind !== 'array' && kind !== 'map' && kind !== 'set')
34
38
  throw Error('unsupported native snapshot kind');
35
39
  if (seen.has(id))
36
40
  throw Error('duplicate native snapshot identity');
@@ -41,7 +45,7 @@ export function nativeWireDecoder(maxObjects = 100000, maxNodes = 10000) {
41
45
  if (!kept) {
42
46
  if (objects.size >= maxObjects)
43
47
  throw Error('native snapshot exceeds identity bound');
44
- const fresh = kind === 'array' ? [] : kind === 'map' ? new Map() : Object.create(null);
48
+ const fresh = kind === 'array' ? [] : kind === 'map' ? new Map() : kind === 'set' ? new Set() : Object.create(null);
45
49
  kept = { kind, value: fresh };
46
50
  objects.set(id, kept);
47
51
  }
@@ -53,6 +57,16 @@ export function nativeWireDecoder(maxObjects = 100000, maxNodes = 10000) {
53
57
  for (const item of node.items)
54
58
  target.push(decode(item));
55
59
  }
60
+ else if (kind === 'set') {
61
+ const target = kept.value;
62
+ target.clear();
63
+ for (const item of node.items) {
64
+ const value = decode(item);
65
+ if (target.has(value))
66
+ throw Error('duplicate native snapshot set item');
67
+ target.add(value);
68
+ }
69
+ }
56
70
  else if (kind === 'map') {
57
71
  const target = kept.value;
58
72
  target.clear();
@@ -592,7 +592,7 @@ def hello(req):
592
592
  S['cls'] = getattr(mod, req['cls'].rpartition('.')[2]) if req.get('cls') else None
593
593
  S['loop'] = asyncio.new_event_loop()
594
594
  asyncio.set_event_loop(S['loop'])
595
- return {'ok': True, 'nativeSnapshot': 1}
595
+ return {'ok': True, 'nativeSnapshot': 1, 'nativeBindings': 1, 'nativeEquality': 'scalar'}
596
596
 
597
597
  def make(args):
598
598
  global OBJ_STORES
@@ -640,6 +640,19 @@ def call(req):
640
640
  try: kwargs = fixed_args(req['a'], {})
641
641
  except OverflowError as e:
642
642
  return {'outside': f'argument outside the declared runtime domain: {e}'}
643
+ # Bind the actual callable's Python signature, before the method can mutate
644
+ # its arguments. Never reconstruct native law inputs from the symbolic IR.
645
+ try:
646
+ native_fn = fn.__func__ if isinstance(fn, types.MethodType) else fn
647
+ if not isinstance(native_fn, types.FunctionType):
648
+ raise ValueError('unsupported native callable for parameter capture')
649
+ if any(dict.__contains__(native_fn.__dict__, name) for name in ('__signature__', '__wrapped__', '__text_signature__')):
650
+ raise ValueError('customized native signature metadata is unsupported')
651
+ bound = inspect.signature(fn, follow_wrapped=False).bind(**kwargs)
652
+ bound.apply_defaults()
653
+ native_bindings = {'snapshot': native_state(types.SimpleNamespace(**bound.arguments), select=False)}
654
+ except Exception as e:
655
+ native_bindings = {'error': f'{type(e).__name__}: {e}'[:300]}
643
656
  before = frames(obj if S['cls'] is not None else None)
644
657
  snap = state_of(obj, stores) if S.get('discard') and S['cls'] is not None else None
645
658
  sys.settrace(tracer)
@@ -658,11 +671,11 @@ def call(req):
658
671
  after = frames(obj if S['cls'] is not None else None)
659
672
  for k in before:
660
673
  if after.get(k) != before[k]: return {'frame': k}
661
- return {'out': tag(out), **({'err': err} if err is not None else {}), **({'effects': dict(EFF)} if EFF else {})}
674
+ return {'out': tag(out), 'nativeBindings': native_bindings, **({'err': err} if err is not None else {}), **({'effects': dict(EFF)} if EFF else {})}
662
675
 
663
676
  # Native observation transport for ordered containers. Retain real references
664
677
  # so Python cannot recycle an address and manufacture cross-snapshot identity.
665
- def native_state(obj):
678
+ def native_state(obj, select=True):
666
679
  seen = set()
667
680
  count = [0]
668
681
  def encode(value, names=None):
@@ -682,6 +695,10 @@ def native_state(obj):
682
695
  seen.add(ident)
683
696
  if isinstance(value, list):
684
697
  return {'kind': 'array', 'id': ident, 'items': [encode(x) for x in value]}
698
+ if type(value) is set:
699
+ return {'kind': 'set', 'id': ident, 'items': [encode(x) for x in value]}
700
+ if isinstance(value, (set, frozenset)):
701
+ raise ValueError('unsupported native snapshot set type')
685
702
  if isinstance(value, dict):
686
703
  if any(not isinstance(k, (str, int, float)) or isinstance(k, bool) for k in value):
687
704
  raise ValueError('unsupported native snapshot map key')
@@ -690,7 +707,7 @@ def native_state(obj):
690
707
  if names is not None: fields = {name: fields[name] for name in names}
691
708
  return {'kind': 'object', 'id': ident, 'items': [[k, encode(v)] for k, v in fields.items()]}
692
709
  roots = sorted({l['path'][0] for l in S['leaves'] if l.get('path') and l['kind'] != 'frame'})
693
- return {'version': 1, 'root': encode(obj, roots)}
710
+ return {'version': 1, 'root': encode(obj, roots if select else None)}
694
711
 
695
712
  def main():
696
713
  fin = open(sys.argv[1], 'r'); fout = open(sys.argv[2], 'w')
@@ -11,19 +11,152 @@ NOW = [0]
11
11
  HIT = {}
12
12
  S = {}
13
13
  OBJS = {}
14
+ # Real references retained strongly: object_id reuse must never create aliases.
15
+ NATIVE_OBJECTS = {}.compare_by_identity
16
+ NATIVE_INVOCATION = [0]
17
+ NATIVE_IS = Object.instance_method(:instance_of?)
18
+ NATIVE_CLASS = Object.instance_method(:class)
19
+ NATIVE_METHOD = Object.instance_method(:method)
20
+ NATIVE_THREAD = Thread.method(:current)
21
+ NATIVE_CLASS_NAME = Module.instance_method(:name)
22
+ NATIVE_VARS = Object.instance_method(:instance_variables)
23
+ NATIVE_GET_VAR = Object.instance_method(:instance_variable_get)
24
+ NATIVE_EQUAL = BasicObject.instance_method(:equal?)
25
+ NATIVE_COPY_STRING = String.method(:new)
26
+ NATIVE_ARRAY_EACH = Array.instance_method(:each)
27
+ NATIVE_HASH_EACH = Hash.instance_method(:each_pair)
28
+ NATIVE_HASH_DEFAULT = Hash.instance_method(:default)
29
+ NATIVE_HASH_DEFAULT_PROC = Hash.instance_method(:default_proc)
30
+ def native_is?(value, klass) = NATIVE_IS.bind_call(value, klass)
31
+ def native_same?(a, b) = NATIVE_EQUAL.bind_call(a, b)
32
+ def native_class(value) = NATIVE_CLASS.bind_call(value)
33
+ def native_class_name(value) = NATIVE_CLASS_NAME.bind_call(native_class(value))
34
+ def native_state(root, bindings: false, records: false)
35
+ seen = {}
36
+ nodes = 0
37
+ encode = nil
38
+ encode = lambda do |value, object_root = false|
39
+ nodes += 1
40
+ raise ArgumentError, 'native snapshot exceeds node bound' if nodes > 10000
41
+ return value if native_same?(value, nil) || native_same?(value, true) || native_same?(value, false)
42
+ return NATIVE_COPY_STRING.call(value).freeze if native_is?(value, String)
43
+ # Symbols cross the wire as native enum labels, never choice indexes.
44
+ return value.to_s if native_is?(value, Symbol)
45
+ if native_is?(value, Integer) || native_is?(value, Float)
46
+ raise ArgumentError, 'native snapshot number is outside exact integer range' unless value.finite? && value.abs <= 9007199254740991 && value == value.to_i
47
+ return value.to_i
48
+ end
49
+ # A store exposes its actual Hash, retaining keys and native identity.
50
+ value = value.data if native_is?(value, GdpStore)
51
+ unless NATIVE_OBJECTS.key?(value)
52
+ raise ArgumentError, 'native snapshot exceeds identity bound' if NATIVE_OBJECTS.length >= 100000
53
+ NATIVE_OBJECTS[value] = (NATIVE_OBJECTS.length + 1).to_s
54
+ end
55
+ id = NATIVE_OBJECTS[value]
56
+ return {'kind' => 'ref', 'id' => id} if seen[id]
57
+ seen[id] = true
58
+ if native_is?(value, Array)
59
+ kind, items = 'array', []
60
+ NATIVE_ARRAY_EACH.bind_call(value) { |v| items << encode.call(v) }
61
+ elsif native_is?(value, Hash)
62
+ raise ArgumentError, 'unsupported native Hash default' unless native_same?(NATIVE_HASH_DEFAULT.bind_call(value), nil) && native_same?(NATIVE_HASH_DEFAULT_PROC.bind_call(value), nil)
63
+ kind = object_root || records ? 'object' : 'map'
64
+ items = []
65
+ NATIVE_HASH_EACH.bind_call(value) do |k, v|
66
+ valid = object_root || records ? native_is?(k, String) : native_is?(k, String) || native_is?(k, Integer)
67
+ raise ArgumentError, 'unsupported native snapshot map key' unless valid
68
+ items << [encode.call(k), encode.call(v)]
69
+ end
70
+ else
71
+ # Opaque Time/IO/Mutex/etc. have no faithful wire encoding.
72
+ vars = NATIVE_VARS.bind_call(value)
73
+ # An uninitialized Ruby instance variable reads as nil. Observe that
74
+ # actual read for source-declared roots too (e.g. @last before first hit).
75
+ if native_same?(value, root) && !bindings
76
+ declared = (S['leaves'] || []).filter_map { |l| l['path']&.first if l['kind'] != 'frame' }
77
+ vars |= declared.filter_map { |name| name.to_sym if name.is_a?(String) && name.start_with?('@') }
78
+ end
79
+ raise ArgumentError, "unsupported native snapshot object #{native_class(value)}" if vars.empty? && native_class(value) != S['cls']
80
+ kind = 'object'
81
+ items = vars.map { |k| [k.to_s.delete_prefix('@'), encode.call(NATIVE_GET_VAR.bind_call(value, k))] }
82
+ end
83
+ {'kind' => kind, 'id' => id, 'items' => items}
84
+ end
85
+ {'version' => 1, 'root' => encode.call(root, bindings)}
86
+ end
14
87
 
88
+ # Invocation-local observations contain only values a native operation actually
89
+ # returned/raised. Missing calls stay absent; repeated inconsistent reads refuse.
90
+ NATIVE_EVENTS = [nil]
91
+ NATIVE_EVENT_ERROR = [nil]
92
+ NATIVE_CALL_TYPES = {}
93
+ NATIVE_ACTIVE_THREAD = [nil]
94
+ def native_active? = NATIVE_EVENTS[0] && native_same?(NATIVE_THREAD.call, NATIVE_ACTIVE_THREAD[0])
95
+ def native_scalar(value)
96
+ return value if native_same?(value, nil) || native_same?(value, true) || native_same?(value, false)
97
+ return NATIVE_COPY_STRING.call(value).freeze if native_is?(value, String)
98
+ return value.to_s.freeze if native_is?(value, Symbol)
99
+ if native_is?(value, Integer) || native_is?(value, Float)
100
+ raise ArgumentError, 'native observation number is outside exact integer range' unless value.finite? && value.abs <= 9007199254740991 && value == value.to_i
101
+ return value.to_i
102
+ end
103
+ raise ArgumentError, "unsupported native observation value #{native_class(value)}"
104
+ end
105
+ def native_record(key, outcome, native_type = nil)
106
+ return unless native_active? && (events = NATIVE_EVENTS[0])
107
+ before = events['calls'][key]
108
+ previous_type = NATIVE_CALL_TYPES[key]
109
+ if native_type && previous_type && !native_same?(native_type, previous_type)
110
+ raise ArgumentError, "inconsistent native call type #{key}"
111
+ end
112
+ NATIVE_CALL_TYPES[key] = native_type if native_type
113
+ raise ArgumentError, "inconsistent native call #{key}" if before && before != outcome
114
+ events['calls'][key] = outcome
115
+ rescue StandardError => e
116
+ NATIVE_EVENT_ERROR[0] ||= "#{e.class}: #{e.message}"[0, 300]
117
+ end
118
+ def native_call(key)
119
+ value = yield
120
+ if native_active?
121
+ begin
122
+ native_record(key, {'kind' => 'returned', 'value' => native_scalar(value)}, native_class(value))
123
+ rescue StandardError => e
124
+ NATIVE_EVENT_ERROR[0] ||= "#{e.class}: #{e.message}"[0, 300]
125
+ end
126
+ end
127
+ value
128
+ rescue Exception => e # Record the actual runtime class, never the requested handler.
129
+ native_record(key, {'kind' => 'raised', 'raised' => native_class_name(e)})
130
+ raise
131
+ end
132
+ def native_clock(value)
133
+ if native_active? && (events = NATIVE_EVENTS[0])
134
+ begin
135
+ actual = native_scalar(value)
136
+ raise ArgumentError, 'inconsistent native clock reads' if events.key?('clock') && events['clock'] != actual
137
+ events['clock'] = actual
138
+ rescue StandardError => e
139
+ NATIVE_EVENT_ERROR[0] ||= "#{e.class}: #{e.message}"[0, 300]
140
+ end
141
+ end
142
+ value
143
+ end
15
144
  module GdpClock
16
- def now(*) = Time.at(NOW[0])
145
+ def now(*)
146
+ value = Time.at(NOW[0])
147
+ native_clock(value.to_i)
148
+ value
149
+ end
17
150
  end
18
151
  Time.singleton_class.prepend(GdpClock)
19
152
  module GdpMono
20
- def clock_gettime(*a) = a.length > 1 && a[1] != :float_second ? NOW[0] : NOW[0].to_f
153
+ def clock_gettime(*a) = native_clock(a.length > 1 && a[1] != :float_second ? NOW[0] : NOW[0].to_f)
21
154
  end
22
155
  Process.singleton_class.prepend(GdpMono)
23
156
  # A clock object the caller stated: its time is the request's.
24
157
  class GdpStatedClock
25
- def current_time = NOW[0]
26
- def now = NOW[0]
158
+ def current_time = native_clock(NOW[0])
159
+ def now = native_clock(NOW[0])
27
160
  end
28
161
 
29
162
  def enc_num(v)
@@ -43,7 +176,7 @@ CUR = {}
43
176
  def answer(key) = (a = CUR[key]).nil? || a['none'] ? nil : build(a)
44
177
  # (a call inside a rescue's begin: raises the class the request says; one left out runs as it is unless it raises)
45
178
  def raising(key) = (r = CUR[key]&.[]('raise')) && raise(Object.const_get(r), 'gdp: raised where the request says')
46
- def stub(key) = proc { |*_a, **_k| raising(key); answer(key) }
179
+ def stub(key) = proc { |*_a, **_k| native_call(key) { raising(key); answer(key) } }
47
180
  # A store (stated, or an injected dependency inferred): get, set and delete over a Hash that keeps what is set; its
48
181
  # other methods answered.
49
182
  class GdpStore
@@ -171,9 +304,9 @@ def hello(req)
171
304
  next unless (mod = a['patch']['mod'])
172
305
  c = mod.split('::').reject(&:empty?).reduce(Object) { |o, n| o.const_defined?(n, false) ? o.const_get(n, false) : o.const_set(n, Module.new) }
173
306
  m, st, key = a['patch']['path'][-1], stub(a['key']), a['key']
174
- c.singleton_class.prepend(Module.new { a['pass'] ? define_method(m) { |*x, **k, &b| raising(key); super(*x, **k, &b) } : define_method(m, &st) })
307
+ c.singleton_class.prepend(Module.new { a['pass'] ? define_method(m) { |*x, **k, &b| native_call(key) { raising(key); super(*x, **k, &b) } } : define_method(m, &st) })
175
308
  end
176
- {'ok' => true}
309
+ {'ok' => true, 'nativeSnapshot' => 1, 'nativeBindings' => 1, 'nativeObservations' => 1, 'nativeEquality' => 'scalar'}
177
310
  end
178
311
  def make(specs)
179
312
  $stores = {}
@@ -187,20 +320,55 @@ def call(req)
187
320
  obj = OBJS[req['id']]
188
321
  NOW[0] = Integer(req['now'] || 0)
189
322
  CUR.replace(req['answers'] || {})
190
- m = obj.method(req['m'])
323
+ NATIVE_INVOCATION[0] += 1
324
+ raise ArgumentError, 'native invocation exceeds exact integer range' if NATIVE_INVOCATION[0] > 9007199254740991
325
+ NATIVE_EVENTS[0] = {'invocation' => NATIVE_INVOCATION[0], 'calls' => {}}
326
+ NATIVE_EVENT_ERROR[0] = nil
327
+ NATIVE_CALL_TYPES.clear
328
+ m = NATIVE_METHOD.bind_call(obj, req['m'])
191
329
  pos, kw = call_args(m, req['a'])
192
330
  before = frames(obj)
193
331
  snap = S['discard'] ? state_of(obj) : nil
194
332
  out, err = nil, nil
333
+ bindings = {'error' => 'native method entry was not observed'}
334
+ entered = false
335
+ # Defaults and keyword arguments are bound before :call. Read actual locals
336
+ # before the first body instruction, never the request's argument envelopes.
337
+ capture = TracePoint.new(:call) do |event|
338
+ next unless native_active?
339
+ next if entered || !native_same?(event.self, obj) || !native_same?(event.defined_class, m.owner) || !native_same?(event.method_id, m.original_name)
340
+ entered = true
341
+ begin
342
+ values = m.parameters.to_h do |kind, name|
343
+ raise ArgumentError, 'unsupported anonymous or block native parameter' if name.nil? || kind == :block
344
+ [name.to_s, event.binding.local_variable_get(name)]
345
+ end
346
+ bindings = {'snapshot' => native_state(values, bindings: true)}
347
+ rescue StandardError => e
348
+ bindings = {'error' => "#{e.class}: #{e.message}"[0, 300]}
349
+ end
350
+ end
195
351
  begin
352
+ NATIVE_ACTIVE_THREAD[0] = NATIVE_THREAD.call
353
+ capture.enable(target_thread: NATIVE_THREAD.call)
196
354
  out = traced { m.call(*pos, **kw) }
197
355
  rescue StandardError => e
198
356
  err = "#{e.class}: #{e.message}"[0, 300]
357
+ ensure
358
+ NATIVE_ACTIVE_THREAD[0] = nil
359
+ capture.disable
199
360
  end
200
361
  set_state(obj, snap) if err && snap
201
362
  after = frames(obj)
202
363
  before.each { |k, v| return {'frame' => k} if after[k] != v }
203
- {'out' => tag(out), **(err ? {'err' => err} : {})}
364
+ observations = begin
365
+ NATIVE_EVENT_ERROR[0] ? {'error' => NATIVE_EVENT_ERROR[0]} : {'snapshot' => native_state(NATIVE_EVENTS[0], bindings: true, records: true)}
366
+ rescue StandardError => e
367
+ {'error' => "#{e.class}: #{e.message}"[0, 300]}
368
+ ensure
369
+ NATIVE_EVENTS[0] = nil
370
+ end
371
+ {'out' => tag(out), 'nativeBindings' => bindings, 'nativeObservations' => observations, **(err ? {'err' => err} : {})}
204
372
  end
205
373
 
206
374
  fin, fout = File.open(ARGV[0], 'r'), File.open(ARGV[1], 'w')
@@ -226,6 +394,7 @@ fin.each_line do |line|
226
394
  {'bad' => "#{e.class}: #{e.message}"[0, 300]}
227
395
  end
228
396
  when 'get' then {'state' => state_of(OBJS[req['id']])}
397
+ when 'native' then {'snapshot' => native_state(OBJS[req['id']])}
229
398
  when 'call' then call(req)
230
399
  when 'coverage' then {'hit' => HIT.keys.sort.map { |n| [File.basename(S['path']), n] }}
231
400
  else {'error' => "no op #{op}"}
@@ -0,0 +1,35 @@
1
+ export type SearchTermination = {
2
+ kind: 'wall-deadline' | 'work-exhausted';
3
+ phase: string;
4
+ scope?: 'search' | 'stage';
5
+ };
6
+ export type SearchContext = {
7
+ goal?: string;
8
+ stuck?: string;
9
+ why?: string;
10
+ witness?: Record<string, number>;
11
+ };
12
+ export type SearchTerminationFields = {
13
+ stopped?: true;
14
+ termination?: SearchTermination;
15
+ context?: SearchContext;
16
+ };
17
+ export declare const searchContext: (v: SearchContext & SearchTerminationFields) => SearchContext;
18
+ export declare const terminationWhy: (t: SearchTermination) => string;
19
+ type Completion = {
20
+ proven: boolean;
21
+ checked: boolean;
22
+ run?: unknown;
23
+ kernelProven?: boolean;
24
+ translation?: string;
25
+ stopped?: boolean;
26
+ termination?: unknown;
27
+ stats?: {
28
+ stopped?: boolean;
29
+ termination?: unknown;
30
+ };
31
+ };
32
+ export declare const completedSourceRefusal: (v: Completion | undefined) => boolean;
33
+ export declare const completedSearch: (v: Completion | undefined) => boolean;
34
+ export declare const stoppedSearch: <T extends SearchContext & SearchTerminationFields>(v: T, termination: SearchTermination) => T & SearchTerminationFields;
35
+ export {};