gdp-wired 0.50.6 → 0.52.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +2 -2
  2. package/dist/core/accel-refute.d.ts +53 -0
  3. package/dist/core/accel-refute.js +997 -0
  4. package/dist/core/cli.d.ts +2 -0
  5. package/dist/core/cli.js +8 -1
  6. package/dist/core/cycles.d.ts +2 -0
  7. package/dist/core/cycles.js +12 -9
  8. package/dist/core/dsl.d.ts +11 -2
  9. package/dist/core/dsl.js +194 -29
  10. package/dist/core/fixed-division.d.ts +9 -0
  11. package/dist/core/fixed-division.js +87 -0
  12. package/dist/core/fixed-integers.d.ts +33 -0
  13. package/dist/core/fixed-integers.js +279 -0
  14. package/dist/core/live-support.d.ts +5 -0
  15. package/dist/core/live-support.js +148 -0
  16. package/dist/core/live.js +194 -37
  17. package/dist/core/lockstep.d.ts +5 -0
  18. package/dist/core/lockstep.js +23 -0
  19. package/dist/core/machine.d.ts +1 -0
  20. package/dist/core/machine.js +33 -3
  21. package/dist/core/ordered-pair-seeds.d.ts +2 -0
  22. package/dist/core/ordered-pair-seeds.js +109 -0
  23. package/dist/core/proof-output.d.ts +38 -1
  24. package/dist/core/proof-output.js +38 -0
  25. package/dist/core/search-termination.d.ts +4 -0
  26. package/dist/core/search-termination.js +1 -1
  27. package/dist/core/source-check.d.ts +4 -1
  28. package/dist/core/source-check.js +5 -2
  29. package/dist/core/sparse-kind-proof.d.ts +7 -0
  30. package/dist/core/sparse-kind-proof.js +49 -0
  31. package/dist/core/step-seeds.d.ts +46 -0
  32. package/dist/core/step-seeds.js +316 -0
  33. package/dist/kernel/integer-primitives.d.ts +38 -0
  34. package/dist/kernel/integer-primitives.js +179 -0
  35. package/dist/kernel/kernel.d.ts +1 -0
  36. package/dist/kernel/kernel.js +44 -5
  37. package/dist/kernel/prove.js +13 -0
  38. package/dist/kernel/word-division-cuts.d.ts +6 -0
  39. package/dist/kernel/word-division-cuts.js +69 -0
  40. package/dist/kernel/word-division.d.ts +12 -0
  41. package/dist/kernel/word-division.js +167 -0
  42. package/dist/lean-kernel/Cert.lean +222 -0
  43. package/dist/lean-kernel/Count.lean +1568 -0
  44. package/dist/lean-kernel/Ghost.lean +373 -0
  45. package/dist/lean-kernel/GhostMap.lean +426 -0
  46. package/dist/lean-kernel/Kernel.lean +2881 -0
  47. package/dist/lean-kernel/Live.lean +1168 -0
  48. package/dist/lean-kernel/Progress.lean +543 -0
  49. package/dist/lean-kernel/Sets.lean +1975 -0
  50. package/dist/lean-kernel/StepLaw.lean +128 -0
  51. package/dist/lean-kernel/Steps.lean +477 -0
  52. package/dist/lean-kernel/Sums.lean +916 -0
  53. package/dist/lean-kernel/emit.d.ts +8 -1
  54. package/dist/lean-kernel/emit.js +59 -15
  55. package/dist/lean-kernel/integer-primitives.d.ts +17 -0
  56. package/dist/lean-kernel/integer-primitives.js +81 -0
  57. package/dist/lean-kernel/lean-aggregate/FiniteFold.lean +44 -0
  58. package/dist/lean-kernel/lean-aggregate/GroupedTransport.lean +308 -0
  59. package/dist/lean-kernel/lean-aggregate/aggregate.d.ts +13 -0
  60. package/dist/lean-kernel/lean-aggregate/aggregate.js +68 -0
  61. package/dist/lean-kernel/lean-aggregate/assets.d.ts +5 -0
  62. package/dist/lean-kernel/lean-aggregate/assets.js +7 -0
  63. package/dist/lean-kernel/lean-aggregate/audit.d.ts +3 -0
  64. package/dist/lean-kernel/lean-aggregate/audit.js +13 -0
  65. package/dist/lean-kernel/lean-aggregate/exact.d.ts +15 -0
  66. package/dist/lean-kernel/lean-aggregate/exact.js +51 -0
  67. package/dist/lean-kernel/lean-aggregate/index.d.ts +19 -0
  68. package/dist/lean-kernel/lean-aggregate/index.js +52 -0
  69. package/dist/lean-kernel/lean-aggregate/point-fold.d.ts +27 -0
  70. package/dist/lean-kernel/lean-aggregate/point-fold.js +79 -0
  71. package/dist/lean-kernel/lean-aggregate/replay-fold.d.ts +2 -0
  72. package/dist/lean-kernel/lean-aggregate/replay-fold.js +163 -0
  73. package/dist/lean-kernel/lean-aggregate/source.d.ts +2 -0
  74. package/dist/lean-kernel/lean-aggregate/source.js +141 -0
  75. package/dist/lean-kernel/lean-aggregate/weighted-flags.d.ts +2 -0
  76. package/dist/lean-kernel/lean-aggregate/weighted-flags.js +26 -0
  77. package/dist/lean-kernel/lean-aggregate/weighted-replay.d.ts +7 -0
  78. package/dist/lean-kernel/lean-aggregate/weighted-replay.js +53 -0
  79. package/dist/lean-kernel/lean-aggregate/weighted-seeded.d.ts +30 -0
  80. package/dist/lean-kernel/lean-aggregate/weighted-seeded.js +64 -0
  81. package/dist/lean-kernel/lean-aggregate/weighted.d.ts +18 -0
  82. package/dist/lean-kernel/lean-aggregate/weighted.js +115 -0
  83. package/dist/lean-kernel/lean-aggregate/worker.d.ts +10 -0
  84. package/dist/lean-kernel/lean-aggregate/worker.js +46 -0
  85. package/dist/lean-kernel/library.js +13 -0
  86. package/dist/lean-kernel/word-division-export.d.ts +26 -0
  87. package/dist/lean-kernel/word-division-export.js +172 -0
  88. package/dist/lean-kernel/word-division-lower.d.ts +10 -0
  89. package/dist/lean-kernel/word-division-lower.js +103 -0
  90. package/docs/lean-aggregate.md +29 -0
  91. package/package.json +6 -1
