gdp-wired 0.51.0 → 0.53.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 (89) 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/aggregate-kinds.d.ts +10 -0
  5. package/dist/core/aggregate-kinds.js +44 -0
  6. package/dist/core/aggregate-search.d.ts +9 -0
  7. package/dist/core/aggregate-search.js +74 -0
  8. package/dist/core/aggregate-weighted/candidates.d.ts +18 -0
  9. package/dist/core/aggregate-weighted/candidates.js +128 -0
  10. package/dist/core/aggregate-weighted/search.d.ts +17 -0
  11. package/dist/core/aggregate-weighted/search.js +68 -0
  12. package/dist/core/cli.d.ts +2 -0
  13. package/dist/core/cli.js +8 -1
  14. package/dist/core/cycles.d.ts +2 -0
  15. package/dist/core/cycles.js +12 -9
  16. package/dist/core/dsl.d.ts +7 -1
  17. package/dist/core/dsl.js +158 -26
  18. package/dist/core/filtered-sum-candidates.d.ts +17 -0
  19. package/dist/core/filtered-sum-candidates.js +77 -0
  20. package/dist/core/live-support.d.ts +5 -0
  21. package/dist/core/live-support.js +148 -0
  22. package/dist/core/live.js +194 -37
  23. package/dist/core/lockstep.d.ts +5 -0
  24. package/dist/core/lockstep.js +23 -0
  25. package/dist/core/ordered-pair-seeds.d.ts +2 -0
  26. package/dist/core/ordered-pair-seeds.js +109 -0
  27. package/dist/core/proof-output.d.ts +49 -2
  28. package/dist/core/proof-output.js +44 -0
  29. package/dist/core/search-termination.d.ts +4 -0
  30. package/dist/core/search-termination.js +1 -1
  31. package/dist/core/source-check.d.ts +4 -1
  32. package/dist/core/source-check.js +5 -2
  33. package/dist/core/sparse-kind-proof.d.ts +7 -0
  34. package/dist/core/sparse-kind-proof.js +49 -0
  35. package/dist/core/step-seeds.d.ts +46 -0
  36. package/dist/core/step-seeds.js +316 -0
  37. package/dist/kernel/finite-sum.d.ts +31 -0
  38. package/dist/kernel/finite-sum.js +74 -0
  39. package/dist/kernel/ghost-write.d.ts +117 -0
  40. package/dist/kernel/ghost-write.js +89 -0
  41. package/dist/lean-kernel/Cert.lean +222 -0
  42. package/dist/lean-kernel/Count.lean +1568 -0
  43. package/dist/lean-kernel/Ghost.lean +373 -0
  44. package/dist/lean-kernel/GhostMap.lean +426 -0
  45. package/dist/lean-kernel/Kernel.lean +2881 -0
  46. package/dist/lean-kernel/Live.lean +1168 -0
  47. package/dist/lean-kernel/Progress.lean +543 -0
  48. package/dist/lean-kernel/Sets.lean +1975 -0
  49. package/dist/lean-kernel/StepLaw.lean +128 -0
  50. package/dist/lean-kernel/Steps.lean +477 -0
  51. package/dist/lean-kernel/Sums.lean +916 -0
  52. package/dist/lean-kernel/emit.d.ts +15 -0
  53. package/dist/lean-kernel/emit.js +47 -6
  54. package/dist/lean-kernel/finite-sum-export.d.ts +3 -0
  55. package/dist/lean-kernel/finite-sum-export.js +163 -0
  56. package/dist/lean-kernel/ghost-write-export.d.ts +3 -0
  57. package/dist/lean-kernel/ghost-write-export.js +81 -0
  58. package/dist/lean-kernel/lean-aggregate/FiniteFold.lean +44 -0
  59. package/dist/lean-kernel/lean-aggregate/GroupedTransport.lean +308 -0
  60. package/dist/lean-kernel/lean-aggregate/aggregate.d.ts +13 -0
  61. package/dist/lean-kernel/lean-aggregate/aggregate.js +68 -0
  62. package/dist/lean-kernel/lean-aggregate/assets.d.ts +5 -0
  63. package/dist/lean-kernel/lean-aggregate/assets.js +7 -0
  64. package/dist/lean-kernel/lean-aggregate/audit.d.ts +3 -0
  65. package/dist/lean-kernel/lean-aggregate/audit.js +13 -0
  66. package/dist/lean-kernel/lean-aggregate/exact.d.ts +15 -0
  67. package/dist/lean-kernel/lean-aggregate/exact.js +51 -0
  68. package/dist/lean-kernel/lean-aggregate/index.d.ts +19 -0
  69. package/dist/lean-kernel/lean-aggregate/index.js +52 -0
  70. package/dist/lean-kernel/lean-aggregate/point-fold.d.ts +27 -0
  71. package/dist/lean-kernel/lean-aggregate/point-fold.js +79 -0
  72. package/dist/lean-kernel/lean-aggregate/replay-fold.d.ts +2 -0
  73. package/dist/lean-kernel/lean-aggregate/replay-fold.js +163 -0
  74. package/dist/lean-kernel/lean-aggregate/source.d.ts +2 -0
  75. package/dist/lean-kernel/lean-aggregate/source.js +141 -0
  76. package/dist/lean-kernel/lean-aggregate/weighted-flags.d.ts +2 -0
  77. package/dist/lean-kernel/lean-aggregate/weighted-flags.js +26 -0
  78. package/dist/lean-kernel/lean-aggregate/weighted-replay.d.ts +7 -0
  79. package/dist/lean-kernel/lean-aggregate/weighted-replay.js +53 -0
  80. package/dist/lean-kernel/lean-aggregate/weighted-seeded.d.ts +30 -0
  81. package/dist/lean-kernel/lean-aggregate/weighted-seeded.js +64 -0
  82. package/dist/lean-kernel/lean-aggregate/weighted.d.ts +18 -0
  83. package/dist/lean-kernel/lean-aggregate/weighted.js +115 -0
  84. package/dist/lean-kernel/lean-aggregate/worker.d.ts +10 -0
  85. package/dist/lean-kernel/lean-aggregate/worker.js +46 -0
  86. package/dist/lean-kernel/library.js +3 -0
  87. package/dist/lean-kernel/lift-simulation/shape.js +5 -5
  88. package/docs/lean-aggregate.md +29 -0
  89. package/package.json +6 -1
