gdp-wired 0.50.1 → 0.50.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +4 -2
  2. package/dist/core/cli.d.ts +12 -1
  3. package/dist/core/cli.js +64 -26
  4. package/dist/core/discover.d.ts +6 -1
  5. package/dist/core/discover.js +54 -7
  6. package/dist/core/dsl-deadline.d.ts +3 -0
  7. package/dist/core/dsl-deadline.js +26 -2
  8. package/dist/core/dsl.d.ts +3 -1
  9. package/dist/core/dsl.js +97 -32
  10. package/dist/core/effect.d.ts +12 -0
  11. package/dist/core/effect.js +26 -9
  12. package/dist/core/ex/harness.exs +171 -5
  13. package/dist/core/extract-c.js +64 -7
  14. package/dist/core/extract-check.d.ts +5 -1
  15. package/dist/core/extract-check.js +28 -10
  16. package/dist/core/extract-go-check.js +130 -3
  17. package/dist/core/extract-go.js +8 -2
  18. package/dist/core/extract-jvm.js +2 -2
  19. package/dist/core/extract-rs.js +51 -5
  20. package/dist/core/extract-step.js +49 -6
  21. package/dist/core/extract-swift.js +47 -3
  22. package/dist/core/extract.d.ts +9 -0
  23. package/dist/core/infer.d.ts +8 -0
  24. package/dist/core/infer.js +133 -16
  25. package/dist/core/jvm/Harness.java +135 -3
  26. package/dist/core/jvm/Rt.java +66 -4
  27. package/dist/core/laws.d.ts +4 -0
  28. package/dist/core/laws.js +59 -10
  29. package/dist/core/native-law.d.ts +3 -1
  30. package/dist/core/native-law.js +126 -14
  31. package/dist/core/native-observations.d.ts +20 -0
  32. package/dist/core/native-observations.js +41 -0
  33. package/dist/core/native-wire.d.ts +2 -0
  34. package/dist/core/native-wire.js +99 -0
  35. package/dist/core/py/harness.py +53 -2
  36. package/dist/core/rb/harness.rb +178 -9
  37. package/dist/core/search-termination.d.ts +35 -0
  38. package/dist/core/search-termination.js +13 -0
  39. package/dist/core/search-watchdog.d.ts +8 -0
  40. package/dist/core/search-watchdog.js +34 -0
  41. package/dist/core/source-check.d.ts +5 -0
  42. package/dist/core/source-check.js +21 -0
  43. package/dist/core/swift/Harness.swift +65 -4
  44. package/dist/core/swift/Main.swift +27 -4
  45. package/dist/core/wall.d.ts +3 -1
  46. package/dist/core/wall.js +7 -4
  47. package/dist/core/work-refusal.d.ts +3 -0
  48. package/dist/core/work-refusal.js +8 -0
  49. package/dist/kernel/prove.d.ts +2 -0
  50. package/dist/kernel/prove.js +13 -5
  51. package/dist/kernel/reader.js +5 -1
  52. package/dist/lean-kernel/axiom-audit.js +5 -2
  53. package/dist/lean-kernel/emit.d.ts +1 -0
  54. package/dist/lean-kernel/emit.js +22 -4
  55. package/package.json +1 -1
@@ -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,6 +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, snapshotNativeBindings } from "./native-wire.js";
31
+ import { nativeObservationSequence } from "./native-observations.js";
30
32
  import { nonneg } from "./extract-print.js";
31
33
  import { HarnessFailure, Outside, constantsOf, draw, drive, evalTerm, noEvidence, retried, tiesIn } from "./extract-check.js";
32
34
  // Bitwise and, or and xor of two naturals below 2^53 (JavaScript's operators stop at 32 bits).
@@ -6632,6 +6634,15 @@ function checkStepOnce(h, read, r, sorts, opts) {
6632
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 } : {}) });
6633
6635
  if (hi.error)
6634
6636
  return { ...empty, mismatch: `the code doesn't load with the check's harness: ${JSON.stringify(hi.error)}` };
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;
6635
6646
  const num = (x, at) => { const n = Number(x); if (typeof x === 'string' && Number.isSafeInteger(n) && String(n) === x)
6636
6647
  return n; throw new Outside(`${at} is ${String(x)}`); };