@@ -0,0 +1,68 @@
1
+ // Untrusted, intentionally small syntax recognizers. Their products are
2
+ // candidates for exact finite-fold replay, never extra source facts.
3
+ import { get, n, x, plus } from "../../core/machine.js";
4
+ import { substC } from "../../kernel/kernel.js";
5
+ const equal = (a, b) => JSON.stringify(a) === JSON.stringify(b);
6
+ const atoms = (c) => !c ? [] : c.op === 'and' ? c.xs.flatMap(atoms) : [c];
7
+ const subKey = (c, name, term) => substC(c, { vars: { [name]: term }, maps: {}, flags: {} });
8
+ const rootReset = (u, start) => u.op === 'if' && equal(u.then, start) ? u : undefined;
9
+ const increase = (u, field) => u.op === 'if' && equal(u.else, x(field)) && equal(u.then, plus(x(field), n(1))) ? u.c : undefined;
10
+ const guardIncludes = (full, sub) => atoms(sub).every(p => atoms(full).some(q => equal(p, q)));
11
+ const onlyVariable = (e, name) => e.op === 'var' && e.name === name;
12
+ export function proposeFilteredCounters(m, caller) {
13
+ if (m.history || Object.keys(m.counts ?? {}).length || Object.keys(m.sums ?? {}).length || caller.forall || caller.keys?.length)
14
+ return [];
15
+ const uses = JSON.stringify(caller.holds);
16
+ const out = [];
17
+ for (const [map, wr] of Object.entries(m.step.maps ?? {})) {
18
+ // Cover singleton point writes and broadcast-reset-plus-point writes. A
19
+ // spatial guard is not accepted as a scalar guard; it is first specialized.
20
+ if (!('each' in wr) || m.maps?.[map] === undefined)
21
+ continue;
22
+ const init = n(m.maps[map]);
23
+ const outer = rootReset(wr.value, init), first = outer?.else;
24
+ if (!outer || first?.op !== 'if')
25
+ continue;
26
+ const keyAtom = atoms(first.c).find(c => c.op === '=' && onlyVariable(c.a, wr.each) && c.b.op === 'var' && m.inputs.includes(c.b.name));
27
+ if (keyAtom?.op !== '=' || keyAtom.b.op !== 'var')
28
+ continue;
29
+ const key = keyAtom.b.name;
30
+ const below = atoms(m.assume).find(c => (c.op === '<=' || c.op === '<') && onlyVariable(c.a, key) && c.b.op === 'var' && m.params.includes(c.b.name));
31
+ if (!below || (below.op !== '<=' && below.op !== '<'))
32
+ continue;
33
+ const lower = atoms(m.assume).filter(c => c.op === '<=' && c.a.op === 'const' && onlyVariable(c.b, key)).map(c => c.op === '<=' && c.a.op === 'const' ? c.a.value : 0);
34
+ const offset = Math.max(0, ...lower);
35
+ const bound0 = below.op === '<=' ? plus(below.b, n(1)) : below.b;
36
+ const bound = below.op === '<=' && offset === 1 ? below.b : offset ? { op: 'sub', a: bound0, b: n(offset) } : bound0;
37
+ const options = [];
38
+ let walk = first;
39
+ for (let i = 0; i < 8 && walk.op === 'if'; i++, walk = walk.else) {
40
+ const value = walk.then;
41
+ const parts = atoms(walk.c);
42
+ if (!parts.some(p => equal(p, keyAtom)) || value.op !== 'const' || equal(value, init))
43
+ break;
44
+ const [one, ...more] = parts.filter(p => !equal(p, keyAtom));
45
+ if (!one)
46
+ break;
47
+ options.push({ value: value.value, guard: more.length ? { op: 'and', xs: [one, ...more] } : one });
48
+ }
49
+ if (!equal(walk, get(map, x(wr.each))) || !options.length)
50
+ continue;
51
+ const counters = Object.entries(m.step.state ?? {}).flatMap(([field, u]) => {
52
+ if (!uses.includes(`"name":${JSON.stringify(field)}`) || !equal(m.state[field], n(0)))
53
+ return [];
54
+ const reset = rootReset(u, n(0)), guard = reset && increase(reset.else, field);
55
+ return reset && guard && equal(reset.c, outer.c) ? [{ field, guard }] : [];
56
+ });
57
+ const fields = counters.flatMap(({ field, guard }) => {
58
+ // Prefer the first branch whose guard is covered by the increment. Later
59
+ // alternatives are fallback writes in the source's own branch order.
60
+ const opt = options.find(o => guardIncludes(guard, o.guard));
61
+ return opt ? [{ field, value: opt.value }] : [];
62
+ });
63
+ if (!fields.length || new Set(fields.map(f => f.value)).size !== fields.length)
64
+ continue;
65
+ out.push({ map, key, reset: subKey(outer.c, wr.each, x(key)), bound, offset, fields });
66
+ }
67
+ return out;
68
+ }
@@ -0,0 +1,5 @@
1
+ export declare const leanLibraries: {
2
+ readonly 'finite-fold': readonly [...string[], "../Count.lean", "./FiniteFold.lean"];
3
+ readonly weighted: readonly [...string[], "../GhostMap.lean", "../Sums.lean", "./GroupedTransport.lean"];
4
+ };
5
+ export type AggregateMechanism = keyof typeof leanLibraries;
@@ -0,0 +1,7 @@
1
+ // Topological order. Build and the staged replay use these exact packaged sources.
2
+ const machine = ['../Cert.lean', '../Kernel.lean', '../Progress.lean', '../StepLaw.lean',
3
+ '../Steps.lean', '../Sets.lean', '../Live.lean', '../Ghost.lean'];
4
+ export const leanLibraries = {
5
+ 'finite-fold': [...machine, '../Count.lean', './FiniteFold.lean'],
6
+ 'weighted': [...machine, '../GhostMap.lean', '../Sums.lean', './GroupedTransport.lean'],
7
+ };
@@ -0,0 +1,3 @@
1
+ export declare const theorem = "aggregate_claim";
2
+ export declare const axiomCommand = "\nset_option pp.fullNames true in\n#print axioms aggregate_claim\n";
3
+ export declare function exactAxioms(log: string): readonly string[];
@@ -0,0 +1,13 @@
1
+ import { answers, standard } from "../axiom-audit.js";
2
+ export const theorem = 'aggregate_claim';
3
+ export const axiomCommand = `\nset_option pp.fullNames true in\n#print axioms ${theorem}\n`;
4
+ // Check the public theorem specifically, not just a count of #print answers.
5
+ // With fullNames on, no short-name alias for an arbitrary axiom is allowed.
6
+ export function exactAxioms(log) {
7
+ const rows = answers(log);
8
+ const row = rows[0];
9
+ if (/\b(?:error|warning):[^\r\n]*(?:sorry|admit)|\berror:/i.test(log) || rows.length !== 1 || row?.name !== theorem
10
+ || row.axioms.some(a => !standard.includes(a)) || new Set(row.axioms).size !== row.axioms.length)
11
+ throw new Error('Lean did not report exactly the allowed axioms for the bound aggregate theorem.');
12
+ return row.axioms;
13
+ }
@@ -0,0 +1,15 @@
1
+ import { type AggregateMechanism } from './assets.js';
2
+ import { theorem } from './audit.js';
3
+ export declare const sha256: (text: string | Uint8Array) => string;
4
+ export type AggregateLeanReceipt = Readonly<{
5
+ schema: 'gdp-wired/lean-aggregate/v1';
6
+ inputSha256: string;
7
+ sourceSha256: string;
8
+ source: string;
9
+ libraries: Readonly<Record<string, string>>;
10
+ version: string;
11
+ theorem: typeof theorem;
12
+ axioms: readonly string[];
13
+ log: string;
14
+ }>;
15
+ export declare function runExactLean(mechanism: AggregateMechanism, generated: string, inputSha256: string, ms: number): Promise<AggregateLeanReceipt>;
@@ -0,0 +1,51 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { basename, join } from 'node:path';
6
+ import { leanLibraries } from "./assets.js";
7
+ import { exactAxioms, axiomCommand, theorem } from "./audit.js";
8
+ export const sha256 = (text) => createHash('sha256').update(text).digest('hex');
9
+ const release = '4.34.0', toolchain = `leanprover/lean4:v${release}`;
10
+ // Official 4.34.0 release, not an RC or a toolchain with the same version prefix.
11
+ const pinned = /^Lean \(version 4\.34\.0, [\w.-]+, commit 293d5d0c0c3f3dded4688b3ccd6a33939ac5102b, Release\)$/;
12
+ // Internal only: the public entry never accepts a Lean program, a log, an
13
+ // olean file, or a success marker from the caller.
14
+ export async function runExactLean(mechanism, generated, inputSha256, ms) {
15
+ const dir = mkdtempSync(join(tmpdir(), 'gdp-aggregate-'));
16
+ try {
17
+ const until = performance.now() + ms;
18
+ const run = (args) => new Promise((resolve, reject) => {
19
+ const timeout = Math.floor(until - performance.now());
20
+ if (timeout <= 0) {
21
+ reject(new Error('Lean replay deadline expired.'));
22
+ return;
23
+ }
24
+ execFile('lean', args, { cwd: dir, env: { ...process.env, ELAN_TOOLCHAIN: toolchain, LEAN_PATH: dir, LEAN_SRC_PATH: dir },
25
+ encoding: 'utf8', timeout, killSignal: 'SIGKILL', maxBuffer: 4 * 1024 * 1024 }, (error, stdout, stderr) => {
26
+ const log = `${stdout}\n${stderr}`.trim();
27
+ if (error || /\berror:|declaration uses 'sorry'/i.test(log))
28
+ reject(new Error(`Lean ${args.join(' ')} refused: ${log.slice(0, 2400) || error?.message}.`));
29
+ else
30
+ resolve(log);
31
+ });
32
+ });
33
+ const version = await run(['--version']);
34
+ if (!pinned.test(version))
35
+ throw new Error(`Expected exact Lean ${release}; got ${version.slice(0, 240)}.`);
36
+ const libraries = {};
37
+ for (const path of leanLibraries[mechanism]) {
38
+ const file = basename(path), body = readFileSync(new URL(path, import.meta.url));
39
+ libraries[file] = sha256(body);
40
+ writeFileSync(join(dir, file), body, { flag: 'wx' });
41
+ await run(['-o', file.replace(/\.lean$/, '.olean'), file]);
42
+ }
43
+ const source = `-- gdp-wired/lean-aggregate input sha256: ${inputSha256}\n${generated}${axiomCommand}`, file = 'Aggregate.lean';
44
+ writeFileSync(join(dir, file), source, { flag: 'wx' });
45
+ const log = await run([file]), axioms = exactAxioms(log);
46
+ return { schema: 'gdp-wired/lean-aggregate/v1', inputSha256, source, sourceSha256: sha256(source), libraries, version, theorem, axioms, log };
47
+ }
48
+ finally {
49
+ rmSync(dir, { recursive: true, force: true });
50
+ }
51
+ }
@@ -0,0 +1,19 @@
1
+ import type { Law, Machine } from '../../core/machine.js';
2
+ import { type AggregateLeanReceipt } from './exact.js';
3
+ import type { AggregateMechanism } from './assets.js';
4
+ export type { AggregateLeanReceipt } from './exact.js';
5
+ export type LeanAggregateOptions = Readonly<{
6
+ searchMs?: number;
7
+ leanMs?: number;
8
+ }>;
9
+ export type LeanAggregateVerdict = Readonly<{
10
+ kind: 'lean-checked';
11
+ verdict: 'checked in Lean, not by the kernel';
12
+ mechanism: AggregateMechanism;
13
+ receipt: AggregateLeanReceipt;
14
+ }> | Readonly<{
15
+ kind: 'not-checked';
16
+ reason: 'unsupported' | 'search' | 'lean';
17
+ detail: string;
18
+ }>;
19
+ export declare function proveLeanAggregate(machine: Machine, law: Law, options?: LeanAggregateOptions): Promise<LeanAggregateVerdict>;
@@ -0,0 +1,52 @@
1
+ import { Worker } from 'node:worker_threads';
2
+ import { admitAggregateSource } from "./source.js";
3
+ import { runExactLean, sha256 } from "./exact.js";
4
+ async function search(input) {
5
+ const suffix = import.meta.url.endsWith('.ts') ? 'ts' : 'js';
6
+ const worker = new Worker(new URL(`./worker.${suffix}`, import.meta.url), { workerData: input });
7
+ let timer;
8
+ try {
9
+ return await new Promise((resolve, reject) => {
10
+ timer = setTimeout(() => reject(new Error('Aggregate search/serialization deadline expired.')), input.ms + 5000);
11
+ worker.once('message', (result) => resolve(result));
12
+ worker.once('error', reject);
13
+ worker.once('exit', code => reject(new Error(`Aggregate worker exited without a candidate (${code}).`)));
14
+ });
15
+ }
16
+ finally {
17
+ clearTimeout(timer);
18
+ if (worker.threadId !== -1)
19
+ await worker.terminate();
20
+ }
21
+ }
22
+ // Deliberately separate from proveRule/proveSteps and native verdict types.
23
+ // The only success branch is after exact Lean checking and axiom validation.
24
+ export async function proveLeanAggregate(machine, law, options = {}) {
25
+ const { searchMs = 60_000, leanMs = 180_000 } = options;
26
+ const budget = (ms, max) => Number.isSafeInteger(ms) && ms > 0 && ms <= max;
27
+ if (!budget(searchMs, 60_000) || !budget(leanMs, 600_000))
28
+ return { kind: 'not-checked', reason: 'unsupported', detail: 'Use 1–60000 search ms and 1–600000 Lean ms.' };
29
+ let input;
30
+ try {
31
+ input = admitAggregateSource(machine, law);
32
+ }
33
+ catch (e) {
34
+ return { kind: 'not-checked', reason: 'unsupported', detail: String(e) };
35
+ }
36
+ let result;
37
+ try {
38
+ result = await search({ source: input, ms: searchMs });
39
+ }
40
+ catch (e) {
41
+ return { kind: 'not-checked', reason: 'search', detail: String(e) };
42
+ }
43
+ if (result.kind === 'refused')
44
+ return { kind: 'not-checked', reason: result.reason, detail: result.detail };
45
+ try {
46
+ const receipt = await runExactLean(result.mechanism, result.source, sha256(input), leanMs);
47
+ return { kind: 'lean-checked', verdict: 'checked in Lean, not by the kernel', mechanism: result.mechanism, receipt };
48
+ }
49
+ catch (e) {
50
+ return { kind: 'not-checked', reason: 'lean', detail: String(e) };
51
+ }
52
+ }
@@ -0,0 +1,27 @@
1
+ import { type C, type E, type Law, type Machine } from '../../core/machine.js';
2
+ import { type Goal, type Tree } from '../../kernel/kernel.js';
3
+ import { type FilteredCounterProposal } from './aggregate.js';
4
+ export type Scope = 'plain' | 'row';
5
+ export type Local = {
6
+ name: string;
7
+ assumptions: C[];
8
+ conclusion: C;
9
+ scope: Scope;
10
+ };
11
+ export type FoldTheory = {
12
+ locals: Local[];
13
+ bound: E;
14
+ coordinate: string;
15
+ point: E;
16
+ proposal: FilteredCounterProposal;
17
+ };
18
+ export type FoldPacket = {
19
+ kind: 'point-fold';
20
+ machine: Machine;
21
+ laws: Law[];
22
+ trees: Record<string, Tree>;
23
+ };
24
+ export declare function foldTheory(m: Machine, law: Law): FoldTheory | undefined;
25
+ export declare function provePointFold(m: Machine, law: Law, ms: number): FoldPacket | undefined;
26
+ export declare function checkPointFold(packet: FoldPacket): boolean;
27
+ export declare const localGoal: (l: Local) => Goal;
@@ -0,0 +1,79 @@
1
+ // A local certificate schema, outside the trusted checker. Its finite-fold
2
+ // composition and binding to the original step are checked in Lean.
3
+ import { atMost, get, n, not, plus, same, x } from "../../core/machine.js";
4
+ import { check, substC, substE } from "../../kernel/kernel.js";
5
+ import { clock, grow, withWall } from "../../kernel/prove.js";
6
+ import { searchWall } from "../../core/wall.js";
7
+ import { proposeFilteredCounters } from "./aggregate.js";
8
+ const zero = n(0);
9
+ const lt = (a, b) => ({ op: '<', a, b });
10
+ const iff = (c, then, otherwise) => ({ op: 'if', c, then, else: otherwise });
11
+ const toGoal = (l) => ({ name: l.name, hyps: [...l.assumptions, not(l.conclusion)] });
12
+ export function foldTheory(m, law) {
13
+ // Closed fragment for source binding: one source map, no carried maps, no
14
+ // external facts or special postprocessing. Unrecognized syntax falls back.
15
+ if (m.facts?.length || Object.keys(m.fns ?? {}).length || m.inputMaps?.length || Object.keys(m.maps ?? {}).length !== 1 || Object.keys(m.step.maps ?? {}).length !== 1)
16
+ return;
17
+ const p = proposeFilteredCounters(m, law)[0];
18
+ if (!p || p.fields.length < 2 || p.fields.length > 6 || !m.assume || p.bound.op !== 'var' || !m.params.includes(p.bound.name))
19
+ return;
20
+ const wr = m.step.maps[p.map];
21
+ if (!('each' in wr))
22
+ return;
23
+ const occupied = JSON.stringify([m, law]);
24
+ let local = 'agg$coordinate';
25
+ while (occupied.includes(local))
26
+ local += '0';
27
+ const j = x(local), input = x(p.key);
28
+ const plusOffset = (k) => p.offset ? plus(k, n(p.offset)) : k;
29
+ const point = p.offset ? { op: 'sub', a: input, b: n(p.offset) } : input;
30
+ const flags = Object.create(null);
31
+ for (const [name, c] of Object.entries(m.step.flags ?? {})) {
32
+ if (c.op === 'all')
33
+ return;
34
+ flags[name] = substC(c, { vars: {}, maps: {}, flags });
35
+ }
36
+ const inline = { vars: {}, maps: {}, flags };
37
+ const assume = substC(m.assume, inline), reset = substC(p.reset, inline), after = (k) => substE(wr.value, { ...inline, vars: { [wr.each]: k } });
38
+ const plain = (name, assumptions, conclusion) => ({ name, assumptions, conclusion, scope: 'plain' });
39
+ const row = (name, assumptions, conclusion) => ({ name, assumptions, conclusion, scope: 'row' });
40
+ const coord = plusOffset(j), atPoint = plusOffset(point);
41
+ const locals = [
42
+ plain('point_inside', [assume], lt(point, p.bound)),
43
+ row('other_cells_frame', [assume, not(reset), not(same(j, point))], same(after(coord), get(p.map, coord))),
44
+ row('broadcast_reset', [assume, reset], same(after(coord), n(m.maps[p.map]))),
45
+ plain('capacity_entails_claim', [atMost(p.fields.map(f => x(f.field)).reduce(plus), p.bound)], law.holds),
46
+ ];
47
+ for (const [i, f] of p.fields.entries()) {
48
+ const next = substE(m.step.state[f.field], inline);
49
+ const indicator = (cell) => iff(same(cell, n(f.value)), n(1), zero);
50
+ locals.push(plain(`field${i}_init`, [], same(m.state[f.field], zero)), plain(`field${i}_reset`, [assume, reset], same(next, zero)), plain(`field${i}_delta`, [assume, not(reset)], same(plus(next, indicator(get(p.map, atPoint))), plus(x(f.field), indicator(after(atPoint))))));
51
+ }
52
+ const classified = p.fields.map(f => iff(same(get(p.map, coord), n(f.value)), n(1), zero)).reduce(plus);
53
+ locals.push(row('disjoint_capacity', [], atMost(classified, n(1))));
54
+ return { locals, coordinate: local, bound: p.bound, point, proposal: p };
55
+ }
56
+ export function provePointFold(m, law, ms) {
57
+ const theory = foldTheory(m, law);
58
+ if (!theory || ms <= 0)
59
+ return;
60
+ return withWall(searchWall(ms), () => {
61
+ const until = clock() + ms, trees = Object.create(null);
62
+ for (const local of theory.locals) {
63
+ const out = grow(toGoal(local), new Map(), { nodes: 0, until });
64
+ if (!('tree' in out))
65
+ return;
66
+ trees[local.name] = out.tree;
67
+ }
68
+ const packet = { kind: 'point-fold', machine: m, laws: [law], trees };
69
+ return checkPointFold(packet) ? packet : undefined;
70
+ });
71
+ }
72
+ export function checkPointFold(packet) {
73
+ const t = packet.laws.length === 1 && foldTheory(packet.machine, packet.laws[0]);
74
+ return !!t && Object.keys(packet.trees).length === t.locals.length && t.locals.every(local => {
75
+ const tree = Object.hasOwn(packet.trees, local.name) && packet.trees[local.name];
76
+ return !!tree && check(toGoal(local), tree);
77
+ });
78
+ }
79
+ export const localGoal = toGoal;
@@ -0,0 +1,2 @@
1
+ import { type FoldPacket } from './point-fold.js';
2
+ export declare function emitPointFold(packet: FoldPacket): string;
@@ -0,0 +1,163 @@
1
+ import assert from 'node:assert/strict';
2
+ import { encode, machineLit } from "../../lean-kernel/emit.js";
3
+ import { leanTerms } from "../../lean-kernel/lean-terms.js";
4
+ import { checkPointFold, foldTheory, localGoal } from "./point-fold.js";
5
+ export function emitPointFold(packet) {
6
+ assert(checkPointFold(packet));
7
+ const { machine: m, laws: [law] } = packet, theory = foldTheory(m, law);
8
+ const { proposal: p, coordinate, locals, point } = theory;
9
+ const writes = m.step.maps[p.map];
10
+ assert('each' in writes);
11
+ assert(theory.bound.op === 'var');
12
+ const names = [...new Set([...m.params, ...m.inputs, ...Object.keys(m.state), ...Object.keys(m.step.flags ?? {}).map(f => `?${f}`), writes.each, coordinate])];
13
+ const maps = [p.map], t = leanTerms(names, maps, 'finite fold'), ix = (x) => { const i = names.indexOf(x); assert(i >= 0, x); return i; }, mx = (name) => { assert.equal(name, p.map); return 0; };
14
+ const certs = locals.map(loc => {
15
+ const goal = localGoal(loc), cert = encode({ name: loc.name, goal, tree: packet.trees[loc.name] }, false, true, names, maps);
16
+ const hypotheses = loc.assumptions.map((h, i) => ` (h${i} : holdsC env maps (${t.c(h)}))`).join('');
17
+ const choices = Array.from({ length: goal.hyps.length }, () => 'rfl').join(' | ');
18
+ return `def ${loc.name}_goal : Kern.Goal := ⟨${cert.tab}, ${cert.hyps}⟩
19
+ def ${loc.name}_tree : Kern.Tree := ${cert.tree}
20
+ theorem ${loc.name}_check : checkGoal ${loc.name}_goal ${loc.name}_tree = true := by decide +kernel
21
+ theorem checked_${loc.name} (env : Nat → Nat) (maps : Nat → Nat → Nat)${hypotheses} :
22
+ holdsC env maps (${t.c(loc.conclusion)}) := by
23
+ apply Classical.byContradiction
24
+ intro h
25
+ apply sound ${loc.name}_goal ${loc.name}_tree ${loc.name}_check env maps
26
+ intro c hc
27
+ simp only [${loc.name}_goal, List.mem_cons, List.mem_nil_iff, or_false] at hc
28
+ ${goal.hyps.length === 1 ? ' subst c' : ` rcases hc with ${choices}`}
29
+ ${loc.assumptions.map((_, i) => ` · exact (evalC_iff env maps _).2 h${i}`).join('\n')}
30
+ ${loc.assumptions.length ? '· ' : ''}exact (evalC_iff env maps _).2 h`;
31
+ }).join('\n\n');
32
+ const boundIx = ix(theory.bound.name), addr = (v) => p.offset ? `(${v} + ${p.offset})` : v;
33
+ const sem = 'src, before, applyS, assoc, lookup, evalE, evalC, holdsC, upd, everyMaps, decideFlags, flagSub, withInputs, -List.elem_eq_contains';
34
+ const shift = (v) => `(upd X ${ix(coordinate)} ${v})`;
35
+ const stepvars = '(ρ : Nat → Nat) (M : Nat → Nat → Nat) (ι : Nat → Nat) (κ : Nat → Nat → Nat)';
36
+ const prev = '(before ρ ι)', next = '(sNext src ρ M ι κ)';
37
+ const cap = p.fields.map(f => `ρ ${ix(f.field)}`).reduce((a, b) => `(${a} + ${b})`);
38
+ const classBody = (mp) => p.fields.map(f => `countCell ${f.value} ${mp} j`).reduce((a, b) => `(${a} + ${b})`);
39
+ const bindStep = (f, i) => `
40
+ · have h0 : (applyS src.f.m.init ρ M) ${ix(f.field)} = 0 := by
41
+ simpa [${sem}] using checked_field${i}_init ρ M
42
+ change (applyS src.f.m.init ρ M) ${ix(f.field)} = sumBelow (countCell ${f.value} M) (applyS src.f.m.init ρ M ${boundIx})
43
+ rw [h0]
44
+ apply Eq.symm
45
+ exact zeroSum _ _ (by intro j; simp [countCell, hMap])`;
46
+ return `import FiniteFold
47
+ import Ghost
48
+ open Kern FiniteFold
49
+ set_option maxRecDepth 30000
50
+ set_option maxHeartbeats 0
51
+ set_option linter.unusedSimpArgs false
52
+
53
+ def src : SMachine := ${machineLit(m, t, ix, mx)}
54
+ def original : C := ${t.c(law.holds)}
55
+ def before (ρ ι : Nat → Nat) : Nat → Nat := withInputs src.f.m.inputs ρ ι
56
+ def point (X : Nat → Nat) (M : Nat → Nat → Nat) := evalE X M (${t.e(point)})
57
+ def countCell (tag : Nat) (M : Nat → Nat → Nat) (j : Nat) : Nat := if M 0 ${addr('j')} = tag then 1 else 0
58
+
59
+ def Coupled (ρ : Nat → Nat) (M : Nat → Nat → Nat) : Prop :=
60
+ ${p.fields.map(f => `(ρ ${ix(f.field)} = sumBelow (countCell ${f.value} M) (ρ ${boundIx}))`).join(' ∧ ')}
61
+
62
+ theorem zeroSum (f : Nat → Nat) (N : Nat) (h : ∀ j, f j = 0) : sumBelow f N = 0 := by
63
+ rw [← sumBelow_zero_fn N]
64
+ exact sumBelow_congr N (fun j _ => h j)
65
+
66
+ theorem view_eq ${stepvars} :
67
+ sView src ρ M ι κ = (decideFlags src.f.flags ${prev} M, M) := by
68
+ have hm : withCarried src M κ = M := by funext i j; rfl
69
+ have hv : decideQ src ${prev} M = ${prev} := by funext i; simp [decideQ_of, src, lookup]
70
+ simp only [sView, hm]
71
+ change (decideFlags src.f.flags (decideQ src (before ρ ι) M) M, M) = _
72
+ rw [hv]
73
+
74
+ theorem assume_eq ${stepvars}
75
+ (h : evalC (sView src ρ M ι κ).1 (sView src ρ M ι κ).2 src.f.m.assume = true) :
76
+ holdsC ${prev} M (${t.c(locals[0].assumptions[0])}) := by
77
+ rw [view_eq] at h
78
+ simpa [${sem}] using h
79
+
80
+ theorem bound_next ${stepvars} : ${next}.1 ${boundIx} = ρ ${boundIx} := by
81
+ simp only [sNext, view_eq, Prod.fst, Prod.snd]
82
+ simp [${sem}]
83
+
84
+ theorem bound_before (ρ ι : Nat → Nat) : ${prev} ${boundIx} = ρ ${boundIx} := by rfl
85
+ ${certs}
86
+
87
+ theorem coupled_init (ρ : Nat → Nat) (M : Nat → Nat → Nat) (hm : StartMaps src.f.m M) :
88
+ Coupled (applyS src.f.m.init ρ M) M := by
89
+ have hMap (j : Nat) : M 0 j = ${m.maps[p.map]} := hm (0,${m.maps[p.map]}) (by simp [src]) j
90
+ unfold Coupled
91
+ refine ⟨${p.fields.map(() => '?_').join(', ')}⟩
92
+ ${p.fields.map(bindStep).join('')}
93
+
94
+ theorem coupled_next ${stepvars}
95
+ (hold : Coupled ρ M) (adm : evalC (sView src ρ M ι κ).1 (sView src ρ M ι κ).2 src.f.m.assume = true) :
96
+ Coupled ${next}.1 ${next}.2 := by
97
+ let X := before ρ ι
98
+ let N := ρ ${boundIx}
99
+ let q := point X M
100
+ let ρ' := ${next}.1
101
+ let M' := ${next}.2
102
+ have hn : ρ' ${boundIx} = N := bound_next ρ M ι κ
103
+ have hb : X ${boundIx} = N := bound_before ρ ι
104
+ have ha := assume_eq ρ M ι κ adm
105
+ have hq : q < N := by simpa only [q, point, holdsC, evalE, hb] using checked_point_inside X M ha
106
+ have haAt (j : Nat) : holdsC ${shift('j')} M (${t.c(locals[1].assumptions[0])}) := by
107
+ simpa [holdsC, evalE, upd] using ha
108
+ have hqAt (j : Nat) : point ${shift('j')} M = q := by simp [point, evalE, upd, q]
109
+ obtain ⟨${p.fields.map((_, i) => `hold${i}`).join(', ')}⟩ := hold
110
+ change Coupled ρ' M'
111
+ unfold Coupled
112
+ rw [hn]
113
+ by_cases hr : holdsC X M (${t.c(p.reset)})
114
+ · have hrAt (j : Nat) : holdsC ${shift('j')} M (${t.c(p.reset)}) := by simpa [holdsC, evalE, upd] using hr
115
+ have resetMap (j : Nat) : M' 0 ${addr('j')} = ${m.maps[p.map]} := by
116
+ have v := checked_broadcast_reset ${shift('j')} M (haAt j) (hrAt j)
117
+ simp only [M', sNext, view_eq, Prod.fst, Prod.snd]
118
+ simpa [X, ${sem}] using v
119
+ refine ⟨${p.fields.map(() => '?_').join(', ')}⟩
120
+ ${p.fields.map((f, i) => ` · have hz : ρ' ${ix(f.field)} = 0 := by
121
+ simp only [ρ', sNext, view_eq, Prod.fst, Prod.snd]
122
+ simpa [X, ${sem}] using checked_field${i}_reset X M ha hr
123
+ rw [hz]
124
+ apply Eq.symm
125
+ exact zeroSum _ _ (by intro j; simp [countCell, resetMap])`).join('\n')}
126
+ · have hrAt (j : Nat) : ¬holdsC ${shift('j')} M (${t.c(p.reset)}) := by simpa [holdsC, evalE, upd] using hr
127
+ have frameMap (j : Nat) (hne : j ≠ q) : M' 0 ${addr('j')} = M 0 ${addr('j')} := by
128
+ have hneq : holdsC ${shift('j')} M (${t.c(locals[1].assumptions[2])}) := by
129
+ change (j ≠ point ${shift('j')} M)
130
+ rwa [hqAt]
131
+ have v := checked_other_cells_frame ${shift('j')} M (haAt j) (hrAt j) hneq
132
+ simp only [M', sNext, view_eq, Prod.fst, Prod.snd]
133
+ simpa [X, ${sem}] using v
134
+ refine ⟨${p.fields.map(() => '?_').join(', ')}⟩
135
+ ${p.fields.map((f, i) => ` · have delta : ρ' ${ix(f.field)} + countCell ${f.value} M q = ρ ${ix(f.field)} + countCell ${f.value} M' q := by
136
+ simp only [ρ', M', countCell, sNext, view_eq, Prod.fst, Prod.snd]
137
+ simpa [q, point, X, ${sem}] using checked_field${i}_delta X M ha hr
138
+ exact coupled_change _ _ _ _ _ _ hq (by intro j _ hne; simp [countCell, frameMap j hne]) hold${i} delta`).join('\n')}
139
+
140
+ theorem all_coupled {ρ M} (h : SReach src ρ M) : Coupled ρ M := by
141
+ induction h with
142
+ | start ρ M hm _ _ _ => exact coupled_init ρ M hm
143
+ | step ρ M ι κ _ adm ih => exact coupled_next ρ M ι κ ih adm
144
+
145
+ theorem original_law {ρ M} (h : SReach src ρ M) : holdsC ρ M original := by
146
+ obtain ⟨${p.fields.map((_, i) => `hold${i}`).join(', ')}⟩ := all_coupled h
147
+ apply checked_capacity_entails_claim
148
+ change ${cap} ≤ ρ ${boundIx}
149
+ rw [${p.fields.map((_, i) => `hold${i}`).join(', ')}]
150
+ rw [${p.fields.slice(1).map(() => '← sumBelow_add').join(', ')}]
151
+ calc
152
+ _ ≤ sumBelow (fun _ => 1) (ρ ${boundIx}) := by
153
+ apply sumBelow_mono
154
+ intro j _
155
+ have v := checked_disjoint_capacity (upd ρ ${ix(coordinate)} j) M
156
+ change ${classBody('M')} ≤ 1
157
+ simpa [countCell, holdsC, evalE, evalC, upd] using v
158
+ _ = ρ ${boundIx} := by simp [sumBelow_const]
159
+
160
+ theorem aggregate_claim : ∀ ρ M, SReach src ρ M → holdsC ρ M original :=
161
+ fun _ _ h => original_law h
162
+ `;
163
+ }
@@ -0,0 +1,2 @@
1
+ import type { Law, Machine } from '../../core/machine.js';
2
+ export declare function admitAggregateSource(machine: Machine, law: Law): string;