gdp-wired 0.51.0 → 0.52.0

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 +2 -2
  2. package/dist/core/accel-refute.d.ts +53 -0
  3. package/dist/core/accel-refute.js +997 -0
  4. package/dist/core/cli.d.ts +2 -0
  5. package/dist/core/cli.js +8 -1
  6. package/dist/core/cycles.d.ts +2 -0
  7. package/dist/core/cycles.js +12 -9
  8. package/dist/core/dsl.d.ts +7 -1
  9. package/dist/core/dsl.js +147 -26
  10. package/dist/core/live-support.d.ts +5 -0
  11. package/dist/core/live-support.js +148 -0
  12. package/dist/core/live.js +194 -37
  13. package/dist/core/lockstep.d.ts +5 -0
  14. package/dist/core/lockstep.js +23 -0
  15. package/dist/core/ordered-pair-seeds.d.ts +2 -0
  16. package/dist/core/ordered-pair-seeds.js +109 -0
  17. package/dist/core/proof-output.d.ts +38 -1
  18. package/dist/core/proof-output.js +38 -0
  19. package/dist/core/search-termination.d.ts +4 -0
  20. package/dist/core/search-termination.js +1 -1
  21. package/dist/core/source-check.d.ts +4 -1
  22. package/dist/core/source-check.js +5 -2
  23. package/dist/core/sparse-kind-proof.d.ts +7 -0
  24. package/dist/core/sparse-kind-proof.js +49 -0
  25. package/dist/core/step-seeds.d.ts +46 -0
  26. package/dist/core/step-seeds.js +316 -0
  27. package/dist/lean-kernel/Cert.lean +222 -0
  28. package/dist/lean-kernel/Count.lean +1568 -0
  29. package/dist/lean-kernel/Ghost.lean +373 -0
  30. package/dist/lean-kernel/GhostMap.lean +426 -0
  31. package/dist/lean-kernel/Kernel.lean +2881 -0
  32. package/dist/lean-kernel/Live.lean +1168 -0
  33. package/dist/lean-kernel/Progress.lean +543 -0
  34. package/dist/lean-kernel/Sets.lean +1975 -0
  35. package/dist/lean-kernel/StepLaw.lean +128 -0
  36. package/dist/lean-kernel/Steps.lean +477 -0
  37. package/dist/lean-kernel/Sums.lean +916 -0
  38. package/dist/lean-kernel/emit.d.ts +4 -0
  39. package/dist/lean-kernel/emit.js +23 -4
  40. package/dist/lean-kernel/lean-aggregate/FiniteFold.lean +44 -0
  41. package/dist/lean-kernel/lean-aggregate/GroupedTransport.lean +308 -0
  42. package/dist/lean-kernel/lean-aggregate/aggregate.d.ts +13 -0
  43. package/dist/lean-kernel/lean-aggregate/aggregate.js +68 -0
  44. package/dist/lean-kernel/lean-aggregate/assets.d.ts +5 -0
  45. package/dist/lean-kernel/lean-aggregate/assets.js +7 -0
  46. package/dist/lean-kernel/lean-aggregate/audit.d.ts +3 -0
  47. package/dist/lean-kernel/lean-aggregate/audit.js +13 -0
  48. package/dist/lean-kernel/lean-aggregate/exact.d.ts +15 -0
  49. package/dist/lean-kernel/lean-aggregate/exact.js +51 -0
  50. package/dist/lean-kernel/lean-aggregate/index.d.ts +19 -0
  51. package/dist/lean-kernel/lean-aggregate/index.js +52 -0
  52. package/dist/lean-kernel/lean-aggregate/point-fold.d.ts +27 -0
  53. package/dist/lean-kernel/lean-aggregate/point-fold.js +79 -0
  54. package/dist/lean-kernel/lean-aggregate/replay-fold.d.ts +2 -0
  55. package/dist/lean-kernel/lean-aggregate/replay-fold.js +163 -0
  56. package/dist/lean-kernel/lean-aggregate/source.d.ts +2 -0
  57. package/dist/lean-kernel/lean-aggregate/source.js +141 -0
  58. package/dist/lean-kernel/lean-aggregate/weighted-flags.d.ts +2 -0
  59. package/dist/lean-kernel/lean-aggregate/weighted-flags.js +26 -0
  60. package/dist/lean-kernel/lean-aggregate/weighted-replay.d.ts +7 -0
  61. package/dist/lean-kernel/lean-aggregate/weighted-replay.js +53 -0
  62. package/dist/lean-kernel/lean-aggregate/weighted-seeded.d.ts +30 -0
  63. package/dist/lean-kernel/lean-aggregate/weighted-seeded.js +64 -0
  64. package/dist/lean-kernel/lean-aggregate/weighted.d.ts +18 -0
  65. package/dist/lean-kernel/lean-aggregate/weighted.js +115 -0
  66. package/dist/lean-kernel/lean-aggregate/worker.d.ts +10 -0
  67. package/dist/lean-kernel/lean-aggregate/worker.js +46 -0
  68. package/docs/lean-aggregate.md +29 -0
  69. package/package.json +6 -1