6637
6648
  const toSnap = (s) => {
@@ -6672,6 +6683,9 @@ function checkStepOnce(h, read, r, sorts, opts) {
6672
6683
  throw new Error(JSON.stringify(res.error)); return toSnap(res.state); },
6673
6684
  call: (self, e, args) => {
6674
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;
6675
6689
  if (res.outside !== undefined)
6676
6690
  return { ok: false, outside: true, error: res.outside };
6677
6691
  if (res.frame)
@@ -6712,6 +6726,32 @@ function checkStepOnce(h, read, r, sorts, opts) {
6712
6726
  }
6713
6727
  return { ok: true, value: o };
6714
6728
  },
6729
+ ...(native ? { nativeState: (self) => {
6730
+ const result = ask({ op: 'native', id: self });
6731
+ if (result.error)
6732
+ throw new Error(`native snapshot: ${JSON.stringify(result.error)}`);
6733
+ return native(result.snapshot);
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' } : {}),
6715
6755
  args: (inputs, e) => { inputsNow = inputs; return (read.args[e.call] ?? []).map(([n, a]) => [n, build(a, inputs)]); },
6716
6756
  setNow: n => { now = n; },
6717
6757
  coverage: () => (coverage ??= closeAndCount()),
@@ -6775,7 +6815,8 @@ function checkStepOnce(h, read, r, sorts, opts) {
6775
6815
  return { arms: arms.length, hit: arms.filter(a => hit.has(a)).length, missed: arms.filter(a => !hit.has(a)).map(a => `the arm at ${a}`) };
6776
6816
  }
6777
6817
  const ev = drive(m, r, sorts, side, o);
6778
- return { ...ev, runMs: Math.round(performance.now() - r0) };
6818
+ // The native journal is keyed by this exact evidence object.
6819
+ return Object.assign(ev, { runMs: Math.round(performance.now() - r0) });
6779
6820
  }
6780
6821
  catch (x) {
6781
6822
  if (x instanceof HarnessFailure)
@@ -6874,7 +6915,7 @@ export function stepNames(read) {
6874
6915
  for (const l of read.leaves) {
6875
6916
  const code = l.path.join('.');
6876
6917
  if (l.kind === 'map')
6877
- out.push({ code: l.orm ? l.name : l.store ?? code, rule: l.name, role: 'state', map: { fields: m.maps.find(d => d.name === l.name)?.fields.map(f => f.name) ?? [], ...(l.orm ? { store: l.orm.rec, tpl: '{}' } : l.store ? { store: l.store, tpl: l.tpl ?? '{}' } : {}), ...(l.ordered ? { ordered: true } : {}) } });
6918
+ out.push({ code: l.orm ? l.name : l.store ?? code, rule: l.name, role: 'state', map: { fields: m.maps.find(d => d.name === l.name)?.fields.map(f => f.name) ?? [], ...(l.orm ? { store: l.orm.rec, tpl: '{}' } : l.store ? { store: l.store, tpl: l.tpl ?? '{}' } : {}), ...(l.ordered ? { ordered: true, scalar: m.maps.find(d => d.name === l.name)?.scalar === true } : {}) } });
6878
6919
  else if (l.kind === 'none') {
6879
6920
  const n = at(code);
6880
6921
  if (n)
@@ -6908,9 +6949,11 @@ export function stepNames(read) {
6908
6949
  arg(a, code, 'input', method);
6909
6950
  for (const a of read.answers) {
6910
6951
  if (!a.pass)
6911
- out.push({ code: a.key, rule: a.inputs.name, role: 'answer', ...(a.inputs.none ? { none: a.inputs.none } : {}) });
6912
- for (const r of a.raises ?? [])
6913
- 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
+ }
6914
6957
  }
6915
6958
  const vars = new Set([...m.state, ...m.inputs].map(v => v.name));
6916
6959
  for (const [method, k] of Object.entries(read.results))
@@ -6921,7 +6964,7 @@ export function stepNames(read) {
6921
6964
  for (const a of read.answers.filter(x => x.effect && !x.quiet))
6922
6965
  out.push({ code: `${a.key}.called`, rule: `${a.key.replace(/\W+/g, '_')}_called`, role: 'result' });
6923
6966
  if (vars.has('now'))
6924
- out.push({ code: 'now', rule: 'now', role: 'clock' });
6967
+ out.push({ code: 'now', rule: 'now', role: 'clock', native: { kind: 'clock', key: 'now' } });
6925
6968
  if (m.event)
6926
6969
  out.push({ code: 'method', rule: m.event, role: 'method' });
6927
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,11 +61,20 @@ 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;
67
75
  tpl?: string;
68
76
  ordered?: boolean;
77
+ scalar?: boolean;
69
78
  };
70
79
  };
71
80
  export declare function namesOf(m: Model): Name[];
@@ -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: {
@@ -1,5 +1,8 @@
1
1
  import { retainFrom } from "./proof-output.js";
2
2
  import { searchNow as countedSearchNow, checkWorkEndpoint } from "./wall.js";
3
+ import { inWorkScope } from "../kernel/prove.js";
4
+ import { completedSearch, completedSourceRefusal, searchContext, stoppedSearch } from "./search-termination.js";
5
+ import { WatchdogExpired, checkWatchdog, withSearchWatchdog } from "./search-watchdog.js";
3
6
  // Invariants nobody wrote: a law that holds but isn't inductive, proven with laws the search finds. Nothing here is
4
7
  // trusted; what it finds is proven by the kernel with the rule's own laws, as laws of the same rule.
5
8
  // - runs: random runs from the start (params and requests by their kinds, the assumption met) give reachable states,
@@ -42,7 +45,7 @@ import { sampleStep } from "./sample-step.js";
42
45
  import { all, any, atMost, carriedView, compileC, compileE, cpair, fastStep, divisorsIn, evalC, evalE, get, hasFinite, interpret, machineTerms, fnValue, modName, n, not, partsOf as tupleOf, plus, same, seeded, times, walk, withArithmetic, x } from "./machine.js";
43
46
  import { bool, refuteModelByRuns, verdictOf } from "./dsl.js";
44
47
  import { allowed, keysOf, linKey, watch } from "./watch.js";
45
- import { clock, counted, fullWork, searchWork, decideLaw, decideNote, machineKey, memoHits, withStrict, fullRate, grow, keyValue, lawInstances, proveLaw, proveLaws, proveSetFast, proveStepLaws, stepLawInstances, usedHyps, withDeadline, withModels, withTrees, withWall, withSearchWork } from "../kernel/prove.js";
48
+ import { BudgetExpired, checkBudget, clock, counted, fullWork, searchWork, decideLaw, decideNote, machineKey, memoHits, withBudget, withStrict, fullRate, grow, keyValue, lawInstances, proveLaw, proveLaws, proveSetFast, proveStepLaws, stepLawInstances, usedHyps, withDeadline, withModels, withTrees, withWall, withSearchWork } from "../kernel/prove.js";
46
49
  import { assumed, eachParts, obligations, plainOf, stepLawObligations, substC, tuple, tupleParts } from "../kernel/kernel.js";
47
50
  import { env, gcd, work } from "./solver.js";
48
51
  import { bgcd } from "./q.js";
@@ -1023,19 +1026,84 @@ function comparisons(m, laws, atoms, coords, more = []) {
1023
1026
  return [...found.values()];
1024
1027
  }
1025
1028
  export function inferLaws(target, laws, stepLaws = [], opts = {}) {
1029
+ if (opts.work !== undefined && (opts.ms !== undefined || opts.wall !== undefined || opts.timed || opts.runsMs !== undefined))
1030
+ throw new RangeError('choose an explicit work budget or a legacy ms/wall/timed budget, not both');
1031
+ if (typeof opts.work === 'number' && (!Number.isFinite(opts.work) || opts.work < 0))
1032
+ throw new RangeError('work budget must be finite and nonnegative');
1026
1033
  // Repeated rounds and minimization can ask the same root goal again. Keep only
1027
1034
  // completed trees for this search, keyed by exact hypotheses and prover modes.
1028
- return withTrees(() => quietly(() => withDeadline(clock() + (opts.wall === undefined ? opts.ms ?? 20000 : Math.max(0, opts.wall - countedSearchNow())), () => inferLawsSearch(target, laws, stepLaws, opts))));
1035
+ const started = fullWork(), observed = {};
1036
+ let result;
1037
+ const run = () => {
1038
+ const enteredAt = countedSearchNow(), enteredWork = fullWork();
1039
+ observed.snapshot = () => ({ samples: 0, candidates: 0, alive: 0, proofs: 0, ms: Math.round(countedSearchNow() - enteredAt), work: Math.max(0, fullWork() - enteredWork), stopped: true });
1040
+ try {
1041
+ const out = withTrees(() => quietly(() => withDeadline(clock() + (opts.work === undefined ? (opts.wall === undefined ? opts.ms ?? 20000 : Math.max(0, opts.wall - countedSearchNow())) : Infinity), () => inferLawsSearch(target, laws, stepLaws, opts, observed))));
1042
+ // A completed source refusal is terminal, but never proof authority or
1043
+ // metadata to clean up. Preserve its exact object and refusal fields.
1044
+ if (completedSourceRefusal(out))
1045
+ return out;
1046
+ if (completedSearch(out)) {
1047
+ const { termination: _statsTermination, ...stats } = out.stats;
1048
+ const { stopped: _stopped, termination: _termination, context: _context, ...completed } = out;
1049
+ void _statsTermination;
1050
+ void _stopped;
1051
+ void _termination;
1052
+ void _context;
1053
+ return retainFrom({ ...completed, stats: { ...stats, stopped: false } }, [out]);
1054
+ }
1055
+ return out.stats.termination ? stoppedSearch({ ...out, context: observed.context?.() ?? searchContext(out) }, out.stats.termination) : out;
1056
+ }
1057
+ catch (error) {
1058
+ observed.last ??= observed.snapshot?.();
1059
+ observed.lastContext ??= observed.context?.();
1060
+ // A watchdog must not hide a rejected work admission while this work
1061
+ // owner is still active. This check does not admit or execute new work.
1062
+ if (error instanceof WatchdogExpired)
1063
+ checkBudget(error.termination.phase);
1064
+ throw error;
1065
+ }
1066
+ };
1067
+ try {
1068
+ return withSearchWatchdog(opts.watchdogMs, () => result = opts.work === undefined ? run() : withBudget(opts.work, run));
1069
+ }
1070
+ catch (error) {
1071
+ if (error instanceof WatchdogExpired) {
1072
+ checkBudget(error.termination.phase);
1073
+ checkWatchdog(error.termination.phase);
1074
+ }
1075
+ else if (error instanceof BudgetExpired)
1076
+ checkWorkEndpoint(error.phase);
1077
+ else
1078
+ throw error;
1079
+ if (error instanceof WatchdogExpired) {
1080
+ if (completedSearch(result) || result?.stopped && result.termination)
1081
+ return result;
1082
+ // Retained before final statistics/trace polls: those observations may
1083
+ // throw before the outer result assignment ever receives the verdict.
1084
+ if (observed.completed)
1085
+ return observed.completed;
1086
+ }
1087
+ const termination = error instanceof WatchdogExpired ? error.termination : { kind: 'work-exhausted', phase: error.phase, scope: 'search' };
1088
+ return { ...stoppedSearch({ ...result, ...opts.first, proven: false, checked: false, stuck: 'unknown', ...((observed.lastContext ?? observed.context?.()) ? { context: observed.lastContext ?? observed.context?.() } : {}) }, termination), found: [], stats: { ...(observed.last ?? result?.stats ?? { samples: 0, candidates: 0, alive: 0, proofs: 0, ms: 0, work: Math.max(0, fullWork() - started) }), stopped: true, termination } };
1089
+ }
1029
1090
  }
1030
- function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1031
- return withEvaluationAdmission(() => inferLawsSearchIn(target, laws, stepLaws, opts));
1091
+ function inferLawsSearch(target, laws, stepLaws, opts, observed) {
1092
+ try {
1093
+ return withEvaluationAdmission(() => inferLawsSearchIn(target, laws, stepLaws, opts, observed));
1094
+ }
1095
+ catch (error) {
1096
+ observed.last = observed.snapshot?.();
1097
+ observed.lastContext = observed.context?.();
1098
+ throw error;
1099
+ }
1032
1100
  }
1033
- function inferLawsSearchIn(target, laws, stepLaws, opts) {
1101
+ function inferLawsSearchIn(target, laws, stepLaws, opts, observed) {
1034
1102
  checkWorkEndpoint('inference entry');
1035
1103
  // (GDP_INFER_TRACE=2: each phase's progress too, to stderr)
1036
1104
  if (env.GDP_INFER_TRACE === '2' && !opts.progress)
1037
1105
  opts = { ...opts, progress: (phase, info) => globalThis.process.stderr.write(`[infer ${phase}] ${JSON.stringify(info)}\n`) };
1038
- const t0 = countedSearchNow(), ms = opts.ms ?? 20000, wallUntil = opts.wall ?? t0 + ms;
1106
+ const t0 = countedSearchNow(), work0 = fullWork(), ms = opts.work === undefined ? opts.ms ?? 20000 : Infinity, wallUntil = opts.work === undefined ? opts.wall ?? t0 + ms : Infinity;
1039
1107
  // Divisor declarations are mutable rule metadata. Keep a private copy even
1040
1108
  // when withSumsOf would return the original rule: candidate search and returned
1041
1109
  // remainder laws must not add arithmetic facts to the caller's next proof.
@@ -1044,8 +1112,18 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
1044
1112
  const timed = !!opts.timed, w0 = work.n, used = { tries: 0, rows: 0, evals: 0, watched: 0, erows: 0, etries: 0 };
1045
1113
  const now = () => (timed ? countedSearchNow() - t0
1046
1114
  : used.tries / inferRates.tries + used.rows / inferRates.rows + used.evals / inferRates.evals + used.watched / inferRates.watched + (work.n - w0) / inferRates.work);
1047
- let stopped = false;
1048
- const stop = () => { checkWorkEndpoint('inference poll'); return stopped || (stopped = countedSearchNow() > wallUntil); };
1115
+ // searchNow's domain is captured with this endpoint, before nested counted
1116
+ // proof calls can change it. Do not classify a stop from stats.ms or its text.
1117
+ const stopDomain = inWorkScope() ? 'counted' : 'real';
1118
+ let stopped = false, termination;
1119
+ const stop = () => {
1120
+ checkWorkEndpoint('inference poll');
1121
+ if (!stopped && countedSearchNow() > wallUntil) {
1122
+ stopped = true;
1123
+ termination = { kind: stopDomain === 'real' ? 'wall-deadline' : 'work-exhausted', phase: 'inference poll', scope: 'stage' };
1124
+ }
1125
+ return stopped;
1126
+ };
1049
1127
  // The engine's clock (the stage below, from the small instance on): counted as `now` is, with the EPR path's work
1050
1128
  // (kernel/epr.ts's eprMeter) and the views' rows beside it, so that every choice it makes by its budget (a BFS cut, the
1051
1129
  // filter, a goal's cap, a round's growth) is the same on any machine; the wall (`stop`, `until` past `ms`) only ends it.
@@ -1074,6 +1152,10 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
1074
1152
  }
1075
1153
  const m = rule ? rule.machine : target;
1076
1154
  let proofs = 0;
1155
+ let sampleCount = () => 0, candidateCount = () => 0, aliveCount = () => 0;
1156
+ // Read actual partial counters while their owning clock scope is still live.
1157
+ // Before an array exists its observed population is genuinely zero.
1158
+ observed.snapshot = () => ({ samples: sampleCount(), candidates: candidateCount(), alive: aliveCount(), proofs, ms: Math.round(countedSearchNow() - t0), work: Math.max(0, fullWork() - work0), stopped: true });
1077
1159
  // The rule (or machine) the kernel proves the candidates with: once a remainder is among them, one that declares
1078
1160
  // div$k and mod$k for its divisors (all declarations stay on the private rule copy).
1079
1161
  // Only the laws proven read: a search none of whose chosen candidates is a remainder proves with the rule as it is.
@@ -1100,16 +1182,33 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
1100
1182
  const model = normalized?.machine ?? mm;
1101
1183
  const given = normalized ? [...normalized.kindLaws().filter(k => !ls.some(l => l.name === k.name)), ...ls] : ls;
1102
1184
  const out = stepLaws.length ? proveStepLaws(model, given, stepLaws) : (fast ? proveSetFast : proveLaws)(model, given);
1103
- return verdictOf(out);
1185
+ const verdict = verdictOf(out);
1186
+ // Engine callbacks can observe a completed whole family before enumProof
1187
+ // or last receives it. Retain only a proof of EVERY caller law, with the
1188
+ // exact additional laws it used; a proved candidate alone is not success.
1189
+ if (verdict.proven && verdict.checked && laws.every(law => ls.includes(law)))
1190
+ observed.completed = retainFrom({ ...verdict, found: ls.filter(law => !laws.includes(law)).map(law => ({ law, text: law.name })), stats: completedStats(sampleCount(), candidateCount(), aliveCount()) }, [verdict], { kind: 'inference', original: m, laws });
1191
+ return verdict;
1192
+ };
1193
+ const completedStats = (samples, candidates, alive) => ({ samples, candidates, alive, proofs, ms: Math.round(countedSearchNow() - t0), work: Math.max(0, fullWork() - work0), stopped: false });
1194
+ const stats = (samples, candidates, alive) => {
1195
+ stop();
1196
+ // This is the actual local search-budget predicate, not reported elapsed
1197
+ // time. wall:Infinity disables only the separate scheduling stop.
1198
+ if (!termination && now() >= until)
1199
+ termination = { kind: timed && stopDomain === 'real' ? 'wall-deadline' : 'work-exhausted', phase: 'inference allowance', scope: 'stage' };
1200
+ return { samples, candidates, alive, proofs, ms: Math.round(countedSearchNow() - t0), work: Math.max(0, fullWork() - work0), stopped: stopped || termination !== undefined, ...(termination ? { termination } : {}) };
1104
1201
  };
1105
- const stats = (samples, candidates, alive) => ({ samples, candidates, alive, proofs, ms: Math.round(countedSearchNow() - t0), stopped: stop() });
1106
1202
  // The old public prover's first pass also sampled reachable counterexamples.
1107
1203
  // Keep that negative model evidence without invoking a source finalizer.
1108
1204
  const refuted = !opts.first && !opts.cubes && rule ? refuteModelByRuns(rule, laws, stepLaws) : undefined;
1109
1205
  const first = opts.first ?? (refuted?.run ? { proven: false, checked: false, stuck: 'sat', ...refuted }
1110
1206
  : opts.cubes ? { proven: false, checked: false } : prove(laws));
1111
- if ((first.proven && first.checked) || first.run)
1112
- return retainFrom({ ...first, found: [], stats: stats(0, 0, 0) }, [first]);
1207
+ observed.context = () => searchContext(first);
1208
+ if ((first.proven && first.checked) || first.run) {
1209
+ const completed = observed.completed = retainFrom({ ...first, found: [], stats: completedStats(0, 0, 0) }, [first]);
1210
+ return retainFrom({ ...completed, stats: stats(0, 0, 0) }, [completed]);
1211
+ }
1113
1212
  // --- runs ------------------------------------------------------------------------------------------------------------
1114
1213
  const run = interpret(m), stepSample = sampleStep(m, run), rand = seeded(17), kinds = rule ? rule.kindsOfState() : [];
1115
1214
  const given = rule ? [...rule.kindLaws().filter(k => !laws.some(l => l.name === k.name)), ...laws] : laws;
@@ -1118,6 +1217,7 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
1118
1217
  : { ...Object.fromEntries(m.inputs.map(i => [i, r(bound + 1)])), ...Object.fromEntries((m.inputMaps ?? []).map(i => [i, new Map()])) });
1119
1218
  // (each state once: a machine with no requests walks one path, and its copies pushed out the caller's states (opts.seen))
1120
1219
  const samples = [], cap = 3000, keys = [], held = new Set();
1220
+ sampleCount = () => samples.length;
1121
1221
  const mapsText = (st) => JSON.stringify(Object.values(st.maps).map(c => [...c]));
1122
1222
  let offered = 0;
1123
1223
  // (how many states offered held each value of each state variable: `rare`, below)
@@ -1418,6 +1518,7 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
1418
1518
  }
1419
1519
  const sizeOf = (coef) => coef.length * 100 + coef.reduce((s, [, c]) => s + Math.abs(c), 0);
1420
1520
  const forms = [];
1521
+ candidateCount = () => forms.length;
1421
1522
  const NS = rowsS.length, NK = rowsK.length;
1422
1523
  const at = (coef, vals, j) => { observeCubeTest(); let s = 0; for (const [i, c] of coef)
1423
1524
  s += c * vals[i][j]; return s; };
@@ -1894,6 +1995,7 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
1894
1995
  tupleMaps.add(String(o.map)); });
1895
1996
  const plainKeyed = (f) => f.view !== undefined || !atomsIn(f).some(i => atoms[i].cell && tupleMaps.has(atoms[i].parts[0][0]));
1896
1997
  let alive = forms.filter(plainKeyed).sort((p, q) => p.size - q.size).slice(0, maxCandidates);
1998
+ aliveCount = () => alive.length;
1897
1999
  const ctis = [];
1898
2000
  // (a law about keys is evaluated at every tuple of the state's keys, as watch does: counted as that many evaluations)
1899
2001
  const lawful = (params, st) => {
@@ -1979,6 +2081,8 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
1979
2081
  let enumSome = [];
1980
2082
  const goalName = (g) => g.replace(/ @[^@]*$/, '');
1981
2083
  let last = first;
2084
+ // Keep the original first verdict immutable; later candidate failures must
2085
+ // not replace its SAT/goal/witness provenance.
1982
2086
  const slow = Math.max(3000, ms / 10);
1983
2087
  // A point a form is false at; a cell form is judged only at rows that read every map it reads.
1984
2088
  const reads = (f, r) => f.coef.every(([i]) => !atoms[i].cell || atoms[i].parts.every(([q]) => AT + q in r));
@@ -5247,12 +5351,20 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
5247
5351
  };
5248
5352
  // A cell form's mirror, −Σ ≤ −d beside Σ ≤ d under the same guard (its text).
5249
5353
  const mirrorText = (f) => (!f.cells || f.mod || f.cong || f.never || f.nevers || f.cube || f.unreachable || f.also || !f.coef.length ? undefined : textOf({ ...f, coef: f.coef.map(([i, c]) => [i, -c]), d: -f.d }));
5250
- if (enumProof)
5354
+ // Keep the checked family and its exact supports/custody before any local
5355
+ // progress, minimization, trace or statistics observation can stop us. A
5356
+ // later actual work refusal still propagates; this is not budget authority.
5357
+ const captureCompleted = () => observed.completed = retainFrom({ ...last, found: [...chosen.map(f => { const law = lawFor(f), text = law.name, source = sourceOf(f, text); return { law, text, ...(source ? { source } : {}) }; }), ...(enumProof ? enumSome : []).map(law => ({ law, text: law.name }))], stats: completedStats(samples.length, forms.length, alive.length) }, [last], { kind: 'inference', original: m, laws });
5358
+ if (enumProof) {
5251
5359
  last = enumProof;
5360
+ captureCompleted();
5361
+ }
5252
5362
  for (let iter = 0; iter < 300 && !enumProof && now() < until && !stop(); iter++) {
5253
5363
  const began = now(), wall = countedSearchNow();
5254
5364
  // (each law proven alone, then the set as a whole: the same goals, grown once)
5255
5365
  last = withTrees(() => search([...given, ...chosen.map(lawFor)]));
5366
+ if (last.proven && last.checked)
5367
+ captureCompleted();
5256
5368
  const took = now() - began;
5257
5369
  opts.progress?.('proof', { chosen: chosen.length, goal: last.goal ?? '', stuck: last.stuck ?? '', ms: Math.round(countedSearchNow() - wall), counted: Math.round(took) });
5258
5370
  if (last.proven && last.checked)
@@ -5321,6 +5433,7 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
5321
5433
  if (v.proven && v.checked) {
5322
5434
  chosen = [f];
5323
5435
  last = v;
5436
+ captureCompleted();
5324
5437
  break;
5325
5438
  }
5326
5439
  }
@@ -5335,12 +5448,16 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
5335
5448
  if (now() > until || stop())
5336
5449
  break;
5337
5450
  const without = chosen.filter(g => g !== f), v = prove([...laws, ...without.map(lawFor)]);
5338
- if (v.proven && v.checked)
5339
- (chosen = without, last = v);
5451
+ if (v.proven && v.checked) {
5452
+ chosen = without;
5453
+ last = v;
5454
+ captureCompleted();
5455
+ }
5340
5456
  }
5341
5457
  const kept = chosen.flatMap(f => (f.mod ? [f.mod.k] : []));
5342
5458
  if (kept.length)
5343
5459
  rule?.dividesBy(...kept);
5460
+ const completed = captureCompleted();
5344
5461
  trace('end', { proven: true, stopped: stop(), found: chosen.map(f => textOf(f)).join('; ') });
5345
- return retainFrom({ ...last, found: [...chosen.map(f => { const law = lawFor(f), text = law.name, source = sourceOf(f, text); return { law, text, ...(source ? { source } : {}) }; }), ...(enumProof ? enumSome : []).map(law => ({ law, text: law.name }))], stats: stats(samples.length, forms.length, alive.length) }, [last], { kind: 'inference', original: m, laws });
5462
+ return retainFrom({ ...completed, stats: stats(samples.length, forms.length, alive.length) }, [completed]);
5346
5463
  }