gdp-wired 0.49.0 → 0.50.1

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 (86) 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/chart.js +28 -4
  5. package/dist/core/cli.js +3 -0
  6. package/dist/core/compose.js +4 -3
  7. package/dist/core/count-support.d.ts +1 -0
  8. package/dist/core/count-support.js +23 -2
  9. package/dist/core/counted-candidate-seeds.d.ts +12 -0
  10. package/dist/core/counted-candidate-seeds.js +31 -0
  11. package/dist/core/counts.js +9 -2
  12. package/dist/core/dsl-binders.d.ts +15 -0
  13. package/dist/core/dsl-binders.js +129 -0
  14. package/dist/core/dsl.d.ts +28 -2
  15. package/dist/core/dsl.js +147 -52
  16. package/dist/core/exists.js +2 -1
  17. package/dist/core/field-laws.js +23 -5
  18. package/dist/core/infer.js +10 -5
  19. package/dist/core/laws.js +2 -1
  20. package/dist/core/lift-cli.d.ts +11 -0
  21. package/dist/core/lift-cli.js +113 -0
  22. package/dist/core/proof-output.d.ts +53 -0
  23. package/dist/core/proof-output.js +38 -0
  24. package/dist/core/quorum-laws.js +55 -16
  25. package/dist/kernel/function-instances.d.ts +45 -0
  26. package/dist/kernel/function-instances.js +460 -0
  27. package/dist/kernel/prove.d.ts +12 -3
  28. package/dist/kernel/prove.js +164 -90
  29. package/dist/lean-kernel/axiom-audit.d.ts +11 -0
  30. package/dist/lean-kernel/axiom-audit.js +50 -0
  31. package/dist/lean-kernel/emit.d.ts +25 -2
  32. package/dist/lean-kernel/emit.js +75 -10
  33. package/dist/lean-kernel/legacy-family-order.d.ts +1 -0
  34. package/dist/lean-kernel/legacy-family-order.js +26 -0
  35. package/dist/lean-kernel/library.js +22 -0
  36. package/dist/lean-kernel/lift/counted-source-data.d.ts +7 -0
  37. package/dist/lean-kernel/lift/counted-source-data.js +78 -0
  38. package/dist/lean-kernel/lift/index.d.ts +82 -0
  39. package/dist/lean-kernel/lift/index.js +116 -0
  40. package/dist/lean-kernel/lift/project.d.ts +4 -0
  41. package/dist/lean-kernel/lift/project.js +15 -0
  42. package/dist/lean-kernel/lift/proof-capture.d.ts +104 -0
  43. package/dist/lean-kernel/lift/proof-capture.js +216 -0
  44. package/dist/lean-kernel/lift/proof-codec.d.ts +28 -0
  45. package/dist/lean-kernel/lift/proof-codec.js +299 -0
  46. package/dist/lean-kernel/lift/proof-counted-source.d.ts +16 -0
  47. package/dist/lean-kernel/lift/proof-counted-source.js +68 -0
  48. package/dist/lean-kernel/lift/proof-frontier.d.ts +19 -0
  49. package/dist/lean-kernel/lift/proof-frontier.js +153 -0
  50. package/dist/lean-kernel/lift/proof-graph.d.ts +17 -0
  51. package/dist/lean-kernel/lift/proof-graph.js +130 -0
  52. package/dist/lean-kernel/lift/proof-parts.d.ts +29 -0
  53. package/dist/lean-kernel/lift/proof-parts.js +131 -0
  54. package/dist/lean-kernel/lift/proof-prelude.d.ts +2 -0
  55. package/dist/lean-kernel/lift/proof-prelude.js +38 -0
  56. package/dist/lean-kernel/lift/proof-witness.d.ts +30 -0
  57. package/dist/lean-kernel/lift/proof-witness.js +283 -0
  58. package/dist/lean-kernel/lift/shape.d.ts +5 -0
  59. package/dist/lean-kernel/lift/shape.js +57 -0
  60. package/dist/lean-kernel/lift/source-projection.d.ts +16 -0
  61. package/dist/lean-kernel/lift/source-projection.js +81 -0
  62. package/dist/lean-kernel/lift/source.d.ts +23 -0
  63. package/dist/lean-kernel/lift/source.js +111 -0
  64. package/dist/lean-kernel/lift/witness-alpha.d.ts +9 -0
  65. package/dist/lean-kernel/lift/witness-alpha.js +31 -0
  66. package/dist/lean-kernel/lift-legacy.d.ts +58 -0
  67. package/dist/lean-kernel/lift-legacy.js +84 -0
  68. package/dist/lean-kernel/lift-names.d.ts +22 -0
  69. package/dist/lean-kernel/lift-names.js +36 -0
  70. package/dist/lean-kernel/lift-simulation/index.d.ts +29 -0
  71. package/dist/lean-kernel/lift-simulation/index.js +352 -0
  72. package/dist/lean-kernel/lift-simulation/shape.d.ts +41 -0
  73. package/dist/lean-kernel/lift-simulation/shape.js +173 -0
  74. package/dist/lean-kernel/lift-special/index.d.ts +36 -0
  75. package/dist/lean-kernel/lift-special/index.js +241 -0
  76. package/dist/lean-kernel/lift-special/structural.d.ts +25 -0
  77. package/dist/lean-kernel/lift-special/structural.js +126 -0
  78. package/dist/lean-kernel/lift-typed/index.d.ts +35 -0
  79. package/dist/lean-kernel/lift-typed/index.js +256 -0
  80. package/dist/lean-kernel/lift-typed/roles.d.ts +17 -0
  81. package/dist/lean-kernel/lift-typed/roles.js +170 -0
  82. package/dist/lean-kernel/lift-typed/shape.d.ts +1 -0
  83. package/dist/lean-kernel/lift-typed/shape.js +12 -0
  84. package/dist/lean-kernel/lift.d.ts +30 -0
  85. package/dist/lean-kernel/lift.js +97 -0
  86. package/package.json +8 -2
