gdp-wired 0.49.0 → 0.50.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 (81) hide show
  1. package/README.md +4 -0
  2. package/dist/core/candidate-seeds.d.ts +25 -0
  3. package/dist/core/candidate-seeds.js +90 -0
  4. package/dist/core/cli.js +3 -0
  5. package/dist/core/count-support.d.ts +1 -0
  6. package/dist/core/count-support.js +23 -2
  7. package/dist/core/counted-candidate-seeds.d.ts +12 -0
  8. package/dist/core/counted-candidate-seeds.js +31 -0
  9. package/dist/core/counts.js +9 -2
  10. package/dist/core/dsl.d.ts +23 -2
  11. package/dist/core/dsl.js +49 -16
  12. package/dist/core/exists.js +2 -1
  13. package/dist/core/field-laws.js +23 -5
  14. package/dist/core/infer.js +4 -3
  15. package/dist/core/lift-cli.d.ts +11 -0
  16. package/dist/core/lift-cli.js +113 -0
  17. package/dist/core/proof-output.d.ts +53 -0
  18. package/dist/core/proof-output.js +38 -0
  19. package/dist/core/quorum-laws.js +55 -16
  20. package/dist/kernel/function-instances.d.ts +45 -0
  21. package/dist/kernel/function-instances.js +460 -0
  22. package/dist/kernel/prove.d.ts +12 -3
  23. package/dist/kernel/prove.js +164 -90
  24. package/dist/lean-kernel/axiom-audit.d.ts +11 -0
  25. package/dist/lean-kernel/axiom-audit.js +50 -0
  26. package/dist/lean-kernel/emit.d.ts +25 -2
  27. package/dist/lean-kernel/emit.js +75 -10
  28. package/dist/lean-kernel/legacy-family-order.d.ts +1 -0
  29. package/dist/lean-kernel/legacy-family-order.js +26 -0
  30. package/dist/lean-kernel/library.js +22 -0
  31. package/dist/lean-kernel/lift/counted-source-data.d.ts +7 -0
  32. package/dist/lean-kernel/lift/counted-source-data.js +78 -0
  33. package/dist/lean-kernel/lift/index.d.ts +82 -0
  34. package/dist/lean-kernel/lift/index.js +116 -0
  35. package/dist/lean-kernel/lift/project.d.ts +4 -0
  36. package/dist/lean-kernel/lift/project.js +15 -0
  37. package/dist/lean-kernel/lift/proof-capture.d.ts +104 -0
  38. package/dist/lean-kernel/lift/proof-capture.js +216 -0
  39. package/dist/lean-kernel/lift/proof-codec.d.ts +28 -0
  40. package/dist/lean-kernel/lift/proof-codec.js +299 -0
  41. package/dist/lean-kernel/lift/proof-counted-source.d.ts +16 -0
  42. package/dist/lean-kernel/lift/proof-counted-source.js +68 -0
  43. package/dist/lean-kernel/lift/proof-frontier.d.ts +19 -0
  44. package/dist/lean-kernel/lift/proof-frontier.js +153 -0
  45. package/dist/lean-kernel/lift/proof-graph.d.ts +17 -0
  46. package/dist/lean-kernel/lift/proof-graph.js +130 -0
  47. package/dist/lean-kernel/lift/proof-parts.d.ts +29 -0
  48. package/dist/lean-kernel/lift/proof-parts.js +131 -0
  49. package/dist/lean-kernel/lift/proof-prelude.d.ts +2 -0
  50. package/dist/lean-kernel/lift/proof-prelude.js +38 -0
  51. package/dist/lean-kernel/lift/proof-witness.d.ts +30 -0
  52. package/dist/lean-kernel/lift/proof-witness.js +283 -0
  53. package/dist/lean-kernel/lift/shape.d.ts +5 -0
  54. package/dist/lean-kernel/lift/shape.js +57 -0
  55. package/dist/lean-kernel/lift/source-projection.d.ts +16 -0
  56. package/dist/lean-kernel/lift/source-projection.js +81 -0
  57. package/dist/lean-kernel/lift/source.d.ts +23 -0
  58. package/dist/lean-kernel/lift/source.js +111 -0
  59. package/dist/lean-kernel/lift/witness-alpha.d.ts +9 -0
  60. package/dist/lean-kernel/lift/witness-alpha.js +31 -0
  61. package/dist/lean-kernel/lift-legacy.d.ts +58 -0
  62. package/dist/lean-kernel/lift-legacy.js +84 -0
  63. package/dist/lean-kernel/lift-names.d.ts +22 -0
  64. package/dist/lean-kernel/lift-names.js +36 -0
  65. package/dist/lean-kernel/lift-simulation/index.d.ts +29 -0
  66. package/dist/lean-kernel/lift-simulation/index.js +352 -0
  67. package/dist/lean-kernel/lift-simulation/shape.d.ts +41 -0
  68. package/dist/lean-kernel/lift-simulation/shape.js +173 -0
  69. package/dist/lean-kernel/lift-special/index.d.ts +36 -0
  70. package/dist/lean-kernel/lift-special/index.js +241 -0
  71. package/dist/lean-kernel/lift-special/structural.d.ts +25 -0
  72. package/dist/lean-kernel/lift-special/structural.js +126 -0
  73. package/dist/lean-kernel/lift-typed/index.d.ts +35 -0
  74. package/dist/lean-kernel/lift-typed/index.js +256 -0
  75. package/dist/lean-kernel/lift-typed/roles.d.ts +17 -0
  76. package/dist/lean-kernel/lift-typed/roles.js +170 -0
  77. package/dist/lean-kernel/lift-typed/shape.d.ts +1 -0
  78. package/dist/lean-kernel/lift-typed/shape.js +12 -0
  79. package/dist/lean-kernel/lift.d.ts +30 -0
  80. package/dist/lean-kernel/lift.js +97 -0
  81. package/package.json +5 -1