@@ -0,0 +1,308 @@
1
+ -- Generic structural transport reused from feat/grouped-sums@3a397980d.
2
+ -- No machine, field, law, or proof tree is encoded in this library.
3
+ import GhostMap
4
+
5
+ open Kern
6
+
7
+ namespace GroupedSumsResearch
8
+
9
+ private abbrev Env := Nat → Nat
10
+ private abbrev Maps := Nat → Nat → Nat
11
+ private abbrev Flag := Nat × C
12
+ private abbrev QFlag := Nat × List Nat × C
13
+
14
+ private def liftFlag (binder : Nat → Nat) (p : Flag) : QFlag :=
15
+ (p.1, [binder p.1], p.2)
16
+
17
+ def promote (s : SMachine) (binder : Nat → Nat)
18
+ (ws : List (Nat × List Nat)) : SMachine :=
19
+ { s with
20
+ f := { s.f with flags := [] }
21
+ qflags := s.f.flags.map (liftFlag binder)
22
+ wits := ws }
23
+
24
+ def bindersOK (s : SMachine) (binder : Nat → Nat) : Bool :=
25
+ s.f.flags.all fun p => !occC (binder p.1) p.2
26
+
27
+ private theorem hit_mem {α : Type} (test : α → Bool) (xs : List α) (a : α)
28
+ (h : lookup test xs = some a) : a ∈ xs := by
29
+ induction xs with
30
+ | nil => simp [lookup] at h
31
+ | cons x xs ih =>
32
+ cases hx : test x with
33
+ | false =>
34
+ exact List.mem_cons_of_mem _ (ih (by simpa [lookup, hx] using h))
35
+ | true =>
36
+ have he : x = a := by simpa [lookup, hx] using h
37
+ simp [he]
38
+
39
+ private theorem hit_test {α : Type} (test : α → Bool) (xs : List α) (a : α)
40
+ (h : lookup test xs = some a) : test a = true := by
41
+ induction xs with
42
+ | nil => simp [lookup] at h
43
+ | cons x xs ih =>
44
+ cases hx : test x with
45
+ | false => exact ih (by simpa [lookup, hx] using h)
46
+ | true =>
47
+ have he : x = a := by simpa [lookup, hx] using h
48
+ simpa [← he] using hx
49
+
50
+ private theorem lift_hit (b : Nat → Nat) (i : Nat) (fs : List Flag) :
51
+ lookup (fun q : QFlag => q.1 == i) (fs.map (liftFlag b)) =
52
+ (lookup (fun p : Flag => p.1 == i) fs).map (liftFlag b) := by
53
+ induction fs with
54
+ | nil => rfl
55
+ | cons p fs ih =>
56
+ cases hp : p.1 == i with
57
+ | false => simpa [lookup, liftFlag, hp] using ih
58
+ | true => simp [lookup, liftFlag, hp]
59
+
60
+ private theorem unused_key (X : Env) (N : Maps) (b : Nat) (c : C)
61
+ (h : occC b c = false) :
62
+ (∀ v, holdsC (atKeys X [b] v) N c) ↔ evalC X N c = true := by
63
+ have he (v : Env) : evalC (atKeys X [b] v) N c = evalC X N c := by
64
+ apply congrC
65
+ intro i hi
66
+ have hn : i ≠ b := by
67
+ intro e
68
+ subst i
69
+ simp [h] at hi
70
+ exact atKeys_out (by simpa using hn)
71
+ constructor
72
+ · intro hall
73
+ rw [← he X]
74
+ exact (evalC_iff _ _ _).mpr (hall X)
75
+ · intro hc v
76
+ apply (evalC_iff _ _ _).mp
77
+ rwa [he v]
78
+
79
+ private theorem promoted_bits (s : SMachine) (b : Nat → Nat)
80
+ (ws : List (Nat × List Nat)) (hb : bindersOK s b = true)
81
+ (X : Env) (N : Maps) :
82
+ decideQ (promote s b ws) X N = decideFlags s.f.flags X N := by
83
+ classical
84
+ have fresh : ∀ p ∈ s.f.flags, occC (b p.1) p.2 = false := by
85
+ simpa [bindersOK] using hb
86
+ funext i
87
+ simp only [decideQ, promote, lift_hit, decideFlags, applyS, assoc_flagSub,
88
+ flagOf]
89
+ cases hh : lookup (fun p : Flag => p.1 == i) s.f.flags with
90
+ | none => rfl
91
+ | some p =>
92
+ have hp := fresh p (hit_mem _ _ _ hh)
93
+ have hk := unused_key X N (b p.1) p.2 hp
94
+ cases hc : evalC X N p.2 <;>
95
+ simp [liftFlag, hk, hc, evalE]
96
+
97
+ private theorem empty_bits (s : SMachine) (hq : s.qflags = [])
98
+ (X : Env) (N : Maps) : decideQ s X N = X := by
99
+ funext i
100
+ simp [decideQ, hq, lookup]
101
+
102
+ theorem promote_view (s : SMachine) (b : Nat → Nat)
103
+ (ws : List (Nat × List Nat)) (hq : s.qflags = [])
104
+ (hb : bindersOK s b = true) : sView (promote s b ws) = sView s := by
105
+ funext ρ M ι κ
106
+ let X := withInputs s.f.m.inputs ρ ι
107
+ let N := withCarried s M κ
108
+ change (decideQ (promote s b ws) X N, N) =
109
+ (decideFlags s.f.flags (decideQ s X N) N, N)
110
+ rw [empty_bits s hq, promoted_bits s b ws hb]
111
+
112
+ theorem promote_next (s : SMachine) (b : Nat → Nat)
113
+ (ws : List (Nat × List Nat)) (hq : s.qflags = [])
114
+ (hb : bindersOK s b = true) : sNext (promote s b ws) = sNext s := by
115
+ funext ρ M ι κ
116
+ simp only [sNext, promote_view s b ws hq hb]
117
+ rfl
118
+
119
+ private theorem transport {s t : SMachine}
120
+ (hm : s.f.m = t.f.m) (hf : s.facts = t.facts)
121
+ (hp : s.pfacts = t.pfacts) (hv : sView s = sView t)
122
+ (hn : sNext s = sNext t) {ρ M} (hr : SReach s ρ M) :
123
+ SReach t ρ M := by
124
+ induction hr with
125
+ | start X N hM hc hl hpl =>
126
+ rw [hm]
127
+ apply SReach.start
128
+ · simpa only [hm] using hM
129
+ · simpa only [hm] using hc
130
+ · simpa only [hf] using hl
131
+ · simpa only [SMachine.PFacts, hp] using hpl
132
+ | step X N ι κ _ hc ih =>
133
+ rw [hn]
134
+ exact SReach.step X N ι κ ih (by simpa only [hm, hv] using hc)
135
+
136
+ theorem promote_reach (s : SMachine) (b : Nat → Nat)
137
+ (ws : List (Nat × List Nat)) (hq : s.qflags = [])
138
+ (hb : bindersOK s b = true) {ρ M} :
139
+ SReach (promote s b ws) ρ M ↔ SReach s ρ M := by
140
+ have hv := promote_view s b ws hq hb
141
+ have hn := promote_next s b ws hq hb
142
+ exact ⟨transport (s := promote s b ws) (t := s) rfl rfl rfl hv hn,
143
+ transport (s := s) (t := promote s b ws) rfl rfl rfl hv.symm hn.symm⟩
144
+
145
+ -- Supply literal identity proofs, not observations of selected executions.
146
+ theorem candidate_reach {source candidate : SMachine} (b : Nat → Nat)
147
+ (ws : List (Nat × List Nat)) (hid : candidate = promote source b ws)
148
+ (hq : source.qflags = []) (hb : bindersOK source b = true) {ρ M} :
149
+ SReach candidate ρ M ↔ SReach source ρ M := by
150
+ subst candidate
151
+ exact promote_reach source b ws hq hb
152
+
153
+ private theorem readE (X : Env) (N : Maps) (o g : Nat) (e : E)
154
+ (h : occE o e = false) : evalE (upd X o g) N e = evalE X N e := by
155
+ apply congrE
156
+ intro i hi
157
+ by_cases eq : i = o
158
+ · subst i
159
+ simp [h] at hi
160
+ · simp [upd, eq]
161
+
162
+ private theorem readC (X : Env) (N : Maps) (o g : Nat) (c : C)
163
+ (h : occC o c = false) : evalC (upd X o g) N c = evalC X N c := by
164
+ apply congrC
165
+ intro i hi
166
+ by_cases eq : i = o
167
+ · subst i
168
+ simp [h] at hi
169
+ · simp [upd, eq]
170
+
171
+ private def assignsOK (o : Nat) (xs : List (Nat × E)) : Bool :=
172
+ xs.all fun p => !(p.1 == o) && !occE o p.2
173
+
174
+ def observerOK (s : SMachine) (o : Nat) : Bool :=
175
+ !s.f.m.inputs.contains o &&
176
+ !occC o s.f.m.pre &&
177
+ !occC o s.f.m.assume &&
178
+ assignsOK o s.f.m.init &&
179
+ assignsOK o s.f.m.step &&
180
+ (s.f.flags.all fun p => !(p.1 == o) && !occC o p.2) &&
181
+ (s.f.m.writes.all fun w => !occE o w.2.1 && !occE o w.2.2) &&
182
+ (s.every.all fun w => !occE o w.2.2)
183
+
184
+ private theorem assoc_member (xs : List (Nat × E)) (i : Nat) (e : E)
185
+ (h : assoc xs i = some e) : (i, e) ∈ xs := by
186
+ induction xs with
187
+ | nil => simp [assoc, lookup] at h
188
+ | cons p xs ih =>
189
+ obtain ⟨j, a⟩ := p
190
+ by_cases hj : j = i
191
+ · subst j
192
+ have ha : a = e := by simpa [assoc, lookup] using h
193
+ simp [ha]
194
+ · exact List.mem_cons_of_mem _ (ih (by
195
+ simpa [assoc, lookup, hj, Ne.symm hj] using h))
196
+
197
+ private theorem assigns_upd (xs : List (Nat × E)) (X : Env) (N : Maps)
198
+ (o g : Nat) (h : assignsOK o xs = true) :
199
+ applyS xs (upd X o g) N = upd (applyS xs X N) o g := by
200
+ have fresh : ∀ p ∈ xs, p.1 ≠ o ∧ occE o p.2 = false := by
201
+ simpa [assignsOK] using h
202
+ funext i
203
+ cases ha : assoc xs i with
204
+ | none => simp [applyS, upd, ha]
205
+ | some e =>
206
+ have hp := fresh (i, e) (assoc_member xs i e ha)
207
+ simp [applyS, upd, ha, hp.1, readE X N o g e hp.2]
208
+
209
+ private theorem inputs_upd (ins : List Nat) (o g : Nat) (X I : Env)
210
+ (h : o ∉ ins) :
211
+ withInputs ins (upd X o g) I = upd (withInputs ins X I) o g := by
212
+ funext i
213
+ by_cases hi : i = o
214
+ · subst i
215
+ simp [withInputs, upd, List.contains_iff_mem, h]
216
+ · simp [withInputs, upd, hi]
217
+
218
+ private theorem flags_upd (fs : List Flag) (X : Env) (N : Maps)
219
+ (o g : Nat) (fresh : ∀ p ∈ fs, p.1 ≠ o ∧ occC o p.2 = false) :
220
+ decideFlags fs (upd X o g) N = upd (decideFlags fs X N) o g := by
221
+ funext i
222
+ simp only [decideFlags, applyS, assoc_flagSub, flagOf, upd]
223
+ cases hh : lookup (fun p : Flag => p.1 == i) fs with
224
+ | none => rfl
225
+ | some p =>
226
+ have hp := fresh p (hit_mem _ _ _ hh)
227
+ have he : p.1 = i := by simpa using hit_test _ _ _ hh
228
+ have hi : i ≠ o := he ▸ hp.1
229
+ have hc := readC X N o g p.2 hp.2
230
+ change evalE (upd X o g) N (.ite p.2 (.const 1) (.const 0)) =
231
+ (if i = o then g else evalE X N (.ite p.2 (.const 1) (.const 0)))
232
+ simp only [if_neg hi, evalE, hc]
233
+
234
+ private theorem view_upd (s : SMachine) (o g : Nat) (X : Env) (N : Maps)
235
+ (I : Env) (K : Maps) (hq : s.qflags = []) (hin : o ∉ s.f.m.inputs)
236
+ (hf : ∀ p ∈ s.f.flags, p.1 ≠ o ∧ occC o p.2 = false) :
237
+ sView s (upd X o g) N I K =
238
+ (upd (sView s X N I K).1 o g, (sView s X N I K).2) := by
239
+ simp only [sView, empty_bits s hq, inputs_upd _ o g X I hin,
240
+ flags_upd _ _ _ o g hf]
241
+
242
+ private theorem writes_upd (ws : List (Nat × E × E)) (D : Env) (N : Maps)
243
+ (o g : Nat)
244
+ (hf : ∀ w ∈ ws, occE o w.2.1 = false ∧ occE o w.2.2 = false) :
245
+ writeMaps ws (upd D o g) N = writeMaps ws D N := by
246
+ funext mp k
247
+ simp only [writeMaps]
248
+ cases hh : lookup (fun w : Nat × E × E => w.1 == mp) ws with
249
+ | none => rfl
250
+ | some w =>
251
+ have hw := hf w (hit_mem _ _ _ hh)
252
+ change (if k = evalE (upd D o g) N w.2.1 then evalE (upd D o g) N w.2.2 else N mp k) =
253
+ (if k = evalE D N w.2.1 then evalE D N w.2.2 else N mp k)
254
+ rw [readE D N o g w.2.1 hw.1, readE D N o g w.2.2 hw.2]
255
+
256
+ private theorem every_upd (s : SMachine) (D : Env) (N : Maps) (o g : Nat)
257
+ (hw : ∀ w ∈ s.f.m.writes, occE o w.2.1 = false ∧ occE o w.2.2 = false)
258
+ (he : ∀ w ∈ s.every, occE o w.2.2 = false) :
259
+ everyMaps s (upd D o g) N = everyMaps s D N := by
260
+ funext mp k
261
+ simp only [everyMaps]
262
+ cases hh : lookup (fun w : Nat × Nat × E => w.1 == mp) s.every with
263
+ | none => rw [writes_upd _ _ _ _ _ hw]
264
+ | some w =>
265
+ have h := he w (hit_mem _ _ _ hh)
266
+ apply congrE
267
+ intro i hi
268
+ by_cases hio : i = o
269
+ · subst i
270
+ simp [h] at hi
271
+ · simp [upd, hio]
272
+
273
+ theorem source_rebind (source : SMachine) (obs : Nat)
274
+ (hq : source.qflags = []) (hfacts : source.facts = [])
275
+ (hpfacts : source.pfacts = []) (hok : observerOK source obs = true) :
276
+ ∀ {ρ M}, SReach source ρ M → ∀ g, SReach source (upd ρ obs g) M := by
277
+ have parts :
278
+ obs ∉ source.f.m.inputs ∧
279
+ occC obs source.f.m.pre = false ∧
280
+ occC obs source.f.m.assume = false ∧
281
+ assignsOK obs source.f.m.init = true ∧
282
+ assignsOK obs source.f.m.step = true ∧
283
+ (∀ p ∈ source.f.flags, p.1 ≠ obs ∧ occC obs p.2 = false) ∧
284
+ (∀ w ∈ source.f.m.writes,
285
+ occE obs w.2.1 = false ∧ occE obs w.2.2 = false) ∧
286
+ (∀ w ∈ source.every, occE obs w.2.2 = false) := by
287
+ simpa [observerOK, List.contains_iff_mem, and_assoc] using hok
288
+ obtain ⟨hin, hpre, hassume, hinit, hstep, hflags, hw, he⟩ := parts
289
+ intro ρ M hr
290
+ induction hr with
291
+ | start X N hM hc _ _ =>
292
+ intro g
293
+ rw [← assigns_upd _ X N obs g hinit]
294
+ apply SReach.start (upd X obs g) N hM
295
+ · rwa [readC _ _ _ _ _ hpre]
296
+ · simp [hfacts]
297
+ · simp [SMachine.PFacts, hpfacts]
298
+ | step X N I K _ hc ih =>
299
+ intro g
300
+ have hv := view_upd source obs g X N I K hq hin hflags
301
+ have hc' : evalC (sView source (upd X obs g) N I K).1
302
+ (sView source (upd X obs g) N I K).2 source.f.m.assume = true := by
303
+ simpa only [hv, readC _ _ obs g _ hassume] using hc
304
+ have hr' := SReach.step (s := source) (upd X obs g) N I K (ih g) hc'
305
+ simpa only [sNext, hv, assigns_upd _ _ _ obs g hstep,
306
+ every_upd source _ _ obs g hw he] using hr'
307
+
308
+ end GroupedSumsResearch
@@ -0,0 +1,13 @@
1
+ import { type C, type E, type Law, type Machine } from '../../core/machine.js';
2
+ export type FilteredCounterProposal = {
3
+ map: string;
4
+ key: string;
5
+ reset: C;
6
+ bound: E;
7
+ offset: number;
8
+ fields: {
9
+ field: string;
10
+ value: number;
11
+ }[];
12
+ };
13
+ export declare function proposeFilteredCounters(m: Machine, caller: Law): FilteredCounterProposal[];
@@ -0,0 +1,68 @@
1
+ // Untrusted, intentionally small syntax recognizers. Their products are
2
+ // candidates for exact finite-fold replay, never extra source facts.
3
+ import { get, n, x, plus } from "../../core/machine.js";
4
+ import { substC } from "../../kernel/kernel.js";
5
+ const equal = (a, b) => JSON.stringify(a) === JSON.stringify(b);
6
+ const atoms = (c) => !c ? [] : c.op === 'and' ? c.xs.flatMap(atoms) : [c];
7
+ const subKey = (c, name, term) => substC(c, { vars: { [name]: term }, maps: {}, flags: {} });
8
+ const rootReset = (u, start) => u.op === 'if' && equal(u.then, start) ? u : undefined;
9
+ const increase = (u, field) => u.op === 'if' && equal(u.else, x(field)) && equal(u.then, plus(x(field), n(1))) ? u.c : undefined;
10
+ const guardIncludes = (full, sub) => atoms(sub).every(p => atoms(full).some(q => equal(p, q)));
11
+ const onlyVariable = (e, name) => e.op === 'var' && e.name === name;
12
+ export function proposeFilteredCounters(m, caller) {
13
+ if (m.history || Object.keys(m.counts ?? {}).length || Object.keys(m.sums ?? {}).length || caller.forall || caller.keys?.length)
14
+ return [];
15
+ const uses = JSON.stringify(caller.holds);
16
+ const out = [];
17
+ for (const [map, wr] of Object.entries(m.step.maps ?? {})) {
18
+ // Cover singleton point writes and broadcast-reset-plus-point writes. A
19
+ // spatial guard is not accepted as a scalar guard; it is first specialized.
20
+ if (!('each' in wr) || m.maps?.[map] === undefined)
21
+ continue;
22
+ const init = n(m.maps[map]);
23
+ const outer = rootReset(wr.value, init), first = outer?.else;
24
+ if (!outer || first?.op !== 'if')
25
+ continue;
26
+ const keyAtom = atoms(first.c).find(c => c.op === '=' && onlyVariable(c.a, wr.each) && c.b.op === 'var' && m.inputs.includes(c.b.name));
27
+ if (keyAtom?.op !== '=' || keyAtom.b.op !== 'var')
28
+ continue;
29
+ const key = keyAtom.b.name;
30
+ const below = atoms(m.assume).find(c => (c.op === '<=' || c.op === '<') && onlyVariable(c.a, key) && c.b.op === 'var' && m.params.includes(c.b.name));
31
+ if (!below || (below.op !== '<=' && below.op !== '<'))
32
+ continue;
33
+ const lower = atoms(m.assume).filter(c => c.op === '<=' && c.a.op === 'const' && onlyVariable(c.b, key)).map(c => c.op === '<=' && c.a.op === 'const' ? c.a.value : 0);
34
+ const offset = Math.max(0, ...lower);
35
+ const bound0 = below.op === '<=' ? plus(below.b, n(1)) : below.b;
36
+ const bound = below.op === '<=' && offset === 1 ? below.b : offset ? { op: 'sub', a: bound0, b: n(offset) } : bound0;
37
+ const options = [];
38
+ let walk = first;
39
+ for (let i = 0; i < 8 && walk.op === 'if'; i++, walk = walk.else) {
40
+ const value = walk.then;
41
+ const parts = atoms(walk.c);
42
+ if (!parts.some(p => equal(p, keyAtom)) || value.op !== 'const' || equal(value, init))
43
+ break;
44
+ const [one, ...more] = parts.filter(p => !equal(p, keyAtom));
45
+ if (!one)
46
+ break;
47
+ options.push({ value: value.value, guard: more.length ? { op: 'and', xs: [one, ...more] } : one });
48
+ }
49
+ if (!equal(walk, get(map, x(wr.each))) || !options.length)
50
+ continue;
51
+ const counters = Object.entries(m.step.state ?? {}).flatMap(([field, u]) => {
52
+ if (!uses.includes(`"name":${JSON.stringify(field)}`) || !equal(m.state[field], n(0)))
53
+ return [];
54
+ const reset = rootReset(u, n(0)), guard = reset && increase(reset.else, field);
55
+ return reset && guard && equal(reset.c, outer.c) ? [{ field, guard }] : [];
56
+ });
57
+ const fields = counters.flatMap(({ field, guard }) => {
58
+ // Prefer the first branch whose guard is covered by the increment. Later
59
+ // alternatives are fallback writes in the source's own branch order.
60
+ const opt = options.find(o => guardIncludes(guard, o.guard));
61
+ return opt ? [{ field, value: opt.value }] : [];
62
+ });
63
+ if (!fields.length || new Set(fields.map(f => f.value)).size !== fields.length)
64
+ continue;
65
+ out.push({ map, key, reset: subKey(outer.c, wr.each, x(key)), bound, offset, fields });
66
+ }
67
+ return out;
68
+ }
@@ -0,0 +1,5 @@
1
+ export declare const leanLibraries: {
2
+ readonly 'finite-fold': readonly [...string[], "../Count.lean", "./FiniteFold.lean"];
3
+ readonly weighted: readonly [...string[], "../GhostMap.lean", "../Sums.lean", "./GroupedTransport.lean"];
4
+ };
5
+ export type AggregateMechanism = keyof typeof leanLibraries;
@@ -0,0 +1,7 @@
1
+ // Topological order. Build and the staged replay use these exact packaged sources.
2
+ const machine = ['../Cert.lean', '../Kernel.lean', '../Progress.lean', '../StepLaw.lean',
3
+ '../Steps.lean', '../Sets.lean', '../Live.lean', '../Ghost.lean'];
4
+ export const leanLibraries = {
5
+ 'finite-fold': [...machine, '../Count.lean', './FiniteFold.lean'],
6
+ 'weighted': [...machine, '../GhostMap.lean', '../Sums.lean', './GroupedTransport.lean'],
7
+ };
@@ -0,0 +1,3 @@
1
+ export declare const theorem = "aggregate_claim";
2
+ export declare const axiomCommand = "\nset_option pp.fullNames true in\n#print axioms aggregate_claim\n";
3
+ export declare function exactAxioms(log: string): readonly string[];
@@ -0,0 +1,13 @@
1
+ import { answers, standard } from "../axiom-audit.js";
2
+ export const theorem = 'aggregate_claim';
3
+ export const axiomCommand = `\nset_option pp.fullNames true in\n#print axioms ${theorem}\n`;
4
+ // Check the public theorem specifically, not just a count of #print answers.
5
+ // With fullNames on, no short-name alias for an arbitrary axiom is allowed.
6
+ export function exactAxioms(log) {
7
+ const rows = answers(log);
8
+ const row = rows[0];
9
+ if (/\b(?:error|warning):[^\r\n]*(?:sorry|admit)|\berror:/i.test(log) || rows.length !== 1 || row?.name !== theorem
10
+ || row.axioms.some(a => !standard.includes(a)) || new Set(row.axioms).size !== row.axioms.length)
11
+ throw new Error('Lean did not report exactly the allowed axioms for the bound aggregate theorem.');
12
+ return row.axioms;
13
+ }
@@ -0,0 +1,15 @@
1
+ import { type AggregateMechanism } from './assets.js';
2
+ import { theorem } from './audit.js';
3
+ export declare const sha256: (text: string | Uint8Array) => string;
4
+ export type AggregateLeanReceipt = Readonly<{
5
+ schema: 'gdp-wired/lean-aggregate/v1';
6
+ inputSha256: string;
7
+ sourceSha256: string;
8
+ source: string;
9
+ libraries: Readonly<Record<string, string>>;
10
+ version: string;
11
+ theorem: typeof theorem;
12
+ axioms: readonly string[];
13
+ log: string;
14
+ }>;
15
+ export declare function runExactLean(mechanism: AggregateMechanism, generated: string, inputSha256: string, ms: number): Promise<AggregateLeanReceipt>;
@@ -0,0 +1,51 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { basename, join } from 'node:path';
6
+ import { leanLibraries } from "./assets.js";
7
+ import { exactAxioms, axiomCommand, theorem } from "./audit.js";
8
+ export const sha256 = (text) => createHash('sha256').update(text).digest('hex');
9
+ const release = '4.34.0', toolchain = `leanprover/lean4:v${release}`;
10
+ // Official 4.34.0 release, not an RC or a toolchain with the same version prefix.
11
+ const pinned = /^Lean \(version 4\.34\.0, [\w.-]+, commit 293d5d0c0c3f3dded4688b3ccd6a33939ac5102b, Release\)$/;
12
+ // Internal only: the public entry never accepts a Lean program, a log, an
13
+ // olean file, or a success marker from the caller.
14
+ export async function runExactLean(mechanism, generated, inputSha256, ms) {
15
+ const dir = mkdtempSync(join(tmpdir(), 'gdp-aggregate-'));
16
+ try {
17
+ const until = performance.now() + ms;
18
+ const run = (args) => new Promise((resolve, reject) => {
19
+ const timeout = Math.floor(until - performance.now());
20
+ if (timeout <= 0) {
21
+ reject(new Error('Lean replay deadline expired.'));
22
+ return;
23
+ }
24
+ execFile('lean', args, { cwd: dir, env: { ...process.env, ELAN_TOOLCHAIN: toolchain, LEAN_PATH: dir, LEAN_SRC_PATH: dir },
25
+ encoding: 'utf8', timeout, killSignal: 'SIGKILL', maxBuffer: 4 * 1024 * 1024 }, (error, stdout, stderr) => {
26
+ const log = `${stdout}\n${stderr}`.trim();
27
+ if (error || /\berror:|declaration uses 'sorry'/i.test(log))
28
+ reject(new Error(`Lean ${args.join(' ')} refused: ${log.slice(0, 2400) || error?.message}.`));
29
+ else
30
+ resolve(log);
31
+ });
32
+ });
33
+ const version = await run(['--version']);
34
+ if (!pinned.test(version))
35
+ throw new Error(`Expected exact Lean ${release}; got ${version.slice(0, 240)}.`);
36
+ const libraries = {};
37
+ for (const path of leanLibraries[mechanism]) {
38
+ const file = basename(path), body = readFileSync(new URL(path, import.meta.url));
39
+ libraries[file] = sha256(body);
40
+ writeFileSync(join(dir, file), body, { flag: 'wx' });
41
+ await run(['-o', file.replace(/\.lean$/, '.olean'), file]);
42
+ }
43
+ const source = `-- gdp-wired/lean-aggregate input sha256: ${inputSha256}\n${generated}${axiomCommand}`, file = 'Aggregate.lean';
44
+ writeFileSync(join(dir, file), source, { flag: 'wx' });
45
+ const log = await run([file]), axioms = exactAxioms(log);
46
+ return { schema: 'gdp-wired/lean-aggregate/v1', inputSha256, source, sourceSha256: sha256(source), libraries, version, theorem, axioms, log };
47
+ }
48
+ finally {
49
+ rmSync(dir, { recursive: true, force: true });
50
+ }
51
+ }
@@ -0,0 +1,19 @@
1
+ import type { Law, Machine } from '../../core/machine.js';
2
+ import { type AggregateLeanReceipt } from './exact.js';
3
+ import type { AggregateMechanism } from './assets.js';
4
+ export type { AggregateLeanReceipt } from './exact.js';
5
+ export type LeanAggregateOptions = Readonly<{
6
+ searchMs?: number;
7
+ leanMs?: number;
8
+ }>;
9
+ export type LeanAggregateVerdict = Readonly<{
10
+ kind: 'lean-checked';
11
+ verdict: 'checked in Lean, not by the kernel';
12
+ mechanism: AggregateMechanism;
13
+ receipt: AggregateLeanReceipt;
14
+ }> | Readonly<{
15
+ kind: 'not-checked';
16
+ reason: 'unsupported' | 'search' | 'lean';
17
+ detail: string;
18
+ }>;
19
+ export declare function proveLeanAggregate(machine: Machine, law: Law, options?: LeanAggregateOptions): Promise<LeanAggregateVerdict>;
@@ -0,0 +1,52 @@
1
+ import { Worker } from 'node:worker_threads';
2
+ import { admitAggregateSource } from "./source.js";
3
+ import { runExactLean, sha256 } from "./exact.js";
4
+ async function search(input) {
5
+ const suffix = import.meta.url.endsWith('.ts') ? 'ts' : 'js';
6
+ const worker = new Worker(new URL(`./worker.${suffix}`, import.meta.url), { workerData: input });
7
+ let timer;
8
+ try {
9
+ return await new Promise((resolve, reject) => {
10
+ timer = setTimeout(() => reject(new Error('Aggregate search/serialization deadline expired.')), input.ms + 5000);
11
+ worker.once('message', (result) => resolve(result));
12
+ worker.once('error', reject);
13
+ worker.once('exit', code => reject(new Error(`Aggregate worker exited without a candidate (${code}).`)));
14
+ });
15
+ }
16
+ finally {
17
+ clearTimeout(timer);
18
+ if (worker.threadId !== -1)
19
+ await worker.terminate();
20
+ }
21
+ }
22
+ // Deliberately separate from proveRule/proveSteps and native verdict types.
23
+ // The only success branch is after exact Lean checking and axiom validation.
24
+ export async function proveLeanAggregate(machine, law, options = {}) {
25
+ const { searchMs = 60_000, leanMs = 180_000 } = options;
26
+ const budget = (ms, max) => Number.isSafeInteger(ms) && ms > 0 && ms <= max;
27
+ if (!budget(searchMs, 60_000) || !budget(leanMs, 600_000))
28
+ return { kind: 'not-checked', reason: 'unsupported', detail: 'Use 1–60000 search ms and 1–600000 Lean ms.' };
29
+ let input;
30
+ try {
31
+ input = admitAggregateSource(machine, law);
32
+ }
33
+ catch (e) {
34
+ return { kind: 'not-checked', reason: 'unsupported', detail: String(e) };
35
+ }
36
+ let result;
37
+ try {
38
+ result = await search({ source: input, ms: searchMs });
39
+ }
40
+ catch (e) {
41
+ return { kind: 'not-checked', reason: 'search', detail: String(e) };
42
+ }
43
+ if (result.kind === 'refused')
44
+ return { kind: 'not-checked', reason: result.reason, detail: result.detail };
45
+ try {
46
+ const receipt = await runExactLean(result.mechanism, result.source, sha256(input), leanMs);
47
+ return { kind: 'lean-checked', verdict: 'checked in Lean, not by the kernel', mechanism: result.mechanism, receipt };
48
+ }
49
+ catch (e) {
50
+ return { kind: 'not-checked', reason: 'lean', detail: String(e) };
51
+ }
52
+ }
@@ -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;