@@ -0,0 +1,7 @@
1
+ import { type FamilyBundle } from './proof-capture.js';
2
+ export declare function countedSourceDefinitions(id: string, bundle: FamilyBundle): {
3
+ producerText: string;
4
+ sourceDefs: string;
5
+ publicLawIndices: number[];
6
+ newCountMapIndices: number[];
7
+ };
@@ -0,0 +1,78 @@
1
+ import { boundOf, postName, witnessesOf } from "../../kernel/kernel.js";
2
+ import { retainedCMachineToLean } from "../emit.js";
3
+ import { alphaProposals, rowAlphaProposals } from "./source-projection.js";
4
+ import { lawCoverage } from "./proof-capture.js";
5
+ export function countedSourceDefinitions(id, bundle) {
6
+ if (bundle.schema !== 'bapa-family/v1' || bundle.route !== 'counted-family' || !bundle.verdict.proven || !bundle.verdict.checked)
7
+ throw Error('counted source requires a checked counted family');
8
+ const source = bundle.original.machine, laws = bundle.original.laws, producer = bundle.final.machine;
9
+ if (source.history || (source.sums && Object.keys(source.sums).length) || Object.keys(source.fns ?? {}).length)
10
+ throw Error('source history/sums/functions require a separate route');
11
+ if (!laws.length || laws.some(l => l.stated !== undefined || l.some !== undefined || l.ex !== undefined || l.finite !== undefined || l.witness !== undefined))
12
+ throw Error('source public laws require ordinary law metadata');
13
+ const indices = lawCoverage(laws, bundle.final.laws);
14
+ const rs = alphaProposals(source, producer), rows = rowAlphaProposals(source, producer);
15
+ const vars = new Set([...source.params, ...source.inputs, ...Object.keys(source.state), ...Object.keys(source.step.state ?? {})]);
16
+ const maps = new Set([...Object.keys(source.maps ?? {}), ...Object.keys(source.step.maps ?? {}), ...(source.inputMaps ?? [])]);
17
+ // Expressions have the same var/get constructors consumed by leanTerms.
18
+ const visit = (value) => {
19
+ if (!value || typeof value !== 'object')
20
+ return;
21
+ if (Array.isArray(value)) {
22
+ value.forEach(visit);
23
+ return;
24
+ }
25
+ const node = value;
26
+ if (node.op === 'var' && typeof node.name === 'string')
27
+ vars.add(node.name);
28
+ if (node.op === 'get' && typeof node.map === 'string')
29
+ maps.add(node.map);
30
+ Object.values(node).forEach(visit);
31
+ };
32
+ visit(source);
33
+ visit(laws);
34
+ for (const [flag, q] of Object.entries(source.step.flags ?? {})) {
35
+ vars.add(`?${flag}`);
36
+ if (q.op === 'all') {
37
+ boundOf(q).forEach(v => vars.add(v));
38
+ witnessesOf(flag, q).forEach(v => vars.add(v));
39
+ }
40
+ }
41
+ for (const w of Object.values(source.step.maps ?? {}))
42
+ if ('each' in w)
43
+ vars.add(w.each);
44
+ for (const l of [...laws, ...(source.facts ?? [])]) {
45
+ if (l.forall)
46
+ vars.add(l.forall);
47
+ for (const k of l.keys ?? [])
48
+ vars.add(k);
49
+ }
50
+ const counts = Object.entries(source.counts ?? {});
51
+ for (const [name, d] of counts) {
52
+ maps.add(name);
53
+ maps.add(postName(name));
54
+ vars.add(d.j);
55
+ vars.add(d.key);
56
+ vars.add(d.lo ?? d.j);
57
+ }
58
+ for (const r of rs) {
59
+ vars.add(`?${r.flag}`);
60
+ vars.add(r.old);
61
+ vars.add(r.fresh);
62
+ }
63
+ let sourceDefs = '', newCountMapIndices = [];
64
+ const normalized = { ...source, counts: undefined, inputMaps: [...(source.inputMaps ?? []), ...counts.map(([name]) => name)] };
65
+ const producerText = retainedCMachineToLean(id, producer, bundle.final.laws, bundle.final.proof, {
66
+ extraVars: [...vars], extraMaps: [...maps], after: basis => {
67
+ const { ix, mx } = basis;
68
+ newCountMapIndices = Object.keys(producer.counts ?? {}).filter(name => !Object.hasOwn(source.counts ?? {}, name)).map(mx);
69
+ const renames = rs.map(r => `⟨${ix(`?${r.flag}`)}, ${ix(r.old)}, ${ix(r.fresh)}⟩`).join(', ');
70
+ const rowRenames = rows.map(r => `⟨${mx(r.map)}, ${ix(r.old)}, ${ix(r.fresh)}⟩`).join(', ');
71
+ const claims = laws.map((law, j) => `def ${id}_source_law${j} : MLaw := ⟨${basis.condition(law.holds)}, ${law.forall ? `some ${ix(law.forall)}` : 'none'}⟩\ndef ${id}_source_keys${j} : List Nat := [${(law.keys ?? []).map(ix).join(', ')}]`).join('\n');
72
+ sourceDefs = `-- Proposed check only: RowAlpha.renameAll (QAlpha.renameAll ${id}_source ${id}_source_renames) ${id}_source_row_renames = { ${id}_machine with carried := ${id}_source.carried }
73
+ def ${id}_source : SMachine := ${basis.machine(normalized)}\ndef ${id}_source_decls : List CDecl := ${basis.decls(source.counts)}\ndef ${id}_source_renames : List QAlpha.Rename := [${renames}]\ndef ${id}_source_row_renames : List RowAlpha.Rename := [${rowRenames}]\ndef ${id}_source_count_maps : List Nat := [${newCountMapIndices.join(', ')}]\ndef ${id}_source_law_indices : List Nat := [${indices.join(', ')}]\n${claims}`;
74
+ return '';
75
+ }
76
+ });
77
+ return { producerText, sourceDefs, publicLawIndices: indices, newCountMapIndices };
78
+ }
@@ -0,0 +1,82 @@
1
+ import { type ReadLimits, type CaptureManifest } from './proof-codec.js';
2
+ import type { NativeBundle, CaptureIdentity, Projection } from './proof-capture.js';
3
+ import { type WitnessPathReceipt, type WitnessAlphaReceipt } from './proof-witness.js';
4
+ import { countedSourceProject } from './proof-counted-source.js';
5
+ import type { PartOptions } from './proof-parts.js';
6
+ import { type GenericLiftSource } from './source.js';
7
+ import { type GenericLiftRoute } from './shape.js';
8
+ export type { GenericLiftSource } from './source.js';
9
+ export { readLiftSource, assertSourceMatches } from './source.js';
10
+ export { selectGenericLiftRoute } from './shape.js';
11
+ export { restoreTermPrelude } from './proof-prelude.js';
12
+ export type { GenericLiftRoute } from './shape.js';
13
+ export type { ReadLimits } from './proof-codec.js';
14
+ export type { PartOptions } from './proof-parts.js';
15
+ export type GenericLiftOptions = {
16
+ /** Pin CAPTURE.json to an independently retained hash, when available. */
17
+ expectedManifestSha256?: string;
18
+ limits?: Partial<ReadLimits>;
19
+ parts?: Partial<PartOptions>;
20
+ maxSourceBytes?: number;
21
+ };
22
+ export type GenericLiftManifest = {
23
+ schema: 'gdp-lift-emission/v1';
24
+ status: 'EMITTED_NOT_CHECKED';
25
+ inputSha256: string;
26
+ capsuleSha256: string;
27
+ sourceSha256: string;
28
+ sourceId: string;
29
+ identity: CaptureIdentity;
30
+ route: NativeBundle['route'];
31
+ projection: Projection;
32
+ familyTheorem: string;
33
+ requiredTheorems: string[];
34
+ files: Record<string, string>;
35
+ sourceProjection: {
36
+ kind: GenericLiftRoute;
37
+ status: 'EMITTED_NOT_CHECKED';
38
+ sourceTheorems: string[];
39
+ publicLawNames: string[];
40
+ publicLawIndices?: number[];
41
+ parentPaths?: WitnessPathReceipt[];
42
+ alphaTransports?: WitnessAlphaReceipt[];
43
+ };
44
+ parts?: ReturnType<typeof countedSourceProject>['parts'];
45
+ leanVersion: '4.34.0';
46
+ leanExecuted: false;
47
+ allSizesProven: false;
48
+ publicSourceAcceptance: 'REQUIRES_LEAN_SOURCE_PROJECTION_CHECK';
49
+ };
50
+ export declare const defaultReadLimits: Readonly<ReadLimits>;
51
+ export declare const defaultPartOptions: Readonly<PartOptions>;
52
+ export type LiftInput = {
53
+ manifest: CaptureManifest;
54
+ bundle: NativeBundle;
55
+ metadata: [object, unknown][];
56
+ source: GenericLiftSource;
57
+ sourceSha256: string;
58
+ capsuleSha256: string;
59
+ };
60
+ /** Data and integrity only: no source equality assertion or term restoration. */
61
+ export declare function readLiftInput(capsuleDirectory: string, sourceFile: string, options?: GenericLiftOptions): LiftInput;
62
+ /**
63
+ * Data-only retained-certificate export. Run once in a fresh process: term
64
+ * restoration is deliberately single-use, even on failure. No proof search,
65
+ * protocol registry, source evaluation, Lean invocation or checked receipt.
66
+ * Covers the 24 generic shapes (10 alpha, 9 counted, 5 witness), not the three
67
+ * separately qualified special transports.
68
+ */
69
+ export declare function emitGenericLift(capsuleDirectory: string, sourceFile: string, outputDirectory: string, options?: GenericLiftOptions): GenericLiftManifest;
70
+ export type GenericLiftProject = {
71
+ project: Record<string, string>;
72
+ manifest: GenericLiftManifest;
73
+ };
74
+ /** After exactly one term restoration by the caller; never reads, restores, or writes. */
75
+ export declare function generateGenericLift(input: LiftInput, options?: GenericLiftOptions): GenericLiftProject;
76
+ export type LiftEmissionRecord = {
77
+ schema: 'gdp-lift-emission/v1';
78
+ status: 'EMITTED_NOT_CHECKED';
79
+ files: Record<string, string>;
80
+ };
81
+ /** Commit emission files only, never a checked receipt. Accepts specialized transports. */
82
+ export declare function writeLiftProject(outputDirectory: string, project: Record<string, string>, receipt: LiftEmissionRecord): void;
@@ -0,0 +1,116 @@
1
+ /// <reference types="node" />
2
+ import { mkdirSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { liftProject as leanProject } from "./project.js";
5
+ import { asked } from "../axiom-audit.js";
6
+ import { readFamilyCapsule } from "./proof-codec.js";
7
+ import { restoreTermPrelude } from "./proof-prelude.js";
8
+ import { emitAlphaSource } from "./source-projection.js";
9
+ import { exportWitnessSource } from "./proof-witness.js";
10
+ import { countedSourceProject } from "./proof-counted-source.js";
11
+ import { readBoundedData, readLiftSource, assertSourceMatches, sha256, sourceLeanId } from "./source.js";
12
+ import { selectGenericLiftRoute, assertGenericBridgeShape } from "./shape.js";
13
+ export { readLiftSource, assertSourceMatches } from "./source.js";
14
+ export { selectGenericLiftRoute } from "./shape.js";
15
+ export { restoreTermPrelude } from "./proof-prelude.js";
16
+ export const defaultReadLimits = Object.freeze({ maxBytes: 512 * 1024 * 1024, maxNodes: 4000000, maxStrings: 200000, maxArrayLength: 2000000, maxShards: 2048 });
17
+ export const defaultPartOptions = Object.freeze({ weightLimit: 1000000n, maxOutputBytes: 256 * 1024 * 1024, maxFiles: 20000, heartbeats: 200000000, recursionDepth: 100000 });
18
+ /** Data and integrity only: no source equality assertion or term restoration. */
19
+ export function readLiftInput(capsuleDirectory, sourceFile, options = {}) {
20
+ const { source, sourceSha256 } = readLiftSource(sourceFile, options.maxSourceBytes);
21
+ const capsuleSha256 = sha256(readBoundedData(join(capsuleDirectory, 'CAPTURE.json'), 1024 * 1024));
22
+ const expected = options.expectedManifestSha256 ?? capsuleSha256;
23
+ if (expected !== capsuleSha256)
24
+ throw Error('capture manifest binding mismatch');
25
+ const metadata = [];
26
+ const { manifest, data } = readFamilyCapsule(capsuleDirectory, expected, { ...defaultReadLimits, ...options.limits }, (o, m) => metadata.push([o, m]));
27
+ return { manifest, bundle: data, metadata, source, sourceSha256, capsuleSha256 };
28
+ }
29
+ /**
30
+ * Data-only retained-certificate export. Run once in a fresh process: term
31
+ * restoration is deliberately single-use, even on failure. No proof search,
32
+ * protocol registry, source evaluation, Lean invocation or checked receipt.
33
+ * Covers the 24 generic shapes (10 alpha, 9 counted, 5 witness), not the three
34
+ * separately qualified special transports.
35
+ */
36
+ export function emitGenericLift(capsuleDirectory, sourceFile, outputDirectory, options = {}) {
37
+ const input = readLiftInput(capsuleDirectory, sourceFile, options);
38
+ assertSourceMatches(input.source, input.bundle);
39
+ selectGenericLiftRoute(input.bundle);
40
+ restoreTermPrelude(input.bundle.terms, input.metadata);
41
+ const generated = generateGenericLift(input, options);
42
+ writeLiftProject(outputDirectory, generated.project, generated.manifest);
43
+ return generated.manifest;
44
+ }
45
+ /** After exactly one term restoration by the caller; never reads, restores, or writes. */
46
+ export function generateGenericLift(input, options = {}) {
47
+ const { source, sourceSha256, capsuleSha256, manifest, bundle } = input;
48
+ assertSourceMatches(source, bundle);
49
+ const kind = selectGenericLiftRoute(bundle);
50
+ assertGenericBridgeShape(bundle, kind);
51
+ const id = sourceLeanId(source.id), familyTheorem = id + '_laws';
52
+ let project, sourceTheorems, publicLawIndices;
53
+ let parentPaths, alphaTransports, parts;
54
+ if (kind === 'counted') {
55
+ const emitted = countedSourceProject(id, bundle, { ...defaultPartOptions, ...options.parts });
56
+ project = emitted.project;
57
+ sourceTheorems = emitted.sourceTheorems;
58
+ publicLawIndices = emitted.publicLawIndices;
59
+ parts = emitted.parts;
60
+ }
61
+ else {
62
+ let body;
63
+ if (kind === 'witness') {
64
+ const emitted = exportWitnessSource(bundle, id);
65
+ body = emitted.body + '\n' + emitted.publicBridge;
66
+ sourceTheorems = emitted.sourceTheorems.map(t => t.name);
67
+ publicLawIndices = emitted.publicLawIndices;
68
+ parentPaths = emitted.parentPaths;
69
+ alphaTransports = emitted.alphaTransports;
70
+ }
71
+ else {
72
+ body = emitAlphaSource(id, bundle);
73
+ sourceTheorems = bundle.original.laws.map((_, j) => id + '_source_law' + j + '_holds');
74
+ }
75
+ const printed = [familyTheorem, ...sourceTheorems, ...(parentPaths ?? []).flatMap(p => [p.familyTheorem, ...p.sourceTheorems]), ...(kind === 'alpha' ? [id + '_source_laws', id + '_alpha_valid', id + '_row_valid', id + '_alpha_result'] : []), ...(alphaTransports ?? []).flatMap(a => a.theorems)];
76
+ const bodyRequests = new Set(asked(body));
77
+ const text = 'import QAlpha\nimport Ghost\nimport GhostMap\nopen Kern Cert\nset_option maxHeartbeats 200000000\nset_option maxRecDepth 100000\n' + body + '\n' + [...new Set(printed)].filter(t => !bodyRequests.has(t)).map(t => '#print axioms ' + t).join('\n') + '\n';
78
+ project = leanProject(text, { name: 'BapaProof' });
79
+ }
80
+ if (!sourceTheorems.length || sourceTheorems.length !== source.laws.length)
81
+ throw Error('incomplete public source theorem coverage');
82
+ // Check generated code, not library comments (which can discuss axioms).
83
+ for (const [name, text] of Object.entries(project))
84
+ if (name.endsWith('.lean') && !['lakefile.lean'].includes(name) && (/^(?:bapa_|BapaProof)/.test(name)) && /\b(?:sorry|axiom|native_decide)\b/.test(text))
85
+ throw Error('unapproved generated Lean construct');
86
+ const requiredTheorems = [...new Set([familyTheorem, ...sourceTheorems, ...[...project['BapaProof.lean'].matchAll(/^#print axioms ([A-Za-z_][A-Za-z0-9_'.]*)\s*$/gm)].map(m => m[1])])];
87
+ const maxOutputBytes = options.parts?.maxOutputBytes ?? defaultPartOptions.maxOutputBytes, maxFiles = options.parts?.maxFiles ?? defaultPartOptions.maxFiles;
88
+ for (const v of [maxOutputBytes, maxFiles])
89
+ if (!Number.isSafeInteger(v) || v < 1)
90
+ throw Error('finite positive output limits required');
91
+ if (Object.keys(project).length > maxFiles || Object.values(project).reduce((n, s) => n + Buffer.byteLength(s), 0) > maxOutputBytes)
92
+ throw Error('complete project output limit exceeded');
93
+ const files = Object.fromEntries(Object.entries(project).map(([name, text]) => [name, sha256(text)]));
94
+ const receipt = { schema: 'gdp-lift-emission/v1', status: 'EMITTED_NOT_CHECKED', inputSha256: capsuleSha256, capsuleSha256, sourceSha256, sourceId: source.id, identity: manifest.identity, route: bundle.route, projection: manifest.projection, familyTheorem, requiredTheorems, files,
95
+ sourceProjection: { kind, status: 'EMITTED_NOT_CHECKED', sourceTheorems, publicLawNames: source.laws.map(l => l.name), ...(publicLawIndices ? { publicLawIndices } : {}), ...(parentPaths ? { parentPaths } : {}), ...(alphaTransports?.length ? { alphaTransports } : {}) }, ...(parts ? { parts } : {}), leanVersion: '4.34.0', leanExecuted: false, allSizesProven: false, publicSourceAcceptance: 'REQUIRES_LEAN_SOURCE_PROJECTION_CHECK' };
96
+ return { project, manifest: receipt };
97
+ }
98
+ /** Commit emission files only, never a checked receipt. Accepts specialized transports. */
99
+ export function writeLiftProject(outputDirectory, project, receipt) {
100
+ if (receipt.schema !== 'gdp-lift-emission/v1' || receipt.status !== 'EMITTED_NOT_CHECKED' || ('leanExecuted' in receipt && receipt.leanExecuted !== false) || ('allSizesProven' in receipt && receipt.allSizesProven !== false))
101
+ throw Error('only unchecked emission receipts may be written');
102
+ if (Object.keys(receipt.files).sort().join('\n') !== Object.keys(project).sort().join('\n'))
103
+ throw Error('project file manifest mismatch');
104
+ for (const [name, text] of Object.entries(project)) {
105
+ if (!/^[A-Za-z0-9_.-]+$/.test(name) || name === '.' || name === '..' || name === 'EMITTED.json')
106
+ throw Error('unsafe generated project filename');
107
+ if (receipt.files[name] !== sha256(text))
108
+ throw Error('project file hash mismatch: ' + name);
109
+ }
110
+ // New directory and exclusive file creation: never overwrite earlier evidence.
111
+ mkdirSync(outputDirectory, { recursive: false });
112
+ for (const [name, text] of Object.entries(project)) {
113
+ writeFileSync(join(outputDirectory, name), text, { flag: 'wx' });
114
+ }
115
+ writeFileSync(join(outputDirectory, 'EMITTED.json'), JSON.stringify(receipt, null, 2) + '\n', { flag: 'wx' });
116
+ }
@@ -0,0 +1,4 @@
1
+ export declare function liftProject(body: string, options?: {
2
+ name?: string;
3
+ }): Record<string, string>;
4
+ export declare function leanSource(module: string): string;
@@ -0,0 +1,15 @@
1
+ import { leanLibrary } from "../library.js";
2
+ import { leanProject } from "../emit.js";
3
+ // Lifts always use the current complete library. The general legacy emitter
4
+ // intentionally selects an older counted ABI for cut-free historical projects;
5
+ // mixing that ABI with the promoted current modules would not compile.
6
+ export function liftProject(body, options = {}) {
7
+ return leanProject(body, { ...options, currentFamily: true });
8
+ }
9
+ // Product-owned library only: no filesystem or research-tree dependency.
10
+ export function leanSource(module) {
11
+ const text = leanLibrary[module + '.lean'];
12
+ if (typeof text !== 'string')
13
+ throw Error('missing product Lean library module: ' + module);
14
+ return text;
15
+ }
@@ -0,0 +1,104 @@
1
+ import type { Machine, Law, C, E } from '../../core/machine.js';
2
+ import type { CountCert, Instances } from '../../kernel/kernel.js';
3
+ import type { PublicProofOutput, ProofOutputNode } from '../../core/proof-output.js';
4
+ export type FamilyProof = {
5
+ instances: Record<string, Instances>;
6
+ certs: Record<string, CountCert>;
7
+ };
8
+ export type ClosedFamily = {
9
+ phase: 'closed-family';
10
+ checked: true;
11
+ machine: Machine;
12
+ laws: Law[];
13
+ proof: FamilyProof;
14
+ };
15
+ export type TermPrelude = {
16
+ terms: (E | C)[];
17
+ identities: [string, number][];
18
+ };
19
+ export type Verdict = {
20
+ proven: boolean;
21
+ checked: boolean;
22
+ };
23
+ export type CaptureIdentity = Readonly<{
24
+ protocol: string;
25
+ invocation: string;
26
+ sourceCommit: string;
27
+ sourceTree: string;
28
+ driverSha256: string;
29
+ inputSha256: string;
30
+ runtimeSha256: string;
31
+ profileSha256: string;
32
+ workBudget: string;
33
+ flags: Readonly<Record<string, string>>;
34
+ }>;
35
+ export type Projection = {
36
+ kind: 'same-machine';
37
+ publicLawIndices: number[];
38
+ } | {
39
+ kind: 'unqualified';
40
+ reason: string;
41
+ };
42
+ export type FamilyBundle = {
43
+ schema: 'bapa-family/v1';
44
+ route: 'counted-family';
45
+ identity: CaptureIdentity;
46
+ original: {
47
+ machine: Machine;
48
+ laws: Law[];
49
+ };
50
+ final: ClosedFamily;
51
+ verdict: Verdict;
52
+ terms: TermPrelude;
53
+ publicLawIndices: number[] | null;
54
+ projection: Projection;
55
+ };
56
+ export type ProvenanceBundle = {
57
+ schema: 'bapa-proof/v1';
58
+ route: 'plain' | 'inferred' | 'witness';
59
+ identity: CaptureIdentity;
60
+ original: FamilyBundle['original'];
61
+ verdict: Verdict;
62
+ terms: TermPrelude;
63
+ proof: ProofOutputNode;
64
+ projection: Projection;
65
+ };
66
+ export type NativeBundle = FamilyBundle | ProvenanceBundle;
67
+ export type OriginalInput = FamilyBundle['original'] | {
68
+ laws: Law[];
69
+ };
70
+ export type CaptureHooks = {
71
+ proofObserver: {
72
+ on?: (event: PublicProofOutput) => void;
73
+ };
74
+ quiescent: () => boolean;
75
+ nativeSucceeded?: () => boolean;
76
+ snapshotTerms: () => TermPrelude;
77
+ write: (bundle: NativeBundle) => {
78
+ manifestSha256: string;
79
+ };
80
+ };
81
+ export declare function retainedLawCoverage(original: Law[], final: Law[]): number[] | null;
82
+ export declare function lawCoverage(original: Law[], final: Law[]): number[];
83
+ export declare function inspectProvenance(root: ProofOutputNode): {
84
+ route: 'plain' | 'inferred' | 'witness' | 'counted-family';
85
+ counted: Extract<ProofOutputNode, {
86
+ kind: 'counted';
87
+ }>[];
88
+ usual: Extract<ProofOutputNode, {
89
+ kind: 'usual';
90
+ }>[];
91
+ };
92
+ export declare function qualifyProjection(original: FamilyBundle['original'], machine: Machine, laws: Law[]): Projection;
93
+ export declare function projectionOf(bundle: NativeBundle): Projection;
94
+ export declare function captureInvocation<T extends Verdict>(identity: CaptureIdentity, original: OriginalInput | (() => OriginalInput), invoke: () => T, hooks: CaptureHooks): {
95
+ verdict: T;
96
+ retention: {
97
+ complete: true;
98
+ manifestSha256: string;
99
+ projection: Projection;
100
+ } | {
101
+ complete: false;
102
+ error: string;
103
+ };
104
+ };
@@ -0,0 +1,216 @@
1
+ // Structural identity of the public law AST, not a name-only coverage claim.
2
+ // This is output-phase validation, and deliberately does not call termId.
3
+ function ast(value, active = new Set()) {
4
+ if (value === undefined)
5
+ return 'u';
6
+ if (value === null)
7
+ return 'null';
8
+ if (typeof value === 'string' || typeof value === 'boolean')
9
+ return JSON.stringify(value);
10
+ if (typeof value === 'number') {
11
+ const b = Buffer.alloc(8);
12
+ b.writeDoubleBE(value);
13
+ return `n:${b.toString('hex')}`;
14
+ }
15
+ if (typeof value !== 'object' || active.has(value))
16
+ throw Error('unsupported or cyclic law AST');
17
+ const p = Object.getPrototypeOf(value);
18
+ if (p !== Object.prototype && p !== null && p !== Array.prototype)
19
+ throw Error('unsupported law AST prototype');
20
+ active.add(value);
21
+ try {
22
+ if (Array.isArray(value)) {
23
+ for (let i = 0; i < value.length; i++)
24
+ if (!Object.hasOwn(value, i))
25
+ throw Error('sparse law AST');
26
+ return '[' + value.map(v => ast(v, active)).join(',') + ']';
27
+ }
28
+ return '{' + Reflect.ownKeys(value).map(key => {
29
+ if (typeof key !== 'string')
30
+ throw Error('symbol law AST');
31
+ const d = Object.getOwnPropertyDescriptor(value, key);
32
+ if (!('value' in d))
33
+ throw Error('accessor law AST');
34
+ return [key, d.value];
35
+ }).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, v]) => JSON.stringify(key) + ':' + ast(v, active)).join(',') + '}';
36
+ }
37
+ finally {
38
+ active.delete(value);
39
+ }
40
+ }
41
+ export function retainedLawCoverage(original, final) {
42
+ try {
43
+ return lawCoverage(original, final);
44
+ }
45
+ catch {
46
+ return null;
47
+ }
48
+ }
49
+ export function lawCoverage(original, final) {
50
+ const names = new Set();
51
+ for (const law of final) {
52
+ if (names.has(law.name))
53
+ throw Error('duplicate final law name');
54
+ names.add(law.name);
55
+ }
56
+ const seen = new Set();
57
+ return original.map(law => {
58
+ if (seen.has(law.name))
59
+ throw Error('duplicate public law name');
60
+ seen.add(law.name);
61
+ const i = final.findIndex(candidate => candidate.name === law.name);
62
+ if (i < 0 || ast(final[i]) !== ast(law))
63
+ throw Error(`public law is not present unchanged: ${law.name}`);
64
+ return i;
65
+ });
66
+ }
67
+ function validIdentity(x) {
68
+ for (const key of ['protocol', 'invocation'])
69
+ if (!x[key] || typeof x[key] !== 'string')
70
+ throw Error(`missing capture identity: ${key}`);
71
+ for (const key of ['sourceCommit', 'sourceTree'])
72
+ if (!/^[0-9a-f]{40}$/.test(x[key]))
73
+ throw Error(`invalid capture identity: ${key}`);
74
+ for (const key of ['driverSha256', 'inputSha256', 'runtimeSha256', 'profileSha256'])
75
+ if (!/^[0-9a-f]{64}$/.test(x[key]))
76
+ throw Error(`invalid capture identity: ${key}`);
77
+ if (!/^[1-9][0-9]*$/.test(x.workBudget))
78
+ throw Error('invalid work budget');
79
+ if (!x.flags || Object.values(x.flags).some(v => typeof v !== 'string'))
80
+ throw Error('invalid flag closure');
81
+ }
82
+ export function inspectProvenance(root) {
83
+ const visited = new Set(), active = new Set(), stack = [[root, false]], counted = [];
84
+ const usual = [];
85
+ let inferred = false, witness = false;
86
+ while (stack.length) {
87
+ const [node, exit] = stack.pop();
88
+ if (!node || typeof node !== 'object')
89
+ throw Error('missing producer provenance');
90
+ if (exit) {
91
+ active.delete(node);
92
+ visited.add(node);
93
+ continue;
94
+ }
95
+ if (active.has(node))
96
+ throw Error('cyclic producer provenance');
97
+ if (visited.has(node))
98
+ continue;
99
+ active.add(node);
100
+ stack.push([node, true]);
101
+ if (node.kind === 'derived') {
102
+ const kind = node.context?.kind;
103
+ if (!['projection', 'inference', 'witness', 'skolem', 'some-key'].includes(String(kind)))
104
+ throw Error('unsupported derivation context');
105
+ inferred ||= kind === 'inference';
106
+ witness ||= ['witness', 'skolem', 'some-key'].includes(String(kind));
107
+ if (!node.parents.length)
108
+ throw Error('derivation without a producer');
109
+ for (const parent of node.parents) {
110
+ if (!parent)
111
+ throw Error('missing producer link');
112
+ stack.push([parent, false]);
113
+ }
114
+ }
115
+ else if (node.kind === 'usual' || node.kind === 'counted') {
116
+ if (!node.machine || !Array.isArray(node.laws) || !node.proof?.instances)
117
+ throw Error('incomplete producer family');
118
+ if (node.kind === 'counted') {
119
+ if (!node.proof.certs)
120
+ throw Error('missing counted certificates');
121
+ counted.push(node);
122
+ }
123
+ else {
124
+ if (!node.proof.trees)
125
+ throw Error('missing usual trees');
126
+ usual.push(node);
127
+ }
128
+ }
129
+ else
130
+ throw Error('unsupported proof producer');
131
+ }
132
+ if (!usual.length && !counted.length)
133
+ throw Error('no complete producer family');
134
+ return { route: witness ? 'witness' : inferred ? 'inferred' : counted.length && !usual.length ? 'counted-family' : 'plain', counted, usual };
135
+ }
136
+ // This is deliberately a narrow structural source projection, not a new prover.
137
+ // Keep other complete data for later checked bridges, but never qualify it here.
138
+ export function qualifyProjection(original, machine, laws) {
139
+ try {
140
+ if (ast(original.machine) !== ast(machine))
141
+ return { kind: 'unqualified', reason: 'producer machine differs from public machine' };
142
+ return { kind: 'same-machine', publicLawIndices: lawCoverage(original.laws, laws) };
143
+ }
144
+ catch (error) {
145
+ return { kind: 'unqualified', reason: error instanceof Error ? error.message : String(error) };
146
+ }
147
+ }
148
+ export function projectionOf(bundle) {
149
+ if (bundle.route === 'counted-family')
150
+ return qualifyProjection(bundle.original, bundle.final.machine, bundle.final.laws);
151
+ const found = inspectProvenance(bundle.proof);
152
+ if (found.route === 'witness')
153
+ return { kind: 'unqualified', reason: 'witness source projection requires a checked bridge' };
154
+ if (found.usual.length !== 1 || found.counted.length)
155
+ return { kind: 'unqualified', reason: 'no unique usual family' };
156
+ return qualifyProjection(bundle.original, found.usual[0].machine, found.usual[0].laws);
157
+ }
158
+ export function captureInvocation(identity, original, invoke, hooks) {
159
+ validIdentity(identity);
160
+ if (!hooks.quiescent())
161
+ throw Error('capture must start outside every work endpoint');
162
+ if (hooks.proofObserver.on !== undefined)
163
+ throw Error('unexpected proof output observer');
164
+ let replaced = false, publicResult, events = 0;
165
+ const proofObserver = (event) => { publicResult = event; events++; };
166
+ hooks.proofObserver.on = proofObserver;
167
+ let verdict;
168
+ try {
169
+ verdict = invoke();
170
+ }
171
+ finally {
172
+ replaced = hooks.proofObserver.on !== proofObserver;
173
+ hooks.proofObserver.on = undefined;
174
+ }
175
+ try {
176
+ if (!hooks.quiescent())
177
+ throw Error('output attempted before the work root exited');
178
+ if (!verdict || typeof verdict !== 'object' || 'then' in verdict)
179
+ throw Error('native invocation must return synchronously');
180
+ if (verdict.proven !== true || verdict.checked !== true || hooks.nativeSucceeded && !hooks.nativeSucceeded())
181
+ throw Error('native invocation did not return proven and checked');
182
+ if (replaced || events !== 1)
183
+ throw Error('missing, replaced or ambiguous public output observer');
184
+ // Snapshot before all validation/traversal, outside the completed work root.
185
+ const terms = hooks.snapshotTerms(), supplied = typeof original === 'function' ? original() : original;
186
+ const input = 'machine' in supplied ? supplied : publicResult ? { machine: publicResult.original.machine, laws: supplied.laws } : undefined;
187
+ if (!input || publicResult?.result !== verdict || publicResult.original.machine !== input.machine || publicResult.original.laws !== input.laws)
188
+ throw Error('no exact final public-result provenance');
189
+ const provenance = publicResult.proof;
190
+ if (!provenance)
191
+ throw Error('no final family: refusing a stale or reconstructed proof');
192
+ const inspected = inspectProvenance(provenance);
193
+ let bundle;
194
+ if (inspected.route === 'counted-family') {
195
+ if (inspected.counted.length !== 1)
196
+ throw Error('ambiguous counted producer family');
197
+ const leaf = inspected.counted[0];
198
+ const final = { phase: 'closed-family', checked: true, machine: leaf.machine, laws: leaf.laws, proof: leaf.proof };
199
+ for (const law of final.laws)
200
+ for (const suffix of [' @start', ' @step'])
201
+ if (!Object.hasOwn(final.proof.certs, law.name + suffix))
202
+ throw Error('missing family certificate: ' + law.name + suffix);
203
+ const publicLawIndices = retainedLawCoverage(input.laws, final.laws);
204
+ bundle = { schema: 'bapa-family/v1', route: 'counted-family', identity, original: input, final, verdict, terms, publicLawIndices, projection: qualifyProjection(input, final.machine, final.laws) };
205
+ }
206
+ else {
207
+ bundle = { schema: 'bapa-proof/v1', route: inspected.route, identity, original: input, verdict, terms, proof: provenance, projection: { kind: 'unqualified', reason: 'not yet inspected' } };
208
+ bundle.projection = projectionOf(bundle);
209
+ }
210
+ const receipt = hooks.write(bundle);
211
+ return { verdict, retention: { complete: true, manifestSha256: receipt.manifestSha256, projection: bundle.projection } };
212
+ }
213
+ catch (error) {
214
+ return { verdict, retention: { complete: false, error: error instanceof Error ? error.message : String(error) } };
215
+ }
216
+ }
@@ -0,0 +1,28 @@
1
+ import { type NativeBundle } from './proof-capture.js';
2
+ export type CaptureManifest = {
3
+ schema: 'bapa-native-certificate/v1';
4
+ complete: true;
5
+ route: NativeBundle['route'];
6
+ identity: NativeBundle['identity'];
7
+ graphManifestSha256: string;
8
+ projection: NativeBundle['projection'];
9
+ publicLawIndices?: number[] | null;
10
+ familyLaws?: number;
11
+ certificateKeys?: string[];
12
+ terms: number;
13
+ };
14
+ export declare function writeFamilyCapsule(directory: string, bundle: NativeBundle, metadata?: (value: object) => unknown): {
15
+ manifestSha256: string;
16
+ };
17
+ export type ReadLimits = {
18
+ maxBytes: number;
19
+ maxNodes: number;
20
+ maxStrings: number;
21
+ maxArrayLength: number;
22
+ maxShards: number;
23
+ };
24
+ export declare function readCertificateGraph(directory: string, expectedManifestSha256: string, limits: ReadLimits, onMetadata?: (object: object, value: unknown) => void): unknown;
25
+ export declare function readFamilyCapsule(directory: string, expectedSha256: string, limits: ReadLimits, onMetadata?: (object: object, value: unknown) => void): {
26
+ manifest: CaptureManifest;
27
+ data: unknown;
28
+ };