@@ -0,0 +1,241 @@
1
+ import { boundOf, postName, witnessesOf } from "../../kernel/kernel.js";
2
+ import { retainedCMachineToLean } from "../emit.js";
3
+ import { splitEntryData } from "../lift/proof-parts.js";
4
+ import { sourceStructure, sourceLeanId } from "../lift/source.js";
5
+ import { proposeWitnessAlpha } from "../lift/witness-alpha.js";
6
+ import { liftProject, leanSource } from "../lift/project.js";
7
+ import { boundSyntaxValues, candidateBounds, eraseBound, publicCoverage, structuralWeakening, trueCondition, weakeningTerm } from "./structural.js";
8
+ const eq = (a, b) => sourceStructure(a) === sourceStructure(b);
9
+ function eligible(m) {
10
+ if (m.history || Object.keys(m.sums ?? {}).length || Object.keys(m.fns ?? {}).length || Object.keys(m.leasts ?? {}).length)
11
+ throw Error('unsupported bound-inclusion machine extension');
12
+ }
13
+ function operational(m) {
14
+ // Parameter labels only allocate the shared variable basis; SMachine has no
15
+ // params field. Preserve their actual uses in all emitted expressions.
16
+ return { ...m, name: '', params: [], counts: undefined, pre: undefined, assume: undefined, maps: m.maps ?? {}, inputMaps: m.inputMaps ?? [],
17
+ step: { ...m.step, state: m.step.state ?? {}, maps: m.step.maps ?? {}, flags: m.step.flags ?? {} } };
18
+ }
19
+ /** Call only after complete-graph validation and exact one-time term restoration.
20
+ * Null means no bound-erasure candidate. A candidate that is unsupported or
21
+ * ambiguous throws; callers MUST NOT turn that failure into strategy fallback.
22
+ * Emission is not checking: every returned theorem requires native Lean. */
23
+ export function tryEmitBoundInclusion(input) {
24
+ const { id, bundle, providedSourceAST: source, options } = input;
25
+ if (id !== sourceLeanId(source.id) || !/^bapa_[A-Za-z0-9_]+$/.test(id))
26
+ throw Error('unsafe or inconsistent full Lean prefix');
27
+ if (source.schema !== 'gdp-lift-source/v1')
28
+ throw Error('invalid provided source ABI');
29
+ sourceStructure(source);
30
+ const f = bundle.final;
31
+ if (!f?.machine || !f.laws || !f.proof)
32
+ return null;
33
+ const bounds = candidateBounds(source.machine, f.machine);
34
+ if (!bounds.length) {
35
+ if (!eq(source.machine.pre ?? trueCondition, f.machine.pre ?? trueCondition) && boundSyntaxValues(f.machine.pre ?? trueCondition).length)
36
+ throw Error('unsupported bound-erasure precondition');
37
+ return null;
38
+ }
39
+ if (bounds.length !== 1)
40
+ throw Error('ambiguous bound-erasure candidate');
41
+ const bound = bounds[0];
42
+ if (bundle.verdict && (!bundle.verdict.proven || !bundle.verdict.checked))
43
+ throw Error('unverified complete family');
44
+ eligible(source.machine);
45
+ eligible(f.machine);
46
+ if (!Object.keys(f.machine.counts ?? {}).length)
47
+ throw Error('bound inclusion requires counted family');
48
+ if (!f.laws.length || new Set(f.laws.map(l => l.name)).size !== f.laws.length)
49
+ throw Error('empty or ambiguous retained family');
50
+ const expected = f.laws.flatMap(l => [l.name + ' @start', l.name + ' @step']);
51
+ if (expected.some(k => !Object.hasOwn(f.proof.certs, k)) || Object.keys(f.proof.certs).some(k => !expected.includes(k)))
52
+ throw Error('incomplete or unrepresented retained family certificates');
53
+ const producer = eraseBound(f.machine, bound), coverage = publicCoverage(source.laws, f.laws, bound);
54
+ const pre = structuralWeakening(source.machine.pre ?? trueCondition, producer.pre ?? trueCondition);
55
+ const admission = structuralWeakening(source.machine.assume ?? trueCondition, producer.assume ?? trueCondition);
56
+ if (!pre || !admission)
57
+ throw Error('unsupported structural source admission');
58
+ // Only exact operations, local quantified/row alpha, and extra count maps are
59
+ // supported. The corresponding equalities and capture avoidance are checked
60
+ // independently in emitted Lean; this preflight is not a semantic assertion.
61
+ const alpha = proposeWitnessAlpha(operational(source.machine), operational(producer));
62
+ const rs = alpha?.renames ?? [], rows = alpha?.rows ?? [];
63
+ for (const [name, d] of Object.entries(source.machine.counts ?? {}))
64
+ if (!eq(d, producer.counts?.[name]))
65
+ throw Error('unsupported source count change: ' + name);
66
+ for (const n of [options.maxOutputBytes, options.maxFiles, options.heartbeats, options.recursionDepth])
67
+ if (!Number.isSafeInteger(n) || n < 1)
68
+ throw Error('finite positive generator limits required');
69
+ const vars = new Set([...source.machine.params, ...source.machine.inputs, ...Object.keys(source.machine.state), ...Object.keys(source.machine.step.state ?? {})]);
70
+ const maps = new Set([...Object.keys(source.machine.maps ?? {}), ...Object.keys(source.machine.step.maps ?? {}), ...(source.machine.inputMaps ?? [])]);
71
+ const visit = (x) => {
72
+ if (!x || typeof x !== 'object')
73
+ return;
74
+ if (Array.isArray(x)) {
75
+ x.forEach(visit);
76
+ return;
77
+ }
78
+ const o = x;
79
+ if (o.op === 'var')
80
+ vars.add(o.name);
81
+ if (o.op === 'get')
82
+ maps.add(o.map);
83
+ Object.values(o).forEach(visit);
84
+ };
85
+ visit(source.machine);
86
+ visit(source.laws);
87
+ for (const [name, q] of Object.entries(source.machine.step.flags ?? {})) {
88
+ vars.add('?' + name);
89
+ if (q.op === 'all') {
90
+ boundOf(q).forEach(x => vars.add(x));
91
+ witnessesOf(name, q).forEach(x => vars.add(x));
92
+ }
93
+ }
94
+ for (const w of Object.values(source.machine.step.maps ?? {}))
95
+ if ('each' in w)
96
+ vars.add(w.each);
97
+ for (const l of [...source.laws, ...(source.machine.facts ?? [])]) {
98
+ if (l.forall)
99
+ vars.add(l.forall);
100
+ l.keys?.forEach(x => vars.add(x));
101
+ }
102
+ for (const [name, d] of Object.entries(source.machine.counts ?? {})) {
103
+ maps.add(name);
104
+ maps.add(postName(name));
105
+ vars.add(d.j);
106
+ vars.add(d.key);
107
+ vars.add(d.lo ?? d.j);
108
+ }
109
+ for (const r of rs) {
110
+ vars.add('?' + r.flag);
111
+ vars.add(r.old);
112
+ vars.add(r.fresh);
113
+ }
114
+ for (const r of rows) {
115
+ vars.add(r.old);
116
+ vars.add(r.fresh);
117
+ maps.add(r.map);
118
+ }
119
+ let sourceDefs = '';
120
+ const raw = id + '_retained';
121
+ // Regenerate ALL retained entries from the capsule, not a frozen Proofs file.
122
+ // retainedCMachineToLean validates native certificate data without any search.
123
+ const text = retainedCMachineToLean(raw, f.machine, f.laws, f.proof, { extraVars: [...vars], extraMaps: [...maps], after: b => {
124
+ const m = source.machine, counts = Object.entries(m.counts ?? {}), normal = { ...m, counts: undefined, inputMaps: [...(m.inputMaps ?? []), ...counts.map(([n]) => n)] };
125
+ sourceDefs = `def ${id}_source : SMachine := ${b.machine(normal)}
126
+ def ${id}_source_decls : List CDecl := ${b.decls(m.counts)}
127
+ def ${id}_source_renames : List QAlpha.Rename := [${rs.map(r => `⟨${b.ix('?' + r.flag)}, ${b.ix(r.old)}, ${b.ix(r.fresh)}⟩`).join(', ')}]
128
+ def ${id}_source_row_renames : List RowAlpha.Rename := [${rows.map(r => `⟨${b.mx(r.map)}, ${b.ix(r.old)}, ${b.ix(r.fresh)}⟩`).join(', ')}]
129
+ def ${id}_fresh : List Nat := [${Object.keys(f.machine.counts ?? {}).filter(n => !Object.hasOwn(m.counts ?? {}, n)).map(b.mx).join(', ')}]
130
+ ${source.laws.map((l, j) => `def ${id}_source_law${j} : MLaw := ⟨${b.condition(l.holds)}, ${l.forall ? `some ${b.ix(l.forall)}` : 'none'}⟩\ndef ${id}_source_keys${j} : List Nat := [${(l.keys ?? []).map(b.ix).join(', ')}]`).join('\n')}`;
131
+ return '';
132
+ } });
133
+ const match = new RegExp(`\\n(?:noncomputable )?def ${raw}_proof : List (CEntryF|CEntry) := `).exec(text), check = text.indexOf(`\ntheorem ${raw}_check :`);
134
+ if (!match || check < 0)
135
+ throw Error('unsupported retained emission layout');
136
+ const entries = splitEntryData(text.slice(match.index + match[0].length, check));
137
+ if (entries.length !== f.laws.length)
138
+ throw Error('lost retained family entry');
139
+ const entryType = match[1], hasAlpha = text.includes(`def ${raw}_checkedMachine :`);
140
+ const header = (imports) => imports.map(s => 'import ' + s).join('\n') + `\nopen Kern Cert\nset_option maxHeartbeats ${options.heartbeats}\nset_option maxRecDepth ${options.recursionDepth}\n`;
141
+ const names = entries.map((_, j) => id + '_entry' + j);
142
+ let definitions = text.slice(0, match.index) + '\n';
143
+ definitions += `def ${id}_bound : Nat := ${bound}
144
+ def ${id}_machine : SMachine := Bapa.CertificateBoundErasure.machine ${id}_bound ${raw}_machine
145
+ def ${id}_decls : List CDecl := ${raw}_decls.map (Bapa.CertificateBoundErasure.countDeclaration ${id}_bound)
146
+ `;
147
+ definitions += entries.map((e, j) => `noncomputable def ${names[j]}_raw : ${entryType} := ${e}\nnoncomputable def ${names[j]} : CEntryF := Bapa.StructuralWeakening.countedEntryF ${id}_bound (${names[j]}_raw${entryType === 'CEntry' ? '.toF' : ''})`).join('\n');
148
+ definitions += `\nnoncomputable def ${id}_family : List CEntryF := [${names.join(', ')}]\n${sourceDefs}\n`;
149
+ const checked = hasAlpha ? id + '_checkedMachine' : id + '_machine';
150
+ if (hasAlpha)
151
+ definitions += `def ${checked} : SMachine := QAlpha.renameAll ${id}_machine ${raw}_renames\n`;
152
+ const project = liftProject(definitions, { name: 'BapaProof' }), defsModule = id + '_Defs';
153
+ for (const n of ['CertificateBoundErasure', 'CountedSourceProjection', 'CountedNoninterference', 'CountedSourceBridge', 'SourceInclusion'])
154
+ project[n + '.lean'] = leanSource(n);
155
+ project['StructuralWeakening.lean'] = leanSource('StructuralWeakening');
156
+ project[defsModule + '.lean'] = header(['QAlpha', 'RowAlpha', 'StructuralWeakening']) + definitions;
157
+ const requiredTheorems = [];
158
+ const printTheorem = (name) => { requiredTheorems.push(name); return '\n#print axioms ' + name + '\n'; };
159
+ const entryModules = names.map((name, j) => {
160
+ const module = id + '_Entry' + j, thm = name + '_check';
161
+ project[module + '.lean'] = header([defsModule]) + `theorem ${thm} : cEntryCheckF ${checked} ${id}_decls (${id}_family.map (·.e)) ${name} = true := by decide +kernel\n` + printTheorem(thm);
162
+ return module;
163
+ });
164
+ const global = id + '_global', family = id + '_laws';
165
+ let familyBody = `theorem ${global} : cGlobalOkF ${checked} ${id}_decls (${id}_family.map (·.e)) = true := by decide +kernel
166
+ theorem ${id}_check : checkCMachineF ${checked} ${id}_decls ${id}_family = true := by
167
+ apply checkCMachineF_of_parts _ _ _ ${global}
168
+ intro ce hce
169
+ simp only [${id}_family, List.mem_cons, List.mem_singleton, List.not_mem_nil, or_false] at hce
170
+ rcases hce with ${names.map(() => 'rfl').join(' | ')}
171
+ ${names.map(n => ' · exact ' + n + '_check').join('\n')}
172
+ theorem ${family} : ∀ ρ M, CReach ${id}_machine ${id}_decls ρ M → ∀ e ∈ ${id}_family, e.e.Holds ρ (withCnt ${id}_decls ρ M) :=
173
+ ${hasAlpha ? `QAlpha.cmachineF_sound ${id}_machine ${raw}_renames ${id}_decls ${id}_family (by decide +kernel) ${id}_check` : `cmachineF_sound ${id}_machine ${id}_decls ${id}_family ${id}_check`}
174
+ `;
175
+ const transported = id + '_transported_laws';
176
+ familyBody += `theorem ${transported} : ∀ ρ M, CReach ${id}_machine ${id}_decls ρ M → ∀ e ∈ ${id}_family, e.e.Holds ρ (withCnt ${id}_decls ρ M) := ${family}\n`;
177
+ familyBody += printTheorem(global) + printTheorem(id + '_check') + printTheorem(family) + printTheorem(transported);
178
+ project[id + '_Family.lean'] = header([defsModule, ...entryModules]) + familyBody;
179
+ const sourceTheorems = source.laws.map((_, j) => id + '_source_law' + j + '_holds');
180
+ // Finite declaration membership is constructor elimination, not DecidableEq
181
+ // over CDecl (which has no such instance). No fixed number of declarations.
182
+ const membership = (list, count, publicCase) => `by
183
+ intro d hd${publicCase ? ' hn' : ''}
184
+ simp only [${list}, List.mem_cons, List.mem_singleton, List.not_mem_nil, or_false] at hd
185
+ ${count ? `rcases hd with ${Array(count).fill('rfl').join(' | ')}\n all_goals simp_all [${id}_source_decls, ${id}_decls, ${raw}_decls, ${id}_fresh, ${id}_bound, Bapa.CertificateBoundErasure.countDeclaration, Bapa.CertificateBoundErasure.expr, Bapa.CertificateBoundErasure.condition]` : 'cases hd'}`;
186
+ const sourceMem = membership(id + '_source_decls', Object.keys(source.machine.counts ?? {}).length, false);
187
+ const publicMem = membership(`${id}_decls, ${raw}_decls, List.map_cons, List.map_nil`, Object.keys(f.machine.counts ?? {}).length, true);
188
+ let body = `def ${id}_source_qalpha : SMachine := QAlpha.renameAll ${id}_source ${id}_source_renames
189
+ def ${id}_source_alpha : SMachine := RowAlpha.renameAll ${id}_source_qalpha ${id}_source_row_renames
190
+ def ${id}_source_plus : SMachine := {${id}_source_alpha with carried := ${id}_source_alpha.carried ++ ${id}_fresh}
191
+ theorem ${id}_alpha_valid : QAlpha.validAll ${id}_source ${id}_source_renames = true := by decide +kernel
192
+ theorem ${id}_row_valid : RowAlpha.validAll ${id}_source_qalpha ${id}_source_row_renames = true := by decide +kernel
193
+ theorem ${id}_view (ρ M ι κ) : sView ${id}_source_plus ρ M ι κ = sView ${id}_machine ρ M ι κ := by rfl
194
+ theorem ${id}_next (ρ M ι κ) : sNext ${id}_source_plus ρ M ι κ = sNext ${id}_machine ρ M ι κ := by rfl
195
+ theorem ${id}_pre : Bapa.StructuralWeakening.Subsumes ${id}_source_plus.f.m.pre ${id}_machine.f.m.pre := ${weakeningTerm(pre)}
196
+ theorem ${id}_admission : Bapa.StructuralWeakening.Subsumes ${id}_source_plus.f.m.assume ${id}_machine.f.m.assume := ${weakeningTerm(admission)}
197
+ theorem ${id}_inclusion : SourceInclusion ${id}_source_plus ${id}_machine where
198
+ inputs := by rfl
199
+ carried := by rfl
200
+ initial := by rfl
201
+ startMaps := by intro M h; exact h
202
+ pre := Bapa.StructuralWeakening.sound ${id}_pre
203
+ facts := by intro ρ M h; exact h
204
+ pfacts := by intro ρ M h; exact h
205
+ admission := by
206
+ intro ρ M ι κ h
207
+ rw [${id}_view] at h
208
+ exact Bapa.StructuralWeakening.sound ${id}_admission _ _ h
209
+ next := by intro ρ M ι κ _; exact ${id}_next ρ M ι κ
210
+ `;
211
+ coverage.indices.forEach((k, j) => {
212
+ const entry = names[k], weak = id + '_weak' + j, lawImp = id + '_law_implication' + j;
213
+ body += `noncomputable def ${weak} : SEntry := {${entry}.e with law := ${id}_source_law${j}, keys2 := ${id}_source_keys${j}}
214
+ theorem ${lawImp} : SourceLawImplication ${entry}.e ${weak} :=
215
+ Bapa.StructuralWeakening.law (by rfl) (by rfl) (${weakeningTerm(coverage.proofs[j])})
216
+ theorem ${sourceTheorems[j]} (ρ M) (hr : CReach ${id}_source ${id}_source_decls ρ M) :
217
+ holdsOver ${id}_source_law${j} (withCnt ${id}_source_decls ρ M) ${id}_source_keys${j} ρ := by
218
+ have hq := (QAlpha.renameAll_equiv ${id}_source ${id}_source_renames ${id}_alpha_valid).symm.creach_imp ${id}_source_decls hr
219
+ have ha : CReach ${id}_source_alpha ${id}_source_decls ρ M :=
220
+ (RowAlpha.renameAll_equiv ${id}_source_qalpha ${id}_source_row_renames ${id}_row_valid).symm.creach_imp ${id}_source_decls hq
221
+ have h := bapa_counted_source_law ${id}_source_alpha ${id}_source_decls ${id}_decls ${id}_fresh ${id}_fresh ${entry}.e
222
+ (by decide +kernel) (by decide +kernel) (by decide +kernel)
223
+ (by decide +kernel) (by decide +kernel) (by decide +kernel)
224
+ (${sourceMem}) (${publicMem}) (stepAvoids_of_check _ _ (by decide +kernel))
225
+ (by decide +kernel)
226
+ (by
227
+ intro X N hh
228
+ exact ${family} X N (${id}_inclusion.creach ${id}_decls hh) ${entry} (by simp [${id}_family])) ρ M ha
229
+ exact ${lawImp} ρ _ h
230
+ `;
231
+ body += printTheorem(lawImp) + printTheorem(sourceTheorems[j]);
232
+ });
233
+ for (const t of [id + '_alpha_valid', id + '_row_valid', id + '_pre', id + '_admission', id + '_inclusion'])
234
+ body += printTheorem(t);
235
+ project['BapaProof.lean'] = header([id + '_Family', 'StructuralWeakening', 'RowAlpha']) + body;
236
+ const modules = Object.keys(project).filter(n => n.endsWith('.lean') && n !== 'lakefile.lean').map(n => n.slice(0, -5));
237
+ project['lakefile.lean'] = 'import Lake\nopen Lake DSL\npackage boundinclusion\n@[default_target]\nlean_lib BoundInclusion where\n roots := #[' + modules.map(n => '`' + n).join(', ') + ']\n';
238
+ if (Object.keys(project).length > options.maxFiles || Object.values(project).reduce((n, s) => n + Buffer.byteLength(s), 0) > options.maxOutputBytes)
239
+ throw Error('complete bound-inclusion project exceeds output budget');
240
+ return { project, familyTheorem: transported, sourceTheorems, publicLawIndices: coverage.indices, requiredTheorems, bound, kind: 'bound-inclusion', parts: { familySize: entries.length, primaryObligations: 2 * entries.length } };
241
+ }
@@ -0,0 +1,25 @@
1
+ import type { C, Law, Machine } from '../../core/machine.js';
2
+ export declare const trueCondition: C;
3
+ /** Mirror only the provided Lean candidate transform, including nested E.ite.
4
+ * This is used for proposals, never as evidence that an erased proof checks. */
5
+ export declare function eraseBound<T>(value: T, bound: number): T;
6
+ export type Weakening = {
7
+ kind: 'refl' | 'top' | 'bot';
8
+ } | {
9
+ kind: 'orLeft' | 'orRight' | 'andLeft' | 'andRight' | 'neg';
10
+ child: Weakening;
11
+ } | {
12
+ kind: 'orElim' | 'andIntro';
13
+ left: Weakening;
14
+ right: Weakening;
15
+ };
16
+ /** Bounded syntactic AND/OR subsumption. Arithmetic formulas are opaque
17
+ * atoms; negation is contravariant. No arithmetic, SMT, theorem search or evaluation of source programs. */
18
+ export declare function structuralWeakening(strong: C, weak: C): Weakening | null;
19
+ export declare function weakeningTerm(p: Weakening): string;
20
+ export declare function boundSyntaxValues(pre: C): number[];
21
+ export declare function candidateBounds(source: Machine, producer: Machine): number[];
22
+ export declare function publicCoverage(laws: Law[], retained: Law[], bound: number): {
23
+ indices: number[];
24
+ proofs: Weakening[];
25
+ };
@@ -0,0 +1,126 @@
1
+ import { sourceStructure } from "../lift/source.js";
2
+ export const trueCondition = { op: '<=', a: { op: 'const', value: 0 }, b: { op: 'const', value: 0 } };
3
+ const falseCondition = { op: '<', a: { op: 'const', value: 0 }, b: { op: 'const', value: 0 } };
4
+ const same = (a, b) => sourceStructure(a) === sourceStructure(b);
5
+ /** Mirror only the provided Lean candidate transform, including nested E.ite.
6
+ * This is used for proposals, never as evidence that an erased proof checks. */
7
+ export function eraseBound(value, bound) {
8
+ if (!Number.isSafeInteger(bound) || bound <= 0)
9
+ throw Error('invalid bound');
10
+ const visit = (x) => {
11
+ if (!x || typeof x !== 'object')
12
+ return x;
13
+ if (Array.isArray(x))
14
+ return x.map(visit);
15
+ const o = x, b = o.b;
16
+ if ((o.op === '<' || o.op === '<=') && b?.op === 'const' && b.value === bound)
17
+ return trueCondition;
18
+ return Object.fromEntries(Object.entries(o).map(([k, v]) => [k, visit(v)]));
19
+ };
20
+ return visit(value);
21
+ }
22
+ function shape(c) {
23
+ if (c.op === 'not')
24
+ return { op: 'not', inner: shape(c.x) };
25
+ if (c.op !== 'and' && c.op !== 'or')
26
+ return { atom: c };
27
+ const neutral = c.op === 'and' ? trueCondition : falseCondition;
28
+ const xs = c.xs.map(shape);
29
+ if (!xs.length)
30
+ return { atom: neutral };
31
+ if (xs.length === 1)
32
+ return { op: c.op, left: xs[0], right: { atom: neutral } };
33
+ return xs.slice(0, -1).reduceRight((right, left) => ({ op: c.op, left, right }), xs.at(-1));
34
+ }
35
+ /** Bounded syntactic AND/OR subsumption. Arithmetic formulas are opaque
36
+ * atoms; negation is contravariant. No arithmetic, SMT, theorem search or evaluation of source programs. */
37
+ export function structuralWeakening(strong, weak) {
38
+ let visits = 0;
39
+ const go = (a, b, depth) => {
40
+ if (++visits > 100000 || depth > 256)
41
+ throw Error('structural weakening limit exceeded');
42
+ if (same(a, b))
43
+ return { kind: 'refl' };
44
+ if ('atom' in b && same(b.atom, trueCondition))
45
+ return { kind: 'top' };
46
+ if ('atom' in a && same(a.atom, falseCondition))
47
+ return { kind: 'bot' };
48
+ if ('op' in a && a.op === 'not' && 'op' in b && b.op === 'not') {
49
+ const child = go(b.inner, a.inner, depth + 1);
50
+ return child ? { kind: 'neg', child } : null;
51
+ }
52
+ if ('op' in a && a.op === 'or') {
53
+ const left = go(a.left, b, depth + 1), right = left && go(a.right, b, depth + 1);
54
+ return left && right ? { kind: 'orElim', left, right } : null;
55
+ }
56
+ if ('op' in b && b.op === 'and') {
57
+ const left = go(a, b.left, depth + 1), right = left && go(a, b.right, depth + 1);
58
+ return left && right ? { kind: 'andIntro', left, right } : null;
59
+ }
60
+ if ('op' in a && a.op === 'and') {
61
+ const left = go(a.left, b, depth + 1);
62
+ if (left)
63
+ return { kind: 'andLeft', child: left };
64
+ const right = go(a.right, b, depth + 1);
65
+ if (right)
66
+ return { kind: 'andRight', child: right };
67
+ }
68
+ if ('op' in b && b.op === 'or') {
69
+ const left = go(a, b.left, depth + 1);
70
+ if (left)
71
+ return { kind: 'orLeft', child: left };
72
+ const right = go(a, b.right, depth + 1);
73
+ if (right)
74
+ return { kind: 'orRight', child: right };
75
+ }
76
+ return null;
77
+ };
78
+ return go(shape(strong), shape(weak), 0);
79
+ }
80
+ export function weakeningTerm(p) {
81
+ const prefix = 'Bapa.StructuralWeakening.Subsumes.';
82
+ if (p.kind === 'refl' || p.kind === 'top' || p.kind === 'bot')
83
+ return prefix + p.kind + ' _';
84
+ if ('child' in p)
85
+ return `${prefix}${p.kind} (${weakeningTerm(p.child)})`;
86
+ if ('left' in p)
87
+ return `${prefix}${p.kind} (${weakeningTerm(p.left)}) (${weakeningTerm(p.right)})`;
88
+ throw Error('unsupported weakening constructor');
89
+ }
90
+ export function boundSyntaxValues(pre) {
91
+ const values = new Set();
92
+ const visit = (c) => {
93
+ if (c.op === 'and' || c.op === 'or')
94
+ c.xs.forEach(visit);
95
+ else if (c.op === '<' || c.op === '<=') {
96
+ if (c.b.op === 'const' && Number.isSafeInteger(c.b.value) && c.b.value > 0)
97
+ values.add(c.b.value);
98
+ }
99
+ };
100
+ // Only positive upper bounds admitted in the producer precondition qualify;
101
+ // constants in value encodings, laws and arithmetic do not select a cap.
102
+ visit(pre);
103
+ return [...values];
104
+ }
105
+ export function candidateBounds(source, producer) {
106
+ const pre = producer.pre ?? trueCondition;
107
+ return boundSyntaxValues(pre).filter(b => !same(pre, eraseBound(pre, b)) && !!structuralWeakening(source.pre ?? trueCondition, eraseBound(pre, b)));
108
+ }
109
+ export function publicCoverage(laws, retained, bound) {
110
+ const ordinary = (l) => !['some', 'ex', 'witness', 'stated', 'finite'].some(k => l[k] !== undefined);
111
+ if (!laws.length || laws.some(l => !ordinary(l)))
112
+ throw Error('unsupported public law metadata');
113
+ const proofs = [], indices = laws.map(l => {
114
+ const matches = retained.flatMap((r, i) => {
115
+ if (!ordinary(r) || l.forall !== r.forall || !same(l.keys ?? [], r.keys ?? []))
116
+ return [];
117
+ const proof = structuralWeakening(eraseBound(r.holds, bound), l.holds);
118
+ return proof ? [{ i, proof }] : [];
119
+ });
120
+ if (matches.length !== 1)
121
+ throw Error(`unsupported or ambiguous structural public coverage (${matches.length} matches)`);
122
+ proofs.push(matches[0].proof);
123
+ return matches[0].i;
124
+ });
125
+ return { indices, proofs };
126
+ }
@@ -0,0 +1,35 @@
1
+ import type { Machine, Law } from '../../core/machine.js';
2
+ import type { ProofOutputNode } from '../../core/proof-output.js';
3
+ import type { GenericLiftSource } from '../lift/source.js';
4
+ import type { PartOptions } from '../lift/proof-parts.js';
5
+ import { type Roles } from './roles.js';
6
+ export type TypedBoundBundle = {
7
+ original: {
8
+ machine: Machine;
9
+ laws: Law[];
10
+ };
11
+ proof?: ProofOutputNode;
12
+ verdict: {
13
+ proven: boolean;
14
+ checked: boolean;
15
+ };
16
+ final?: unknown;
17
+ };
18
+ export type TypedBoundOptions = {
19
+ id: string;
20
+ bundle: TypedBoundBundle;
21
+ providedSourceAST: GenericLiftSource;
22
+ options: PartOptions;
23
+ };
24
+ export type TypedBoundEmission = {
25
+ project: Record<string, string>;
26
+ familyTheorem: string;
27
+ sourceTheorems: string[];
28
+ publicLawIndices: number[];
29
+ requiredTheorems: string[];
30
+ roles: Roles;
31
+ status: 'EMITTED_NOT_CHECKED';
32
+ };
33
+ /** After caller-owned capsule/hash validation and single term restoration.
34
+ * No protocol lookup, search, old generated Lean, or schema rewriting occurs. */
35
+ export declare function tryTypedBoundSubstitution({ id, bundle, providedSourceAST: source, options }: TypedBoundOptions): TypedBoundEmission | null;