@@ -0,0 +1,27 @@
1
+ import { type C, type E, type Law, type Machine } from '../../core/machine.js';
2
+ import { type Goal, type Tree } from '../../kernel/kernel.js';
3
+ import { type FilteredCounterProposal } from './aggregate.js';
4
+ export type Scope = 'plain' | 'row';
5
+ export type Local = {
6
+ name: string;
7
+ assumptions: C[];
8
+ conclusion: C;
9
+ scope: Scope;
10
+ };
11
+ export type FoldTheory = {
12
+ locals: Local[];
13
+ bound: E;
14
+ coordinate: string;
15
+ point: E;
16
+ proposal: FilteredCounterProposal;
17
+ };
18
+ export type FoldPacket = {
19
+ kind: 'point-fold';
20
+ machine: Machine;
21
+ laws: Law[];
22
+ trees: Record<string, Tree>;
23
+ };
24
+ export declare function foldTheory(m: Machine, law: Law): FoldTheory | undefined;
25
+ export declare function provePointFold(m: Machine, law: Law, ms: number): FoldPacket | undefined;
26
+ export declare function checkPointFold(packet: FoldPacket): boolean;
27
+ export declare const localGoal: (l: Local) => Goal;
@@ -0,0 +1,79 @@
1
+ // A local certificate schema, outside the trusted checker. Its finite-fold
2
+ // composition and binding to the original step are checked in Lean.
3
+ import { atMost, get, n, not, plus, same, x } from "../../core/machine.js";
4
+ import { check, substC, substE } from "../../kernel/kernel.js";
5
+ import { clock, grow, withWall } from "../../kernel/prove.js";
6
+ import { searchWall } from "../../core/wall.js";
7
+ import { proposeFilteredCounters } from "./aggregate.js";
8
+ const zero = n(0);
9
+ const lt = (a, b) => ({ op: '<', a, b });
10
+ const iff = (c, then, otherwise) => ({ op: 'if', c, then, else: otherwise });
11
+ const toGoal = (l) => ({ name: l.name, hyps: [...l.assumptions, not(l.conclusion)] });
12
+ export function foldTheory(m, law) {
13
+ // Closed fragment for source binding: one source map, no carried maps, no
14
+ // external facts or special postprocessing. Unrecognized syntax falls back.
15
+ if (m.facts?.length || Object.keys(m.fns ?? {}).length || m.inputMaps?.length || Object.keys(m.maps ?? {}).length !== 1 || Object.keys(m.step.maps ?? {}).length !== 1)
16
+ return;
17
+ const p = proposeFilteredCounters(m, law)[0];
18
+ if (!p || p.fields.length < 2 || p.fields.length > 6 || !m.assume || p.bound.op !== 'var' || !m.params.includes(p.bound.name))
19
+ return;
20
+ const wr = m.step.maps[p.map];
21
+ if (!('each' in wr))
22
+ return;
23
+ const occupied = JSON.stringify([m, law]);
24
+ let local = 'agg$coordinate';
25
+ while (occupied.includes(local))
26
+ local += '0';
27
+ const j = x(local), input = x(p.key);
28
+ const plusOffset = (k) => p.offset ? plus(k, n(p.offset)) : k;
29
+ const point = p.offset ? { op: 'sub', a: input, b: n(p.offset) } : input;
30
+ const flags = Object.create(null);
31
+ for (const [name, c] of Object.entries(m.step.flags ?? {})) {
32
+ if (c.op === 'all')
33
+ return;
34
+ flags[name] = substC(c, { vars: {}, maps: {}, flags });
35
+ }
36
+ const inline = { vars: {}, maps: {}, flags };
37
+ const assume = substC(m.assume, inline), reset = substC(p.reset, inline), after = (k) => substE(wr.value, { ...inline, vars: { [wr.each]: k } });
38
+ const plain = (name, assumptions, conclusion) => ({ name, assumptions, conclusion, scope: 'plain' });
39
+ const row = (name, assumptions, conclusion) => ({ name, assumptions, conclusion, scope: 'row' });
40
+ const coord = plusOffset(j), atPoint = plusOffset(point);
41
+ const locals = [
42
+ plain('point_inside', [assume], lt(point, p.bound)),
43
+ row('other_cells_frame', [assume, not(reset), not(same(j, point))], same(after(coord), get(p.map, coord))),
44
+ row('broadcast_reset', [assume, reset], same(after(coord), n(m.maps[p.map]))),
45
+ plain('capacity_entails_claim', [atMost(p.fields.map(f => x(f.field)).reduce(plus), p.bound)], law.holds),
46
+ ];
47
+ for (const [i, f] of p.fields.entries()) {
48
+ const next = substE(m.step.state[f.field], inline);
49
+ const indicator = (cell) => iff(same(cell, n(f.value)), n(1), zero);
50
+ locals.push(plain(`field${i}_init`, [], same(m.state[f.field], zero)), plain(`field${i}_reset`, [assume, reset], same(next, zero)), plain(`field${i}_delta`, [assume, not(reset)], same(plus(next, indicator(get(p.map, atPoint))), plus(x(f.field), indicator(after(atPoint))))));
51
+ }
52
+ const classified = p.fields.map(f => iff(same(get(p.map, coord), n(f.value)), n(1), zero)).reduce(plus);
53
+ locals.push(row('disjoint_capacity', [], atMost(classified, n(1))));
54
+ return { locals, coordinate: local, bound: p.bound, point, proposal: p };
55
+ }
56
+ export function provePointFold(m, law, ms) {
57
+ const theory = foldTheory(m, law);
58
+ if (!theory || ms <= 0)
59
+ return;
60
+ return withWall(searchWall(ms), () => {
61
+ const until = clock() + ms, trees = Object.create(null);
62
+ for (const local of theory.locals) {
63
+ const out = grow(toGoal(local), new Map(), { nodes: 0, until });
64
+ if (!('tree' in out))
65
+ return;
66
+ trees[local.name] = out.tree;
67
+ }
68
+ const packet = { kind: 'point-fold', machine: m, laws: [law], trees };
69
+ return checkPointFold(packet) ? packet : undefined;
70
+ });
71
+ }
72
+ export function checkPointFold(packet) {
73
+ const t = packet.laws.length === 1 && foldTheory(packet.machine, packet.laws[0]);
74
+ return !!t && Object.keys(packet.trees).length === t.locals.length && t.locals.every(local => {
75
+ const tree = Object.hasOwn(packet.trees, local.name) && packet.trees[local.name];
76
+ return !!tree && check(toGoal(local), tree);
77
+ });
78
+ }
79
+ export const localGoal = toGoal;
@@ -0,0 +1,2 @@
1
+ import { type FoldPacket } from './point-fold.js';
2
+ export declare function emitPointFold(packet: FoldPacket): string;
@@ -0,0 +1,163 @@
1
+ import assert from 'node:assert/strict';
2
+ import { encode, machineLit } from "../../lean-kernel/emit.js";
3
+ import { leanTerms } from "../../lean-kernel/lean-terms.js";
4
+ import { checkPointFold, foldTheory, localGoal } from "./point-fold.js";
5
+ export function emitPointFold(packet) {
6
+ assert(checkPointFold(packet));
7
+ const { machine: m, laws: [law] } = packet, theory = foldTheory(m, law);
8
+ const { proposal: p, coordinate, locals, point } = theory;
9
+ const writes = m.step.maps[p.map];
10
+ assert('each' in writes);
11
+ assert(theory.bound.op === 'var');
12
+ const names = [...new Set([...m.params, ...m.inputs, ...Object.keys(m.state), ...Object.keys(m.step.flags ?? {}).map(f => `?${f}`), writes.each, coordinate])];
13
+ const maps = [p.map], t = leanTerms(names, maps, 'finite fold'), ix = (x) => { const i = names.indexOf(x); assert(i >= 0, x); return i; }, mx = (name) => { assert.equal(name, p.map); return 0; };
14
+ const certs = locals.map(loc => {
15
+ const goal = localGoal(loc), cert = encode({ name: loc.name, goal, tree: packet.trees[loc.name] }, false, true, names, maps);
16
+ const hypotheses = loc.assumptions.map((h, i) => ` (h${i} : holdsC env maps (${t.c(h)}))`).join('');
17
+ const choices = Array.from({ length: goal.hyps.length }, () => 'rfl').join(' | ');
18
+ return `def ${loc.name}_goal : Kern.Goal := ⟨${cert.tab}, ${cert.hyps}⟩
19
+ def ${loc.name}_tree : Kern.Tree := ${cert.tree}
20
+ theorem ${loc.name}_check : checkGoal ${loc.name}_goal ${loc.name}_tree = true := by decide +kernel
21
+ theorem checked_${loc.name} (env : Nat → Nat) (maps : Nat → Nat → Nat)${hypotheses} :
22
+ holdsC env maps (${t.c(loc.conclusion)}) := by
23
+ apply Classical.byContradiction
24
+ intro h
25
+ apply sound ${loc.name}_goal ${loc.name}_tree ${loc.name}_check env maps
26
+ intro c hc
27
+ simp only [${loc.name}_goal, List.mem_cons, List.mem_nil_iff, or_false] at hc
28
+ ${goal.hyps.length === 1 ? ' subst c' : ` rcases hc with ${choices}`}
29
+ ${loc.assumptions.map((_, i) => ` · exact (evalC_iff env maps _).2 h${i}`).join('\n')}
30
+ ${loc.assumptions.length ? '· ' : ''}exact (evalC_iff env maps _).2 h`;
31
+ }).join('\n\n');
32
+ const boundIx = ix(theory.bound.name), addr = (v) => p.offset ? `(${v} + ${p.offset})` : v;
33
+ const sem = 'src, before, applyS, assoc, lookup, evalE, evalC, holdsC, upd, everyMaps, decideFlags, flagSub, withInputs, -List.elem_eq_contains';
34
+ const shift = (v) => `(upd X ${ix(coordinate)} ${v})`;
35
+ const stepvars = '(ρ : Nat → Nat) (M : Nat → Nat → Nat) (ι : Nat → Nat) (κ : Nat → Nat → Nat)';
36
+ const prev = '(before ρ ι)', next = '(sNext src ρ M ι κ)';
37
+ const cap = p.fields.map(f => `ρ ${ix(f.field)}`).reduce((a, b) => `(${a} + ${b})`);
38
+ const classBody = (mp) => p.fields.map(f => `countCell ${f.value} ${mp} j`).reduce((a, b) => `(${a} + ${b})`);
39
+ const bindStep = (f, i) => `
40
+ · have h0 : (applyS src.f.m.init ρ M) ${ix(f.field)} = 0 := by
41
+ simpa [${sem}] using checked_field${i}_init ρ M
42
+ change (applyS src.f.m.init ρ M) ${ix(f.field)} = sumBelow (countCell ${f.value} M) (applyS src.f.m.init ρ M ${boundIx})
43
+ rw [h0]
44
+ apply Eq.symm
45
+ exact zeroSum _ _ (by intro j; simp [countCell, hMap])`;
46
+ return `import FiniteFold
47
+ import Ghost
48
+ open Kern FiniteFold
49
+ set_option maxRecDepth 30000
50
+ set_option maxHeartbeats 0
51
+ set_option linter.unusedSimpArgs false
52
+
53
+ def src : SMachine := ${machineLit(m, t, ix, mx)}
54
+ def original : C := ${t.c(law.holds)}
55
+ def before (ρ ι : Nat → Nat) : Nat → Nat := withInputs src.f.m.inputs ρ ι
56
+ def point (X : Nat → Nat) (M : Nat → Nat → Nat) := evalE X M (${t.e(point)})
57
+ def countCell (tag : Nat) (M : Nat → Nat → Nat) (j : Nat) : Nat := if M 0 ${addr('j')} = tag then 1 else 0
58
+
59
+ def Coupled (ρ : Nat → Nat) (M : Nat → Nat → Nat) : Prop :=
60
+ ${p.fields.map(f => `(ρ ${ix(f.field)} = sumBelow (countCell ${f.value} M) (ρ ${boundIx}))`).join(' ∧ ')}
61
+
62
+ theorem zeroSum (f : Nat → Nat) (N : Nat) (h : ∀ j, f j = 0) : sumBelow f N = 0 := by
63
+ rw [← sumBelow_zero_fn N]
64
+ exact sumBelow_congr N (fun j _ => h j)
65
+
66
+ theorem view_eq ${stepvars} :
67
+ sView src ρ M ι κ = (decideFlags src.f.flags ${prev} M, M) := by
68
+ have hm : withCarried src M κ = M := by funext i j; rfl
69
+ have hv : decideQ src ${prev} M = ${prev} := by funext i; simp [decideQ_of, src, lookup]
70
+ simp only [sView, hm]
71
+ change (decideFlags src.f.flags (decideQ src (before ρ ι) M) M, M) = _
72
+ rw [hv]
73
+
74
+ theorem assume_eq ${stepvars}
75
+ (h : evalC (sView src ρ M ι κ).1 (sView src ρ M ι κ).2 src.f.m.assume = true) :
76
+ holdsC ${prev} M (${t.c(locals[0].assumptions[0])}) := by
77
+ rw [view_eq] at h
78
+ simpa [${sem}] using h
79
+
80
+ theorem bound_next ${stepvars} : ${next}.1 ${boundIx} = ρ ${boundIx} := by
81
+ simp only [sNext, view_eq, Prod.fst, Prod.snd]
82
+ simp [${sem}]
83
+
84
+ theorem bound_before (ρ ι : Nat → Nat) : ${prev} ${boundIx} = ρ ${boundIx} := by rfl
85
+ ${certs}
86
+
87
+ theorem coupled_init (ρ : Nat → Nat) (M : Nat → Nat → Nat) (hm : StartMaps src.f.m M) :
88
+ Coupled (applyS src.f.m.init ρ M) M := by
89
+ have hMap (j : Nat) : M 0 j = ${m.maps[p.map]} := hm (0,${m.maps[p.map]}) (by simp [src]) j
90
+ unfold Coupled
91
+ refine ⟨${p.fields.map(() => '?_').join(', ')}⟩
92
+ ${p.fields.map(bindStep).join('')}
93
+
94
+ theorem coupled_next ${stepvars}
95
+ (hold : Coupled ρ M) (adm : evalC (sView src ρ M ι κ).1 (sView src ρ M ι κ).2 src.f.m.assume = true) :
96
+ Coupled ${next}.1 ${next}.2 := by
97
+ let X := before ρ ι
98
+ let N := ρ ${boundIx}
99
+ let q := point X M
100
+ let ρ' := ${next}.1
101
+ let M' := ${next}.2
102
+ have hn : ρ' ${boundIx} = N := bound_next ρ M ι κ
103
+ have hb : X ${boundIx} = N := bound_before ρ ι
104
+ have ha := assume_eq ρ M ι κ adm
105
+ have hq : q < N := by simpa only [q, point, holdsC, evalE, hb] using checked_point_inside X M ha
106
+ have haAt (j : Nat) : holdsC ${shift('j')} M (${t.c(locals[1].assumptions[0])}) := by
107
+ simpa [holdsC, evalE, upd] using ha
108
+ have hqAt (j : Nat) : point ${shift('j')} M = q := by simp [point, evalE, upd, q]
109
+ obtain ⟨${p.fields.map((_, i) => `hold${i}`).join(', ')}⟩ := hold
110
+ change Coupled ρ' M'
111
+ unfold Coupled
112
+ rw [hn]
113
+ by_cases hr : holdsC X M (${t.c(p.reset)})
114
+ · have hrAt (j : Nat) : holdsC ${shift('j')} M (${t.c(p.reset)}) := by simpa [holdsC, evalE, upd] using hr
115
+ have resetMap (j : Nat) : M' 0 ${addr('j')} = ${m.maps[p.map]} := by
116
+ have v := checked_broadcast_reset ${shift('j')} M (haAt j) (hrAt j)
117
+ simp only [M', sNext, view_eq, Prod.fst, Prod.snd]
118
+ simpa [X, ${sem}] using v
119
+ refine ⟨${p.fields.map(() => '?_').join(', ')}⟩
120
+ ${p.fields.map((f, i) => ` · have hz : ρ' ${ix(f.field)} = 0 := by
121
+ simp only [ρ', sNext, view_eq, Prod.fst, Prod.snd]
122
+ simpa [X, ${sem}] using checked_field${i}_reset X M ha hr
123
+ rw [hz]
124
+ apply Eq.symm
125
+ exact zeroSum _ _ (by intro j; simp [countCell, resetMap])`).join('\n')}
126
+ · have hrAt (j : Nat) : ¬holdsC ${shift('j')} M (${t.c(p.reset)}) := by simpa [holdsC, evalE, upd] using hr
127
+ have frameMap (j : Nat) (hne : j ≠ q) : M' 0 ${addr('j')} = M 0 ${addr('j')} := by
128
+ have hneq : holdsC ${shift('j')} M (${t.c(locals[1].assumptions[2])}) := by
129
+ change (j ≠ point ${shift('j')} M)
130
+ rwa [hqAt]
131
+ have v := checked_other_cells_frame ${shift('j')} M (haAt j) (hrAt j) hneq
132
+ simp only [M', sNext, view_eq, Prod.fst, Prod.snd]
133
+ simpa [X, ${sem}] using v
134
+ refine ⟨${p.fields.map(() => '?_').join(', ')}⟩
135
+ ${p.fields.map((f, i) => ` · have delta : ρ' ${ix(f.field)} + countCell ${f.value} M q = ρ ${ix(f.field)} + countCell ${f.value} M' q := by
136
+ simp only [ρ', M', countCell, sNext, view_eq, Prod.fst, Prod.snd]
137
+ simpa [q, point, X, ${sem}] using checked_field${i}_delta X M ha hr
138
+ exact coupled_change _ _ _ _ _ _ hq (by intro j _ hne; simp [countCell, frameMap j hne]) hold${i} delta`).join('\n')}
139
+
140
+ theorem all_coupled {ρ M} (h : SReach src ρ M) : Coupled ρ M := by
141
+ induction h with
142
+ | start ρ M hm _ _ _ => exact coupled_init ρ M hm
143
+ | step ρ M ι κ _ adm ih => exact coupled_next ρ M ι κ ih adm
144
+
145
+ theorem original_law {ρ M} (h : SReach src ρ M) : holdsC ρ M original := by
146
+ obtain ⟨${p.fields.map((_, i) => `hold${i}`).join(', ')}⟩ := all_coupled h
147
+ apply checked_capacity_entails_claim
148
+ change ${cap} ≤ ρ ${boundIx}
149
+ rw [${p.fields.map((_, i) => `hold${i}`).join(', ')}]
150
+ rw [${p.fields.slice(1).map(() => '← sumBelow_add').join(', ')}]
151
+ calc
152
+ _ ≤ sumBelow (fun _ => 1) (ρ ${boundIx}) := by
153
+ apply sumBelow_mono
154
+ intro j _
155
+ have v := checked_disjoint_capacity (upd ρ ${ix(coordinate)} j) M
156
+ change ${classBody('M')} ≤ 1
157
+ simpa [countCell, holdsC, evalE, evalC, upd] using v
158
+ _ = ρ ${boundIx} := by simp [sumBelow_const]
159
+
160
+ theorem aggregate_claim : ∀ ρ M, SReach src ρ M → holdsC ρ M original :=
161
+ fun _ _ h => original_law h
162
+ `;
163
+ }
@@ -0,0 +1,2 @@
1
+ import type { Law, Machine } from '../../core/machine.js';
2
+ export declare function admitAggregateSource(machine: Machine, law: Law): string;
@@ -0,0 +1,141 @@
1
+ import { types } from 'node:util';
2
+ import { isSourceBound } from "../../core/source-check.js";
3
+ import { scope } from "../../kernel/kernel.js";
4
+ function refuse(detail) { throw new Error(detail); }
5
+ const isObject = (v) => v !== null && typeof v === 'object';
6
+ // Never look up a source property (including array elements) or serialize a
7
+ // caller-supplied object. Reject proxies before any reflective operation.
8
+ function snapshot(machine, law) {
9
+ if (Object.getPrototypeOf(Array.prototype) !== Object.prototype)
10
+ refuse('Unexpected array prototype chain.');
11
+ if (Object.getOwnPropertyDescriptor(Object.prototype, 'toJSON') ||
12
+ Object.getOwnPropertyDescriptor(Array.prototype, 'toJSON'))
13
+ refuse('Inherited toJSON is not supported.');
14
+ const active = new Set();
15
+ let nodes = 0;
16
+ const copy = (v, depth) => {
17
+ if (++nodes > 250_000 || depth > 256)
18
+ return refuse('Source data exceeds the snapshot bound.');
19
+ if (v === null || typeof v === 'string' || typeof v === 'boolean' ||
20
+ typeof v === 'number' && Number.isFinite(v) && !Object.is(v, -0))
21
+ return v;
22
+ if (!isObject(v) || types.isProxy(v))
23
+ return refuse('Source must contain only passive JSON data; omit absent optional fields.');
24
+ if (active.has(v))
25
+ return refuse('Source data must not be cyclic.');
26
+ const array = Array.isArray(v), proto = Object.getPrototypeOf(v);
27
+ if (array ? proto !== Array.prototype && proto !== null : proto !== Object.prototype && proto !== null)
28
+ return refuse('Unexpected source prototype.');
29
+ active.add(v);
30
+ const keys = Reflect.ownKeys(v);
31
+ const out = (array ? Object.setPrototypeOf([], null) : Object.create(null));
32
+ const length = array ? Object.getOwnPropertyDescriptor(v, 'length').value : 0;
33
+ // An array has exactly its length descriptor and one enumerable data
34
+ // descriptor per index. Reject holes, symbols and extra own properties.
35
+ if (array && keys.length !== length + 1)
36
+ return refuse('Source arrays must be dense and have no extra properties.');
37
+ let i = 0;
38
+ for (const key of keys) {
39
+ if (array && key === 'length')
40
+ continue;
41
+ if (typeof key !== 'string' || key === 'toJSON' || array && key !== String(i++))
42
+ return refuse('Unsupported source property.');
43
+ const d = Object.getOwnPropertyDescriptor(v, key);
44
+ if (!d.enumerable || !Object.hasOwn(d, 'value'))
45
+ return refuse('Source properties must be enumerable own data.');
46
+ out[key] = copy(d.value, depth + 1);
47
+ }
48
+ active.delete(v);
49
+ return out;
50
+ };
51
+ const pair = [copy(machine, 0), copy(law, 0)];
52
+ Object.setPrototypeOf(pair, null);
53
+ return JSON.stringify(pair);
54
+ }
55
+ const record = (v) => isObject(v) && !Array.isArray(v);
56
+ const fields = (v, required, optional = []) => record(v) && required.every(k => Object.hasOwn(v, k)) && Object.keys(v).every(k => required.includes(k) || optional.includes(k));
57
+ // These labels may be printed in comments. Do not let one supply Lean syntax.
58
+ function label(v) {
59
+ if (typeof v !== 'string' || v.includes('/-') || v.includes('-/'))
60
+ return false;
61
+ for (const c of v) {
62
+ const point = c.codePointAt(0);
63
+ if (point < 0x20 || point >= 0x7f && point <= 0x9f || point === 0x2028 || point === 0x2029)
64
+ return false;
65
+ }
66
+ return true;
67
+ }
68
+ const nat = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
69
+ const list = (v, valid) => Array.isArray(v) && v.every(valid);
70
+ const table = (v, valid) => record(v) && Object.entries(v).every(([key, x]) => label(key) && valid(x));
71
+ const emptyList = (v) => Array.isArray(v) && v.length === 0;
72
+ const emptyTable = (v) => record(v) && Object.keys(v).length === 0;
73
+ const optional = (v, key, valid) => !Object.hasOwn(v, key) || valid(v[key]);
74
+ // Validate the closed natural-number source fragment, not just its opcodes.
75
+ // No primitive failure, carried maps, history, derived values, external facts,
76
+ // native functions, or alternate law binders may reach either recognizer.
77
+ function admissible(m, law) {
78
+ if (!fields(m, ['name', 'params', 'inputs', 'state', 'step'], ['maps', 'pre', 'assume', 'inputMaps', 'facts', 'fns', 'leasts', 'relations']) ||
79
+ !fields(law, ['name', 'holds'], ['forall', 'keys', 'some', 'stated']) ||
80
+ !fields(m.step, [], ['state', 'maps', 'flags']))
81
+ return false;
82
+ const maps = Object.hasOwn(m, 'maps') ? m.maps : {};
83
+ function term(v) {
84
+ if (!record(v) || !Object.hasOwn(v, 'op'))
85
+ return false;
86
+ switch (v.op) {
87
+ case 'var': return fields(v, ['op', 'name']) && label(v.name);
88
+ case 'const': return fields(v, ['op', 'value']) && nat(v.value);
89
+ case 'add':
90
+ case 'sub':
91
+ case 'min':
92
+ case 'max':
93
+ case 'prod':
94
+ case 'tup':
95
+ return fields(v, ['op', 'a', 'b']) && term(v.a) && term(v.b);
96
+ case 'mul': return fields(v, ['op', 'k', 'a']) && nat(v.k) && term(v.a);
97
+ case 'proj': return fields(v, ['op', 'k', 'a']) && (v.k === 0 || v.k === 1) && term(v.a);
98
+ case 'if': return fields(v, ['op', 'c', 'then', 'else']) && cond(v.c) && term(v.then) && term(v.else);
99
+ case 'get': return fields(v, ['op', 'map', 'key']) && label(v.map) && record(maps) && Object.hasOwn(maps, v.map) && term(v.key);
100
+ default: return false;
101
+ }
102
+ }
103
+ function cond(v) {
104
+ if (!record(v) || !Object.hasOwn(v, 'op'))
105
+ return false;
106
+ switch (v.op) {
107
+ case '<':
108
+ case '<=':
109
+ case '=': return fields(v, ['op', 'a', 'b']) && term(v.a) && term(v.b);
110
+ case 'and':
111
+ case 'or': return fields(v, ['op', 'xs']) && list(v.xs, cond);
112
+ case 'not': return fields(v, ['op', 'x']) && cond(v.x);
113
+ case 'flag': return fields(v, ['op', 'name']) && label(v.name);
114
+ default: return false;
115
+ }
116
+ }
117
+ const write = (v) => (fields(v, ['each', 'value']) && label(v.each) || fields(v, ['key', 'value']) && term(v.key)) && term(v.value);
118
+ return label(m.name) && label(law.name) && list(m.params, label) && list(m.inputs, label) && table(maps, nat) &&
119
+ table(m.state, term) && optional(m.step, 'state', v => table(v, term)) && optional(m.step, 'maps', v => table(v, write)) &&
120
+ optional(m.step, 'flags', v => table(v, cond)) && optional(m, 'pre', cond) && optional(m, 'assume', cond) &&
121
+ optional(m, 'inputMaps', emptyList) && optional(m, 'facts', emptyList) && optional(m, 'fns', emptyTable) &&
122
+ optional(m, 'leasts', emptyTable) && optional(m, 'relations', v => table(v, a => list(a, label))) &&
123
+ optional(law, 'forall', v => label(v) && v.length > 0) && optional(law, 'keys', emptyList) && optional(law, 'some', emptyList) &&
124
+ cond(law.holds) && optional(law, 'stated', v => cond(v) && JSON.stringify(v) === JSON.stringify(law.holds));
125
+ }
126
+ export function admitAggregateSource(machine, law) {
127
+ if (!isObject(machine) || !isObject(law) || types.isProxy(machine) || types.isProxy(law))
128
+ return refuse('Source machine and invariant must be passive data.');
129
+ // These identities matter before copying: the marker deliberately survives
130
+ // without a native journal. This adapter only certifies an unmarked model.
131
+ if (isSourceBound(machine, [law]))
132
+ return refuse('Source-bound machines and laws are not supported; this adapter checks models only.');
133
+ const input = snapshot(machine, law);
134
+ const [m, l] = JSON.parse(input);
135
+ if (!admissible(m, l))
136
+ return refuse('Unsupported source machine or invariant.');
137
+ // Scope the exact, uninstrumented data the worker will parse, before either
138
+ // recognizer. The retained, instrumented family is a separate obligation.
139
+ scope(m, [l]);
140
+ return input;
141
+ }
@@ -0,0 +1,2 @@
1
+ import type { WeightedCandidate } from './weighted.js';
2
+ export declare function closeWeightedFlags(c: WeightedCandidate): WeightedCandidate | undefined;
@@ -0,0 +1,26 @@
1
+ import { walkOnce } from "../../core/machine.js";
2
+ import { ghostedOk, substC } from "../../kernel/kernel.js";
3
+ export function closeWeightedFlags(c) {
4
+ const flags = Object.create(null), inlined = Object.create(null);
5
+ const src = JSON.stringify(c.machine);
6
+ let stem = 'internal$';
7
+ while (src.includes(stem))
8
+ stem += 'a';
9
+ for (const [i, [name, value]] of Object.entries(c.ghost.orig.step.flags ?? {}).entries()) {
10
+ if (value.op === 'all')
11
+ return undefined;
12
+ const body = substC(value, { vars: {}, maps: {}, flags: inlined });
13
+ let open = false;
14
+ walkOnce(body, e => { const t = e; if (t.op === 'flag' || t.op === 'all')
15
+ open = true; });
16
+ if (open)
17
+ return undefined;
18
+ inlined[name] = body;
19
+ flags[name] = { op: 'all', key: `${stem}${i}`, c: body };
20
+ }
21
+ const replace = (m) => ({ ...m, step: { ...m.step, flags } });
22
+ const ghost = { ...c.ghost, orig: replace(c.ghost.orig) };
23
+ if (!ghostedOk(ghost))
24
+ return undefined;
25
+ return { ...c, ghost, machine: replace(c.machine) };
26
+ }
@@ -0,0 +1,7 @@
1
+ import type { Law, Machine } from '../../core/machine.js';
2
+ import { type Instances, type Tree } from '../../kernel/kernel.js';
3
+ import type { WeightedCandidate } from './weighted.js';
4
+ export declare function emitWeighted(c: WeightedCandidate, source: Machine, law: Law, proof: {
5
+ instances: Record<string, Instances>;
6
+ trees: Record<string, Tree>;
7
+ }): string;
@@ -0,0 +1,53 @@
1
+ // Generic proof-output bridge: export only the retained weighted family,
2
+ // then prove source correspondence (flag views, observer, ghost map, sum).
3
+ import assert from 'node:assert/strict';
4
+ import { checkLaws, ghostedOk, sideGoals } from "../../kernel/kernel.js";
5
+ import { retainedSumMachineToLean } from "../../lean-kernel/emit.js";
6
+ export function emitWeighted(c, source, law, proof) {
7
+ assert(law.forall && !law.keys?.length && !law.some?.length);
8
+ assert(ghostedOk(c.ghost));
9
+ assert.equal(sideGoals(c.machine, c.laws).length, 0, 'unexpected cover search');
10
+ assert(checkLaws(c.machine, c.laws, proof), 'exact native weighted family rejected');
11
+ const [g, ...extra] = Object.keys(c.ghost.maps);
12
+ assert(g && extra.length === 0 && Object.keys(c.ghost.vars).length === 0);
13
+ const idx = c.laws.findIndex(l => l.name === law.name);
14
+ assert(idx >= 0);
15
+ const body = retainedSumMachineToLean('packet', c.machine, c.laws, proof, { free: [law.forall], after: (ix, mx, lit, cond) => {
16
+ const flags = Object.entries(c.ghost.orig.step.flags ?? {});
17
+ const binder = flags.map(([f, a]) => { assert.equal(a.op, 'all'); assert(a.op === 'all' && !a.keys?.length); return `if i = ${ix(`?${f}`)} then ${ix(a.key)} else `; }).join('') + '0';
18
+ const goal = cond(law.holds), specialization = cond(c.laws[idx].holds);
19
+ return `
20
+ def originalMachine : SMachine := ${lit(source)}
21
+ def unchangedLaw : MLaw := ⟨${goal}, some ${ix(law.forall)}⟩
22
+ def observer : Nat := ${ix(c.observer)}
23
+ def closedBinder (i : Nat) : Nat := ${binder}
24
+ def mapLift : SGhostedM := ⟨${lit(c.ghost.orig)}, [], [(${mx(g)}, ${c.ghost.maps[g].start})],
25
+ packet_sums.s.f.m.writes.filter (fun row => row.1 == ${mx(g)}), []⟩
26
+ theorem liftChecks : smghostOk mapLift = true := by decide +kernel
27
+ theorem sumShape : mapLift.full = packet_sums.s := by rfl
28
+ theorem sumGhostChecks : sghostOk packet_sums.ghosts = true := by decide +kernel
29
+ theorem promotionIdentity : mapLift.orig = GroupedSumsResearch.promote originalMachine closedBinder mapLift.orig.wits := by rfl
30
+
31
+ theorem unchanged_law (ρ : Nat → Nat) (M : Nat → Nat → Nat)
32
+ (hr : SReach originalMachine ρ M) : unchangedLaw.Holds ρ M := by
33
+ intro k
34
+ have ho := GroupedSumsResearch.source_rebind originalMachine observer rfl rfl rfl (by decide +kernel) hr k
35
+ have hc : SReach mapLift.orig (upd ρ observer k) M :=
36
+ (GroupedSumsResearch.candidate_reach closedBinder _ promotionIdentity rfl (by decide +kernel)).mpr ho
37
+ obtain ⟨ρg, Mg, hg, hs, hm⟩ := smghost_reach mapLift liftChecks hc
38
+ have he : packet_e${idx}.Holds ρg Mg :=
39
+ sum_project_laws packet_sums sumGhostChecks packet_proof packet_check packet_scheck
40
+ ρg Mg (sumShape ▸ hg) packet_e${idx} (by simp [packet_proof]) (by decide +kernel)
41
+ have hl : packet_e${idx}.Holds (upd ρ observer k) M :=
42
+ sentry_transfer (V := mapLift.vars) (MS := mapLift.maps) (by decide +kernel) (by decide +kernel)
43
+ (fun i hi => (hs i hi).symm) (fun m hmi => (hm m hmi).symm) he
44
+ change evalC (upd ρ observer k) M (${specialization}) = true at hl
45
+ change evalC (upd ρ ${ix(law.forall)} k) M (${goal}) = true
46
+ simpa [observer, evalC, evalE, upd] using hl
47
+
48
+ theorem aggregate_claim : ∀ ρ M, SReach originalMachine ρ M → unchangedLaw.Holds ρ M :=
49
+ unchanged_law
50
+ `;
51
+ } });
52
+ return `import GhostMap\nimport Sums\nimport GroupedTransport\nopen Kern Cert\nset_option maxRecDepth 100000\nset_option maxHeartbeats 0\n${body}`;
53
+ }
@@ -0,0 +1,30 @@
1
+ import { type Instances, type Tree } from '../../kernel/kernel.js';
2
+ import type { WeightedCandidate } from './weighted.js';
3
+ export declare function proveWeightedSeeded(c: WeightedCandidate, ms: number, observe: (x: object) => void): {
4
+ proven: boolean;
5
+ checked: boolean;
6
+ failed: {
7
+ why: string;
8
+ goal?: undefined;
9
+ };
10
+ proof?: undefined;
11
+ } | {
12
+ proven: boolean;
13
+ checked: boolean;
14
+ failed: {
15
+ goal: string;
16
+ why: string;
17
+ };
18
+ proof?: undefined;
19
+ } | {
20
+ proven: boolean;
21
+ checked: boolean;
22
+ proof: {
23
+ instances: Record<string, Instances>;
24
+ trees: Record<string, Tree>;
25
+ };
26
+ failed: {
27
+ why: string;
28
+ goal?: undefined;
29
+ } | undefined;
30
+ };
@@ -0,0 +1,64 @@
1
+ import { n, same, x } from "../../core/machine.js";
2
+ import { checkLaws, obligations, sumParts } from "../../kernel/kernel.js";
3
+ import { clock, grow } from "../../kernel/prove.js";
4
+ import { countGuardTree } from "../../core/count-guard-tree.js";
5
+ // Propose ∀-instances only at the address the weighted summary actually
6
+ // subtracts and the preservation goal's own row. Every branch tree is an
7
+ // ordinary proof of the original goal (no changed hypothesis list).
8
+ export function proveWeightedSeeded(c, ms, observe) {
9
+ const { machine, laws, links } = c;
10
+ const p = laws.find(l => l.forall);
11
+ if (!p?.forall)
12
+ return { proven: false, checked: false, failed: { why: 'no pointwise helper' } };
13
+ const probe = x(`${p.forall}#`);
14
+ const point = links.point;
15
+ const touched = [point, ...(point.op === 'if' ? [point.then, point.else] : [])];
16
+ const sum = Object.keys(machine.sums ?? {})[0];
17
+ const q = `?${sumParts(sum).flag}`;
18
+ const closed = Object.entries(machine.step.flags ?? {}).flatMap(([name, c]) => c.op === 'all' ? [name] : []);
19
+ const instances = Object.fromEntries(laws.map(l => [l.name, { ...Object.fromEntries(closed.map(f => ['?' + f, [n(0)]])), [p.name]: l === p ? [...touched, probe] : [point], [q]: l === p ? [probe] : [] }]));
20
+ const until = clock() + ms, trees = {};
21
+ const goals = obligations(machine, laws, instances);
22
+ // Try agreement first so a large pointwise relation cannot starve it.
23
+ const i = laws.findIndex(({ holds: c }) => (c.op === '=' || c.op === '<=') && [c.a, c.b].some(e => e.op === 'var' && e.name === sum));
24
+ if (i >= 0)
25
+ goals.unshift(...goals.splice(2 * i, 2));
26
+ for (const goal of goals) {
27
+ if (clock() >= until)
28
+ return { proven: false, checked: false, failed: { goal: goal.name, why: 'budget' } };
29
+ const addressConditions = goal.name.endsWith('@step') ? (point.op === 'if' ? [point.c] : []) : [];
30
+ if (goal.name === `${p.name} @step`)
31
+ addressConditions.push(same(probe, point));
32
+ if (goal.name.endsWith('@step'))
33
+ for (const f of links.events.filter(f => closed.includes(f)))
34
+ addressConditions.push({ op: '<=', a: x('?' + f), b: n(0) });
35
+ const one = (g, path, ms) => {
36
+ const found = grow(g, path, { nodes: 0, until: Math.min(until, clock() + ms) });
37
+ return 'tree' in found ? found.tree : undefined;
38
+ };
39
+ const quick = one(goal, new Map(), goal.name.endsWith('@start') ? 1000 : closed.length ? 1200 : 3500);
40
+ const split = countGuardTree(until, { yesFirst: true });
41
+ const branch = (at, path) => {
42
+ if (at === addressConditions.length) {
43
+ const proof = one(goal, path, Math.min(closed.length ? 6000 : 8000, until - clock()));
44
+ if (!proof && closed.length)
45
+ observe({ goal: goal.name, phase: 'leaf', path: [...path.values()].slice(-12) });
46
+ return proof;
47
+ }
48
+ if (closed.length && at > 0) {
49
+ const dead = one(goal, path, 70);
50
+ if (dead)
51
+ return dead;
52
+ }
53
+ const next = (p) => branch(at + 1, p);
54
+ return split.condition(addressConditions[at], path, next, next);
55
+ };
56
+ const tree = quick ?? branch(0, new Map());
57
+ observe({ goal: goal.name, checkedHere: !!tree, remaining: Math.round(until - clock()) });
58
+ if (!tree)
59
+ return { proven: false, checked: false, failed: { goal: goal.name, why: 'write-key instances and guard splitting did not close' } };
60
+ trees[goal.name] = tree;
61
+ }
62
+ const proof = { instances, trees }, checked = checkLaws(machine, laws, proof);
63
+ return { proven: checked, checked, proof, failed: checked ? undefined : { why: 'whole-family kernel refused' } };
64
+ }
@@ -0,0 +1,18 @@
1
+ import { type E, type Law, type Machine } from '../../core/machine.js';
2
+ import { type Ghosted } from '../../kernel/kernel.js';
3
+ export type WeightedCandidate = {
4
+ ghost: Ghosted;
5
+ machine: Machine;
6
+ laws: Law[];
7
+ links: {
8
+ balance: string;
9
+ weight: string;
10
+ group: string;
11
+ gates: [string, number][];
12
+ absence?: [string, number];
13
+ point: E;
14
+ events: string[];
15
+ };
16
+ observer: string;
17
+ };
18
+ export declare function weightedCandidates(m: Machine, law: Law): WeightedCandidate[];