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,130 @@
1
+ // Streaming, order/descriptor/alias preserving diagnostic graph codec.
2
+ // No code is deserialized. An incomplete directory has no manifest and is invalid.
3
+ import { mkdirSync, readdirSync, openSync, closeSync, writeSync, fsyncSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { types } from 'node:util';
6
+ import { createHash } from 'node:crypto';
7
+ const SHARD = 8 * 1024 * 1024, LINE = 1024 * 1024, TEXT = 16 * 1024;
8
+ const builtin = { object: Object.prototype, null: null, array: Array.prototype, map: Map.prototype, set: Set.prototype, error: Error.prototype, typeError: TypeError.prototype, rangeError: RangeError.prototype, referenceError: ReferenceError.prototype, syntaxError: SyntaxError.prototype, uriError: URIError.prototype, evalError: EvalError.prototype, aggregateError: AggregateError.prototype };
9
+ function writeAll(fd, data) { let offset = 0; while (offset < data.length) {
10
+ const n = writeSync(fd, data, offset, data.length - offset);
11
+ if (n <= 0)
12
+ throw Error('short capsule write');
13
+ offset += n;
14
+ } }
15
+ export function writeGraphCapsule(directory, root, options = {}) {
16
+ mkdirSync(directory, { recursive: true });
17
+ if (readdirSync(directory).length)
18
+ throw Error('graph output must be a new empty directory');
19
+ const prototypes = { ...builtin, ...options.prototypes }, tags = new Map(), ids = new WeakMap(), pending = [], shards = [];
20
+ for (const [name, prototype] of Object.entries(prototypes))
21
+ if (!tags.has(prototype))
22
+ tags.set(prototype, name);
23
+ let fd, bytes = 0, parts = [], buffered = 0, digest = createHash('sha256'), stringCount = 0;
24
+ const flush = () => { if (!buffered)
25
+ return; const data = Buffer.from(parts.join('')); writeAll(fd, data); digest.update(data); parts = []; buffered = 0; };
26
+ const close = () => { if (fd === undefined)
27
+ return; flush(); fsyncSync(fd); closeSync(fd); fd = undefined; shards.push({ name: `shard-${String(shards.length).padStart(6, '0')}.jsonl`, bytes, sha256: digest.digest('hex') }); };
28
+ const emit = (record) => {
29
+ const line = JSON.stringify(record) + '\n', size = Buffer.byteLength(line);
30
+ if (size > LINE)
31
+ throw Error('graph record exceeds line bound');
32
+ if (fd !== undefined && bytes + size > SHARD)
33
+ close();
34
+ if (fd === undefined) {
35
+ fd = openSync(join(directory, `shard-${String(shards.length).padStart(6, '0')}.jsonl`), 'wx');
36
+ bytes = 0;
37
+ digest = createHash('sha256');
38
+ }
39
+ parts.push(line);
40
+ buffered += size;
41
+ bytes += size;
42
+ if (buffered >= 256 * 1024)
43
+ flush();
44
+ };
45
+ const ref = (value) => {
46
+ if (value === undefined)
47
+ return ['u'];
48
+ if (value === null || typeof value === 'boolean')
49
+ return ['v', value];
50
+ if (typeof value === 'number') {
51
+ const bits = Buffer.allocUnsafe(8);
52
+ bits.writeDoubleBE(value);
53
+ return ['n', bits.toString('hex')];
54
+ }
55
+ if (typeof value === 'bigint')
56
+ return ['b', String(value)];
57
+ if (typeof value === 'string') {
58
+ if (value.length <= TEXT)
59
+ return ['v', value];
60
+ const id = stringCount++;
61
+ emit(['string', id]);
62
+ for (let i = 0; i < value.length; i += TEXT)
63
+ emit(['text', id, value.slice(i, i + TEXT)]);
64
+ emit(['string-end', id]);
65
+ return ['s', id];
66
+ }
67
+ if (typeof value !== 'object')
68
+ throw Error('functions and symbols are not graph data');
69
+ let id = ids.get(value);
70
+ if (id === undefined) {
71
+ id = pending.length;
72
+ ids.set(value, id);
73
+ pending.push(value);
74
+ }
75
+ return ['r', id];
76
+ };
77
+ try {
78
+ emit(['root', ref(root)]);
79
+ for (let id = 0; id < pending.length; id++) {
80
+ const object = pending[id];
81
+ if (types.isProxy(object))
82
+ throw Error('proxy graph data is not lossless');
83
+ const prototype = Object.getPrototypeOf(object);
84
+ const tag = tags.get(prototype);
85
+ if (tag === undefined)
86
+ throw Error('unsupported graph prototype');
87
+ emit(['node', id, tag, Array.isArray(object) ? object.length : null]);
88
+ if (tag === 'map')
89
+ for (const [key, value] of object)
90
+ emit(['map', id, ref(key), ref(value)]);
91
+ if (tag === 'set')
92
+ for (const value of object)
93
+ emit(['set', id, ref(value)]);
94
+ for (const key of Reflect.ownKeys(object)) {
95
+ if (typeof key !== 'string')
96
+ throw Error('symbol graph property');
97
+ const d = Object.getOwnPropertyDescriptor(object, key);
98
+ if (!('value' in d))
99
+ throw Error('accessor graph property');
100
+ if (tag === 'array' && key === 'length')
101
+ continue;
102
+ emit(['prop', id, ref(key), ref(d.value), !!d.writable, !!d.enumerable, !!d.configurable]);
103
+ }
104
+ const metadata = options.metadata?.(object);
105
+ if (metadata !== undefined)
106
+ emit(['meta', id, ref(metadata)]);
107
+ emit(['seal', id, Object.isExtensible(object), tag === 'array' ? !!Object.getOwnPropertyDescriptor(object, 'length').writable : true]);
108
+ pending[id] = undefined;
109
+ }
110
+ close();
111
+ const manifest = { schema: 'closing-graph/v1', complete: true, nodes: pending.length, strings: stringCount, shards };
112
+ const out = openSync(join(directory, 'manifest.json'), 'wx');
113
+ try {
114
+ writeAll(out, Buffer.from(JSON.stringify(manifest) + '\n'));
115
+ fsyncSync(out);
116
+ }
117
+ finally {
118
+ closeSync(out);
119
+ }
120
+ return manifest;
121
+ }
122
+ finally {
123
+ if (fd !== undefined) {
124
+ try {
125
+ closeSync(fd);
126
+ }
127
+ catch { /* retain incomplete files, no manifest */ }
128
+ }
129
+ }
130
+ }
@@ -0,0 +1,29 @@
1
+ import type { FamilyBundle } from './proof-capture.js';
2
+ import { type Frontier } from './proof-frontier.js';
3
+ export type PartOptions = {
4
+ weightLimit: bigint;
5
+ maxOutputBytes: number;
6
+ maxFiles: number;
7
+ heartbeats: number;
8
+ recursionDepth: number;
9
+ };
10
+ export type GeneratedPart = {
11
+ module: string;
12
+ role: string;
13
+ text: string;
14
+ sha256: string;
15
+ };
16
+ export type CountedParts = {
17
+ status: 'EMITTED_NOT_CHECKED';
18
+ files: GeneratedPart[];
19
+ frontiers: {
20
+ law: string;
21
+ phase: 'start' | 'step';
22
+ frontier: Frontier;
23
+ }[];
24
+ familySize: number;
25
+ primaryObligations: number;
26
+ finalModule: string;
27
+ };
28
+ export declare function splitEntryData(text: string): string[];
29
+ export declare function emitCountedParts(id: string, bundle: FamilyBundle, options: PartOptions): CountedParts;
@@ -0,0 +1,131 @@
1
+ // Source generator for the retained counted family. Run ONLY in the separately
2
+ // authorized recheck worker after exact term-prelude replay. No search fallback.
3
+ import { createHash } from 'node:crypto';
4
+ import { retainedCMachineToLean } from "../emit.js";
5
+ import { makeFrontier, verifyFrontier, structuralWeight } from "./proof-frontier.js";
6
+ const sha = (s) => createHash('sha256').update(s).digest('hex');
7
+ const list = (xs) => '[' + xs.join(', ') + ']';
8
+ // Frontier addresses contain only the ASCII branch digits 0 and 1.
9
+ const address = (s) => list(s.split('').map(x => x === '1' ? 'true' : 'false'));
10
+ // Lean constructor data only; brackets/tuples nested inside each entry must not
11
+ // be mistaken for the outer list. The emitter emits no string literals here.
12
+ export function splitEntryData(text) {
13
+ const source = text.trim();
14
+ if (!source.startsWith('[') || !source.endsWith(']'))
15
+ throw Error('expected emitted entry list');
16
+ const values = [], stack = [];
17
+ let start = 1;
18
+ const pairs = { ')': '(', ']': '[', '}': '{', '⟩': '⟨' };
19
+ for (let i = 1; i < source.length - 1; i++) {
20
+ const c = source[i];
21
+ if (c === '"' || c === '`')
22
+ throw Error('unexpected literal in emitted entry data');
23
+ if ('([{⟨'.includes(c))
24
+ stack.push(c);
25
+ else if (Object.hasOwn(pairs, c)) {
26
+ if (stack.pop() !== pairs[c])
27
+ throw Error('unbalanced entry data');
28
+ }
29
+ else if (c === ',' && !stack.length) {
30
+ const item = source.slice(start, i).trim();
31
+ if (!item)
32
+ throw Error('empty entry');
33
+ values.push(item);
34
+ start = i + 1;
35
+ }
36
+ }
37
+ if (stack.length)
38
+ throw Error('unclosed entry data');
39
+ const last = source.slice(start, -1).trim();
40
+ if (last)
41
+ values.push(last);
42
+ return values;
43
+ }
44
+ export function emitCountedParts(id, bundle, options) {
45
+ if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(id) || id.length > 80)
46
+ throw Error('unsafe Lean identifier');
47
+ for (const value of [options.maxOutputBytes, options.maxFiles, options.heartbeats, options.recursionDepth])
48
+ if (!Number.isSafeInteger(value) || value < 1)
49
+ throw Error('finite positive generator limits required');
50
+ const { machine, laws, proof } = bundle.final;
51
+ if (!laws.length)
52
+ throw Error('empty retained family');
53
+ const text = retainedCMachineToLean(id, machine, laws, proof);
54
+ const match = new RegExp(`\\n(?:noncomputable )?def ${id}_proof : List (CEntryF|CEntry) := `).exec(text), check = text.indexOf(`\ntheorem ${id}_check :`);
55
+ if (!match || check < 0)
56
+ throw Error('unexpected retained family emission layout');
57
+ const begin = match.index + match[0].length, entries = splitEntryData(text.slice(begin, check));
58
+ if (entries.length !== laws.length)
59
+ throw Error('family entry count mismatch');
60
+ const entryType = match[1], defsModule = `${id}_Defs`, family = `${id}_family`, es = `(${family}.map (·.e))`, decls = `${id}_decls`;
61
+ const checked = text.includes(`def ${id}_checkedMachine :`) ? `${id}_checkedMachine` : `${id}_machine`;
62
+ const files = [], frontiers = [];
63
+ let bytes = 0;
64
+ const add = (module, role, imports, body) => {
65
+ if (files.some(f => f.module === module))
66
+ throw Error('duplicate generated module');
67
+ const source = imports.map(m => `import ${m}`).join('\n') + `\nopen Kern Cert\nset_option maxHeartbeats ${options.heartbeats}\nset_option maxRecDepth ${options.recursionDepth}\n` + body + '\n';
68
+ bytes += Buffer.byteLength(source);
69
+ if (bytes > options.maxOutputBytes || files.length >= options.maxFiles)
70
+ throw Error('generated source limit exceeded');
71
+ files.push({ module, role, text: source, sha256: sha(source) });
72
+ };
73
+ const names = entries.map((_, i) => `${id}_entry${i}`);
74
+ let defs = text.slice(0, match.index) + '\n';
75
+ defs += entries.map((entry, i) => `noncomputable def ${names[i]}_raw : ${entryType} := ${entry}\nnoncomputable def ${names[i]} : CEntryF := ${entryType === 'CEntry' ? `${names[i]}_raw.toF` : `${names[i]}_raw`}`).join('\n');
76
+ defs += `\nnoncomputable def ${family} : List CEntryF := ${list(names)}\n`;
77
+ add(defsModule, 'definitions', ['QAlpha', 'FamilyParts'], defs);
78
+ const globalModule = `${id}_Global`;
79
+ add(globalModule, 'global-conditions', [defsModule], `theorem ${id}_global : cGlobalOkF ${checked} ${decls} ${es} = true := by decide +kernel\n#print axioms ${id}_global`);
80
+ const entryModules = [];
81
+ for (let i = 0; i < laws.length; i++) {
82
+ const entry = names[i], law = laws[i], checks = [], checkModules = [];
83
+ for (const phase of ['start', 'step']) {
84
+ const cert = proof.certs[`${law.name} @${phase}`];
85
+ if (!cert)
86
+ throw Error('missing primary certificate');
87
+ const base = `${id}_e${i}_${phase}`, certificate = `${entry}.${phase}`, aux = `${entry}.${phase}Aux`;
88
+ const ds = `(${phase === 'start' ? 'cStartDecls' : 'cStepDecls'} ${checked} ${decls})`;
89
+ const hyps = phase === 'start' ? `(cStartGoal ${checked} ${decls} ${entry}.e)` : `(cStepGoal ${checked} ${decls} ${es} ${entry}.e)`;
90
+ const context = { machine, laws, instances: proof.instances, reads: cert.reads, insts: cert.insts, picks: cert.picks, lemmas: cert.lemmas, frames: cert.frames, monos: cert.monos, lins: cert.lins };
91
+ const frontier = makeFrontier(cert.tree, options.weightLimit, structuralWeight(context));
92
+ verifyFrontier(cert.tree, frontier);
93
+ frontiers.push({ law: law.name, phase, frontier });
94
+ const at = (a) => `FamilyParts.mcfWith ${ds} ${certificate} (fun g cs => FamilyParts.checkAt g.tab g.hyps ${certificate}.lemmas ${aux}.frames ${aux}.monos ${aux}.lins [] ${certificate}.tree ${address(a)})`;
95
+ const ready = new Map();
96
+ for (const piece of frontier.pieces) {
97
+ const module = `${base}_p${piece.address ? sha(piece.address).slice(0, 20) : 'root'}`, theorem = `${module}_check`;
98
+ add(module, 'tree-piece', [defsModule], `theorem ${theorem} : ${at(piece.address)} = true := by decide +kernel\n#print axioms ${theorem}`);
99
+ ready.set(piece.address, { module, theorem });
100
+ }
101
+ const ancestors = new Set();
102
+ for (const p of frontier.pieces)
103
+ for (let n = 0; n < p.address.length; n++)
104
+ ancestors.add(p.address.slice(0, n));
105
+ for (const a of [...ancestors].sort((x, y) => y.length - x.length || (x < y ? -1 : 1))) {
106
+ const yes = ready.get(a + '1'), no = ready.get(a + '0');
107
+ if (!yes || !no)
108
+ throw Error('incomplete canonical assembly frontier');
109
+ const module = `${base}_a${a ? sha(a).slice(0, 20) : 'root'}`, theorem = `${module}_check`;
110
+ add(module, 'tree-assembly', [defsModule, yes.module, no.module], `theorem ${theorem} : ${at(a)} = true := by\n exact FamilyParts.mcfWith_map2 ${ds} ${certificate} _ _ _\n (by intro g cs h1 h0; exact FamilyParts.checkAt_split g.tab g.hyps ${certificate}.lemmas ${aux}.frames ${aux}.monos ${aux}.lins ${address(a)} [] ${certificate}.tree h1 h0)\n ${yes.theorem} ${no.theorem}\n#print axioms ${theorem}`);
111
+ ready.set(a, { module, theorem });
112
+ }
113
+ const root = ready.get('');
114
+ if (!root)
115
+ throw Error('missing root assembly');
116
+ const preModule = `${base}_Pre`, side = `FamilyParts.mcfWith ${ds} ${certificate} (fun g cs => FamilyParts.goalPre ${certificate}.lemmas ${aux}.monos ${aux}.lins g cs && ${aux}.frames.all (frameOk g.tab cs))`;
117
+ add(preModule, 'obligation-side-conditions', [defsModule], `theorem ${base}_pre : FamilyParts.mcfPre ${hyps} ${ds} ${certificate} = true := by decide +kernel\ntheorem ${base}_side : ${side} = true := by decide +kernel\n#print axioms ${base}_pre\n#print axioms ${base}_side`);
118
+ const module = `${base}_Complete`, theorem = `${base}_check`;
119
+ add(module, 'obligation-assembly', [defsModule, preModule, root.module], `theorem ${theorem} : checkMCF ${hyps} ${ds} ${certificate} ${aux}.frames ${aux}.monos ${aux}.lins = true := by\n apply FamilyParts.checkMCF_of_parts _ _ _ _ _ _ ${base}_pre\n exact FamilyParts.mcfWith_map2 ${ds} ${certificate} _ _ _\n (by intro g cs hs ht; simp only [Bool.and_eq_true] at hs; exact FamilyParts.goal_of_parts g cs ${certificate}.tree ${certificate}.lemmas ${aux}.frames ${aux}.monos ${aux}.lins hs.1 hs.2 ht)\n ${base}_side ${root.theorem}\n#print axioms ${theorem}`);
120
+ checks.push(theorem);
121
+ checkModules.push(module);
122
+ }
123
+ const module = `${id}_e${i}_Complete`;
124
+ add(module, 'entry-assembly', [defsModule, ...checkModules], `theorem ${id}_e${i}_check : cEntryCheckF ${checked} ${decls} ${es} ${entry} = true := by\n exact FamilyParts.entry_of_both _ _ _ _ (by decide +kernel) ${checks[0]} ${checks[1]}\n#print axioms ${id}_e${i}_check`);
125
+ entryModules.push(module);
126
+ }
127
+ const finalModule = `${id}_Complete`, branches = names.map((_, i) => ` · exact ${id}_e${i}_check`).join('\n');
128
+ const transport = checked === `${id}_machine` ? `cmachineF_sound ${id}_machine ${decls} ${family} ${id}_check` : `QAlpha.cmachineF_sound ${id}_machine ${id}_renames ${decls} ${family} (by decide +kernel) ${id}_check`;
129
+ add(finalModule, 'family-assembly', [defsModule, globalModule, ...entryModules], `theorem ${id}_check : checkCMachineF ${checked} ${decls} ${family} = true := by\n apply checkCMachineF_of_parts _ _ _ ${id}_global\n intro ce hce\n simp only [${family}, List.mem_cons, List.mem_singleton, List.not_mem_nil, or_false] at hce\n rcases hce with ${names.map(() => 'rfl').join(' | ')}\n${branches}\ntheorem ${id}_laws : ∀ ρ M, CReach ${id}_machine ${decls} ρ M → ∀ ce ∈ ${family}, ce.e.Holds ρ (withCnt ${decls} ρ M) :=\n ${transport}\n#print axioms ${id}_check\n#print axioms ${id}_laws`);
130
+ return { status: 'EMITTED_NOT_CHECKED', files, frontiers, familySize: laws.length, primaryObligations: 2 * laws.length, finalModule };
131
+ }
@@ -0,0 +1,2 @@
1
+ import type { TermPrelude } from './proof-capture.js';
2
+ export declare function restoreTermPrelude(prelude: TermPrelude, memos: ReadonlyArray<readonly [object, unknown]>): void;
@@ -0,0 +1,38 @@
1
+ // Fresh-worker term prelude. Fail rather than renumber process-local columns.
2
+ // This is permitted only in the separately authorized recheck process, never in
3
+ // the final native invocation. All native checks/emission follow this operation.
4
+ import { snapshotKernelTermState, termColumn } from "../../kernel/kernel.js";
5
+ // Replay is deliberately single-use. A failed semantic replay can have interned
6
+ // a prefix of the term table: discard this process; never retry or renumber it.
7
+ let attempted = false;
8
+ export function restoreTermPrelude(prelude, memos) {
9
+ if (attempted)
10
+ throw Error('term prelude replay is single-use; discard this process');
11
+ attempted = true;
12
+ if (snapshotKernelTermState().terms.length !== 0 || snapshotKernelTermState().identities.length !== 0)
13
+ throw Error('term prelude requires a pristine worker');
14
+ if (!Array.isArray(prelude.terms) || !Array.isArray(prelude.identities) || prelude.terms.length !== prelude.identities.length)
15
+ throw Error('incomplete ordered term prelude');
16
+ for (let i = 0; i < prelude.terms.length; i++) {
17
+ if (!Array.isArray(prelude.identities[i]) || prelude.identities[i][1] !== i || typeof prelude.identities[i][0] !== 'string')
18
+ throw Error('noncanonical term identity table');
19
+ if (termColumn(prelude.terms[i]) !== `⟦${i}⟧`)
20
+ throw Error(`term ordinal mismatch at ${i}`);
21
+ }
22
+ const same = () => {
23
+ const state = snapshotKernelTermState();
24
+ if (state.terms.length !== prelude.terms.length || JSON.stringify(state.identities) !== JSON.stringify(prelude.identities))
25
+ throw Error('term identity replay differs from capture');
26
+ };
27
+ same();
28
+ for (const [object, metadata] of memos) {
29
+ if (!metadata || typeof metadata !== 'object' || Object.keys(metadata).length !== 1 || !('termId' in metadata))
30
+ throw Error('unsupported graph metadata');
31
+ const id = metadata.termId;
32
+ if (typeof id !== 'number' || !Number.isSafeInteger(id) || id < 0 || id >= prelude.terms.length)
33
+ throw Error('invalid retained term memo');
34
+ if (termColumn(object) !== `⟦${id}⟧`)
35
+ throw Error('stale or incompatible retained term memo');
36
+ }
37
+ same();
38
+ }
@@ -0,0 +1,30 @@
1
+ import { type WitnessAlpha } from './witness-alpha.js';
2
+ import type { NativeBundle } from './proof-capture.js';
3
+ type SourceTheorem = {
4
+ publicIndex: number;
5
+ familyIndex: number | null;
6
+ name: string;
7
+ type: 'exists' | 'ordinary';
8
+ };
9
+ export type WitnessPathReceipt = {
10
+ path: number[];
11
+ witnessPath: number[];
12
+ familyTheorem: string;
13
+ sourceTheorems: string[];
14
+ publicLawIndices: number[];
15
+ };
16
+ export type WitnessAlphaReceipt = WitnessAlpha & {
17
+ id: string;
18
+ theorems: string[];
19
+ };
20
+ type WitnessExport = {
21
+ status: 'EMITTED_NOT_CHECKED';
22
+ body: string;
23
+ publicBridge: string;
24
+ sourceTheorems: SourceTheorem[];
25
+ publicLawIndices: number[];
26
+ parentPaths?: WitnessPathReceipt[];
27
+ alphaTransports?: WitnessAlphaReceipt[];
28
+ };
29
+ export declare function exportWitnessSource(bundle: NativeBundle, id: string): WitnessExport;
30
+ export {};
@@ -0,0 +1,283 @@
1
+ // Output-only projection of the captured skolem producer. This is not a Lean check.
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { proposeWitnessAlpha } from "./witness-alpha.js";
4
+ import { checkLaws, ghostedMachine, someOfGhostsOk, substC } from "../../kernel/kernel.js";
5
+ import { retainedSMachineToLean } from "../emit.js";
6
+ function parentPaths(root) {
7
+ const result = [], active = new Set();
8
+ const visit = (node, path, witnesses, inferences) => {
9
+ if (!node || active.has(node))
10
+ throw Error('missing or cyclic witness provenance');
11
+ if (path.length > 256 || result.length >= 128)
12
+ throw Error('witness parent path limit');
13
+ if (node.kind === 'usual') {
14
+ result.push({ path, leaf: node, witnesses, inferences });
15
+ return;
16
+ }
17
+ if (node.kind !== 'derived')
18
+ throw Error('witness path needs a usual producer');
19
+ if (!Array.isArray(node.parents) || !node.parents.length || new Set(node.parents).size !== node.parents.length)
20
+ throw Error('empty or duplicate witness parent path');
21
+ const c = node.context;
22
+ if (c?.kind === 'witness' || c?.kind === 'skolem')
23
+ witnesses = [...witnesses, { path, context: c }];
24
+ else if (c?.kind === 'inference' && Object.keys(c).sort().join(',') === 'kind,laws,original' && Array.isArray(c.laws))
25
+ inferences = [...inferences, { path, original: c.original, laws: c.laws }];
26
+ else if (c?.kind !== 'projection' || Object.keys(c).length !== 1)
27
+ throw Error('unsupported witness derivation context');
28
+ active.add(node);
29
+ node.parents.forEach((p, i) => visit(p, [...path, i], witnesses, inferences));
30
+ active.delete(node);
31
+ };
32
+ visit(root, [], [], []);
33
+ return result;
34
+ }
35
+ // Validate with fresh bound labels, but emit the ORIGINAL source body and labels.
36
+ // BoundGhost.lean discharges the stronger transfer: bound ghost variables are
37
+ // overwritten by the existential assignment; every other ghost remains avoided.
38
+ function boundSourceSubstitutionOk(G, law, plain, sub) {
39
+ const xs = law.some ?? [];
40
+ if (new Set(xs).size !== xs.length || Object.keys(sub).length !== xs.length || !xs.every(x => Object.hasOwn(sub, x)))
41
+ return false;
42
+ if (!xs.some(x => Object.hasOwn(G.vars, x)))
43
+ return someOfGhostsOk(G, law, plain, sub);
44
+ const used = new Set(), seen = new Set();
45
+ const walk = (x) => {
46
+ if (typeof x === 'string')
47
+ used.add(x);
48
+ else if (x && typeof x === 'object' && !seen.has(x)) {
49
+ seen.add(x);
50
+ for (const [k, v] of Object.entries(x)) {
51
+ used.add(k);
52
+ walk(v);
53
+ }
54
+ }
55
+ };
56
+ walk([G, law, plain, sub]);
57
+ const rename = Object.create(null), freshSub = Object.create(null), fresh = [];
58
+ for (const x of xs) {
59
+ let name = '__source_bound_' + fresh.length;
60
+ while (used.has(name))
61
+ name += '_';
62
+ used.add(name);
63
+ fresh.push(name);
64
+ rename[x] = { op: 'var', name };
65
+ freshSub[name] = sub[x];
66
+ }
67
+ return someOfGhostsOk(G, { ...law, some: fresh, holds: substC(law.holds, { vars: rename, maps: {}, flags: {} }) }, plain, freshSub);
68
+ }
69
+ // `body` is exactly the retained emitter's output; `publicBridge` contains only
70
+ // ordinary-law specializations. Both must be compiled together by Lean.
71
+ function exportWitnessLeaf(bundle, publicId, node, context) {
72
+ let sk = context.kind === 'skolem' ? context : undefined;
73
+ const witness = context.kind === 'witness' ? context : undefined;
74
+ if (witness) {
75
+ const w = witness;
76
+ if (!Array.isArray(w.ghosts) || !Array.isArray(w.plain) || !Array.isArray(w.laws) ||
77
+ !isDeepStrictEqual(w.machine, node.machine) || !isDeepStrictEqual(w.plain, node.laws))
78
+ throw Error('witness producer mismatch');
79
+ const vars = Object.create(null), state = w.machine.step.state ?? {};
80
+ for (const name of w.ghosts) {
81
+ if (Object.hasOwn(vars, name) || !Object.hasOwn(w.machine.state, name) || !Object.hasOwn(state, name))
82
+ throw Error('invalid captured scalar ghost');
83
+ vars[name] = { start: w.machine.state[name], step: state[name] };
84
+ }
85
+ const maps = Object.create(null);
86
+ for (const [name, start] of Object.entries(w.machine.maps ?? {})) {
87
+ if (Object.hasOwn(w.original.maps ?? {}, name))
88
+ continue;
89
+ const write = w.machine.step.maps?.[name];
90
+ if (!Number.isSafeInteger(start) || start < 0 || !write)
91
+ throw Error('invalid captured ghost map');
92
+ maps[name] = { start, write };
93
+ }
94
+ const G = { orig: w.original, vars, maps };
95
+ const plains = Object.create(null);
96
+ for (const law of bundle.original.laws) {
97
+ const i = w.laws.findIndex(l => l.name === law.name);
98
+ if (i < 0)
99
+ throw Error('public law absent from witness context');
100
+ if (!law.some?.length)
101
+ continue;
102
+ const matching = w.plain.filter(l => l.name === law.name);
103
+ if (matching.length !== 1)
104
+ throw Error('ambiguous captured witness plain');
105
+ const plain = matching[0], ex = plain.ex;
106
+ if (!plain || !ex || !isDeepStrictEqual(ex.body, law.holds) || !isDeepStrictEqual(ex.vars, law.some))
107
+ throw Error('unsupported or renamed captured witness');
108
+ const sub = ex.sub ?? (ex.ghost ? Object.fromEntries(ex.vars.map(name => [name, { op: 'var', name }])) :
109
+ ex.map && ex.vars.length === 1 ? { [ex.vars[0]]: { op: 'get', map: ex.map.name, key: ex.map.at } } : undefined);
110
+ if (!sub)
111
+ throw Error('missing captured witness substitution');
112
+ plains[law.name] = { plain, sub };
113
+ }
114
+ sk = { kind: 'skolem', original: w.original, laws: w.laws, G, plains, family: w.plain };
115
+ }
116
+ if (!sk)
117
+ throw Error('missing witness context');
118
+ const { G, original, laws: capturedLaws, plains, family: declaredFamily } = sk;
119
+ const family = node.laws;
120
+ const laws = bundle.original.laws;
121
+ for (const law of laws) {
122
+ const matches = capturedLaws.filter(l => l.name === law.name);
123
+ if (matches.length !== 1)
124
+ throw Error('ambiguous or absent captured public law');
125
+ const { witness: _advisory, ...capturedPublic } = matches[0];
126
+ if (!isDeepStrictEqual(capturedPublic, law))
127
+ throw Error('captured public law differs from original');
128
+ }
129
+ if (!laws.length || laws.some(l => l.stated !== undefined || l.ex !== undefined || l.finite !== undefined || l.witness !== undefined || (l.some !== undefined && !l.some.length)))
130
+ throw Error('unsupported public witness law semantics');
131
+ if (Object.keys(original.counts ?? {}).length || Object.keys(node.machine.counts ?? {}).length)
132
+ throw Error('counted source requires its own semantic bridge');
133
+ if (!G || !plains || !Array.isArray(laws) || !Array.isArray(declaredFamily) ||
134
+ !isDeepStrictEqual(original, G.orig) ||
135
+ !Array.isArray(capturedLaws))
136
+ throw Error('skolem public input mismatch');
137
+ const alpha = proposeWitnessAlpha(bundle.original.machine, original);
138
+ const id = alpha ? publicId + '_producer' : publicId;
139
+ // Empty optional map records have the same machine semantics as absent ones.
140
+ const normalize = (m) => ({ ...m, maps: m.maps ?? {}, step: { ...m.step, maps: m.step.maps ?? {} } });
141
+ if (!isDeepStrictEqual(normalize(node.machine), normalize(ghostedMachine(G))) ||
142
+ declaredFamily.some(l => family.filter(f => isDeepStrictEqual(f, l)).length !== 1))
143
+ throw Error('skolem producer family mismatch');
144
+ if (!checkLaws(node.machine, node.laws, node.proof))
145
+ throw Error('captured usual family does not check');
146
+ const names = new Set();
147
+ for (const l of family) {
148
+ if (names.has(l.name))
149
+ throw Error('duplicate family law name');
150
+ names.add(l.name);
151
+ }
152
+ const publicNames = new Set(), ghostSubst = [];
153
+ const publicLawIndices = [], sourceTheorems = [], free = [];
154
+ let publicBridge = '';
155
+ const mem = (i) => i === 0 ? 'List.mem_cons_self' : `List.mem_cons_of_mem _ (${mem(i - 1)})`;
156
+ for (const [publicIndex, law] of laws.entries()) {
157
+ if (publicNames.has(law.name))
158
+ throw Error('duplicate public law name');
159
+ publicNames.add(law.name);
160
+ if (law.some?.length) {
161
+ const q = Object.hasOwn(plains, law.name) ? plains[law.name] : undefined;
162
+ if (!q || !declaredFamily.includes(q.plain) || !boundSourceSubstitutionOk(G, law, q.plain, q.sub))
163
+ throw Error('invalid captured skolem plain');
164
+ const index = family.findIndex(l => isDeepStrictEqual(l, q.plain)), j = ghostSubst.length;
165
+ if (index < 0)
166
+ throw Error('captured skolem plain absent from complete family');
167
+ ghostSubst.push({ law: q.plain.name, body: law.holds, sub: q.sub, boundGhosts: true });
168
+ free.push(...law.some);
169
+ publicLawIndices.push(index);
170
+ sourceTheorems.push({ publicIndex, familyIndex: index, name: `${id}_ex${j}`, type: 'exists' });
171
+ }
172
+ else {
173
+ const index = family.findIndex(l => l.name === law.name);
174
+ if (index < 0 || !isDeepStrictEqual(family[index], law))
175
+ throw Error('ordinary public law missing unchanged');
176
+ publicLawIndices.push(index);
177
+ const name = `${id}_public${publicIndex}`;
178
+ sourceTheorems.push({ publicIndex, familyIndex: index, name, type: 'ordinary' });
179
+ publicBridge += `\ntheorem ${name} : ∀ ρ M, SReach ${id}_gm.orig ρ M → ${id}_e${index}.Holds ρ M := by\n intro ρ M h\n exact ${id}_orig_laws ρ M h ${id}_e${index} (${mem(index)}) (by decide +kernel) (by decide +kernel)\n`;
180
+ }
181
+ }
182
+ if (!ghostSubst.length)
183
+ throw Error('no existential public law');
184
+ const alphaTransports = [];
185
+ if (alpha)
186
+ free.push(...alpha.renames.flatMap(r => [r.old, r.fresh]), ...alpha.rows.flatMap(r => [r.old, r.fresh]));
187
+ const body = retainedSMachineToLean(id, node.machine, node.laws, node.proof, { ghosted: G, ghostSubst, free: [...new Set(free)], ...(alpha ? { after: (ix, mx, lit, c) => {
188
+ const renames = alpha.renames.map(r => `⟨${ix('?' + r.flag)}, ${ix(r.old)}, ${ix(r.fresh)}⟩`).join(', ');
189
+ const rows = alpha.rows.map(r => `⟨${mx(r.map)}, ${ix(r.old)}, ${ix(r.fresh)}⟩`).join(', ');
190
+ const claims = sourceTheorems.map(t => {
191
+ const law = laws[t.publicIndex], index = t.familyIndex, name = t.name.replace(id + '_', publicId + '_');
192
+ const conclusion = t.type === 'exists' ? `ExHolds (${c(law.holds)}) ${id}_e${index}.law.key [${law.some.map(ix).join(', ')}] M ${id}_e${index}.keys2 ρ` : `${id}_e${index}.Holds ρ M`;
193
+ const apply = t.type === 'exists' ? `${t.name} ρ M hp` : `${id}_orig_laws ρ M hp ${id}_e${index} (${mem(index)}) (by decide +kernel) (by decide +kernel)`;
194
+ return `theorem ${name} : ∀ ρ M, SReach ${publicId}_source ρ M → ${conclusion} := by\n intro ρ M hr\n have hp := ${publicId}_source_reach ρ M hr\n exact ${apply}`;
195
+ }).join('\n');
196
+ return `def ${publicId}_source : SMachine := ${lit(bundle.original.machine)}
197
+ def ${publicId}_source_renames : List Kern.QAlpha.Rename := [${renames}]
198
+ def ${publicId}_source_row_renames : List Kern.RowAlpha.Rename := [${rows}]
199
+ theorem ${publicId}_alpha_valid : Kern.QAlpha.validAll ${publicId}_source ${publicId}_source_renames = true := by decide +kernel
200
+ theorem ${publicId}_row_valid : Kern.RowAlpha.validAll (Kern.QAlpha.renameAll ${publicId}_source ${publicId}_source_renames) ${publicId}_source_row_renames = true := by decide +kernel
201
+ theorem ${publicId}_alpha_result : Kern.RowAlpha.renameAll (Kern.QAlpha.renameAll ${publicId}_source ${publicId}_source_renames) ${publicId}_source_row_renames = ${id}_gm.orig := by rfl
202
+ theorem ${publicId}_source_reach : ∀ ρ M, SReach ${publicId}_source ρ M → SReach ${id}_gm.orig ρ M := by
203
+ intro ρ M hr
204
+ rw [← ${publicId}_alpha_result]
205
+ have q := Kern.QAlpha.renameAll_equiv ${publicId}_source ${publicId}_source_renames ${publicId}_alpha_valid
206
+ have r := Kern.RowAlpha.renameAll_equiv (Kern.QAlpha.renameAll ${publicId}_source ${publicId}_source_renames) ${publicId}_source_row_renames ${publicId}_row_valid
207
+ exact r.symm.sreach_imp (q.symm.sreach_imp hr)
208
+ theorem ${publicId}_laws : ∀ ρ M, SReach ${id}_machine ρ M → ∀ e ∈ ${id}_proof, e.Holds ρ M := ${id}_laws
209
+ ${claims}`;
210
+ } } : {}) });
211
+ if (alpha) {
212
+ alphaTransports.push({ ...alpha, id: publicId, theorems: ['_alpha_valid', '_row_valid', '_alpha_result', '_source_reach'].map(s => publicId + s) });
213
+ for (const t of sourceTheorems)
214
+ t.name = t.name.replace(id + '_', publicId + '_');
215
+ publicBridge = '';
216
+ }
217
+ return { status: 'EMITTED_NOT_CHECKED', body, publicBridge, sourceTheorems, publicLawIndices, ...(alpha ? { alphaTransports } : {}) };
218
+ }
219
+ // Every provenance path is an obligation. A context-free inference branch may
220
+ // reuse the UNIQUE retained witness context, but must independently prove its
221
+ // exact source substitution with its own complete family. No leaf is selected.
222
+ export function exportWitnessSource(bundle, id) {
223
+ if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(id))
224
+ throw Error('unsafe witness identifier');
225
+ if (bundle.route !== 'witness' || bundle.verdict.proven !== true || bundle.verdict.checked !== true)
226
+ throw Error('expected a checked witness capsule');
227
+ const paths = parentPaths(bundle.proof);
228
+ const contexts = new Map();
229
+ for (const p of paths)
230
+ for (const w of p.witnesses)
231
+ contexts.set(w.context, w.path);
232
+ const receipts = [], exports = [];
233
+ for (const [i, p] of paths.entries()) {
234
+ if (p.witnesses.length > 1)
235
+ throw Error('multiple witness contexts on parent path');
236
+ const own = p.witnesses[0];
237
+ if (!own && contexts.size !== 1)
238
+ throw Error('parent path has no unique compatible witness context');
239
+ const context = own?.context ?? contexts.keys().next().value;
240
+ for (const inf of p.inferences) {
241
+ // An inference ABOVE this path's witness projects the original source
242
+ // claims; below it (or on a sibling-only path) it describes the producer.
243
+ if (own && inf.path.length < own.path.length) {
244
+ try {
245
+ const proposed = proposeWitnessAlpha(bundle.original.machine, inf.original);
246
+ if (proposed && !isDeepStrictEqual(inf.original, context.original))
247
+ throw Error('different witness source');
248
+ }
249
+ catch {
250
+ throw Error('source inference original differs from source machine beyond checked alpha transport');
251
+ }
252
+ if (new Set(inf.laws.map(l => l.name)).size !== inf.laws.length || bundle.original.laws.some(l => inf.laws.filter(f => isDeepStrictEqual(f, l)).length !== 1))
253
+ throw Error('source inference public laws missing or changed');
254
+ const publicNames = new Set(bundle.original.laws.map(l => l.name));
255
+ if (inf.laws.some(l => !publicNames.has(l.name) && p.leaf.laws.filter(f => isDeepStrictEqual(f, l)).length !== 1))
256
+ throw Error('source inference extra law absent from complete witness family');
257
+ // No law is added to assumptions here. exportWitnessLeaf checks and
258
+ // emits the complete family, including every retained candidate seed.
259
+ }
260
+ else if (!isDeepStrictEqual(inf.original, p.leaf.machine) || inf.laws.some(l => p.leaf.laws.filter(f => isDeepStrictEqual(f, l)).length !== 1)) {
261
+ throw Error('inference parent differs from complete witness producer');
262
+ }
263
+ }
264
+ const prefix = paths.length === 1 ? id : `${id}_path${i}`;
265
+ const emitted = exportWitnessLeaf(bundle, prefix, p.leaf, context);
266
+ exports.push(emitted);
267
+ receipts.push({ path: p.path, witnessPath: own?.path ?? contexts.get(context), familyTheorem: prefix + '_laws', sourceTheorems: emitted.sourceTheorems.map(t => t.name), publicLawIndices: emitted.publicLawIndices });
268
+ }
269
+ if (exports.length === 1)
270
+ return exports[0];
271
+ const conjunction = (names) => names.length === 1 ? `(@${names[0]})` : `And.intro (@${names[0]}) (${conjunction(names.slice(1))})`;
272
+ const sourceTheorems = exports[0].sourceTheorems.map(t => ({ ...t, familyIndex: null, name: t.name.replace(`${id}_path0_`, `${id}_`) }));
273
+ const joinTheorem = (name, names) => {
274
+ const proof = conjunction(names);
275
+ return `theorem ${name} : ${id}_claim (${proof}) := ${proof}`;
276
+ };
277
+ // The reducible claim helper obtains the exact conjunction type from all
278
+ // checked path proofs. It introduces no assumption or new proof principle.
279
+ const joined = [`def ${id}_claim {p : Prop} (_proof : p) : Prop := p`,
280
+ joinTheorem(id + '_laws', receipts.map(p => p.familyTheorem)),
281
+ ...sourceTheorems.map((t, j) => joinTheorem(t.name, exports.map(e => e.sourceTheorems[j].name)))].join('\n');
282
+ return { status: 'EMITTED_NOT_CHECKED', body: exports.map(e => e.body + '\n' + e.publicBridge).join('\n'), publicBridge: joined, sourceTheorems, publicLawIndices: [], parentPaths: receipts, alphaTransports: exports.flatMap(e => e.alphaTransports ?? []) };
283
+ }