gdp-wired 0.52.0 → 0.53.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.
@@ -777,6 +777,50 @@ function unchanged(t, map, env, st, m) {
777
777
  const zeroOne = () => [...(st.maps[map]?.values() ?? [])].every(x => x === 0 || x === 1) && (st.defaults?.[map] ?? m.maps[map]) <= 1;
778
778
  return v.op === 'if' && v.then.op === 'const' && v.then.value === 1 && v.else.op === 'const' && v.else.value === 0 && v.c.op === '<=' && v.c.a.op === 'const' && v.c.a.value === 1 && own(v.c.b) && zeroOne();
779
779
  }
780
+ // Exact value of a declared map sum directly from a state's maps and defaults (independent of sumRuntime's finite-cover
781
+ // delta). Throws RangeError when the sum's term is non-zero past the stored cells (an infinite sum over all naturals).
782
+ export function exactMapSum(m, name, sum, st) {
783
+ const read = mapsIn(sum.term);
784
+ for (const mp of read)
785
+ if (st.defaults?.[mp] === undefined && m.maps?.[mp] === undefined)
786
+ throw new RangeError(`${m.name}: map ${mp} is not declared on the machine`);
787
+ const dfltState = { scalars: {}, maps: Object.fromEntries(read.map(mp => [mp, new Map()])), ...(st.defaults ? { defaults: st.defaults } : {}) };
788
+ const d = evalE(sum.term, { [sum.key]: 0 }, dfltState, m);
789
+ if (d !== 0)
790
+ throw new RangeError(`${m.name}: the sum ${name} is infinite (its term is ${d} past the stored cells)`);
791
+ if (!read.length)
792
+ return 0;
793
+ let total = 0;
794
+ const env = { [sum.key]: 0 };
795
+ if (read.length === 1) {
796
+ const cells = st.maps[read[0]];
797
+ if (cells)
798
+ for (const key of cells.keys()) {
799
+ env[sum.key] = key;
800
+ total = exact(total + evalE(sum.term, env, st, m));
801
+ }
802
+ return total;
803
+ }
804
+ const keys = new Set();
805
+ for (const mp of read)
806
+ for (const key of st.maps[mp]?.keys() ?? [])
807
+ keys.add(key);
808
+ for (const key of keys) {
809
+ env[sum.key] = key;
810
+ total = exact(total + evalE(sum.term, env, st, m));
811
+ }
812
+ return total;
813
+ }
814
+ // Sums whose term reads at least one map written at every key (`each`): sumRuntime's finite-cover delta is only valid
815
+ // when the write's cover goal holds, so the runtimes recompute these sums directly from the post-step maps instead.
816
+ function recomputedSums(m) {
817
+ const out = new Set();
818
+ for (const [name, sum] of Object.entries(m.sums ?? {})) {
819
+ if (mapsIn(sum.term).some(mp => { const w = m.step.maps?.[mp]; return !!w && 'each' in w; }))
820
+ out.add(name);
821
+ }
822
+ return out;
823
+ }
780
824
  // The machine a runtime steps (with a history, kernel.ts's plain machine), its queries, and the inputs a request carries.
781
825
  function runnable(m) {
782
826
  const h = m.history;
@@ -870,7 +914,7 @@ export const numbersOf = (input) => Object.fromEntries(Object.entries(input).fil
870
914
  const refused = (m) => `${m.name}: the request fails the rule's assumption, so no proof covers the step it would take`;
871
915
  // The interpreter: persistent (a step leaves the state it was given as it was), so searches can branch from any state.
872
916
  export function interpret(m, checkpoint) {
873
- const { h, plain, carried } = runnable(m), arity = mapArities(plain);
917
+ const { h, plain, carried } = runnable(m), arity = mapArities(plain), recompute = recomputedSums(m);
874
918
  const args = (params, input) => {
875
919
  const env = {};
876
920
  for (const p of m.params)
@@ -948,7 +992,8 @@ export function interpret(m, checkpoint) {
948
992
  }
949
993
  const scalars = { ...st.scalars };
950
994
  for (const [name, e] of Object.entries(plain.step.state ?? {}))
951
- scalars[name] = evalE(e, env, st, plain);
995
+ if (!recompute.has(name))
996
+ scalars[name] = evalE(e, env, st, plain);
952
997
  const writes = Object.entries(plain.step.maps ?? {}).map(([name, w]) => [name, 'each' in w ? writeEvery(w, env, st, plain, arity[name] ?? 1, name) : { key: evalE(w.key, env, st, plain), value: evalE(w.value, env, st, plain) }]);
953
998
  const maps = Object.fromEntries(Object.entries(given.maps).map(([name, cells]) => [name, new Map(cells)]));
954
999
  const defaults = { ...given.defaults };
@@ -960,6 +1005,11 @@ export function interpret(m, checkpoint) {
960
1005
  else
961
1006
  maps[name].set(w.key, w.value);
962
1007
  const withDefaults = Object.keys(defaults).length ? { defaults } : {};
1008
+ if (recompute.size) {
1009
+ const post = { scalars, maps, ...withDefaults };
1010
+ for (const name of recompute)
1011
+ scalars[name] = exactMapSum(m, name, m.sums[name], post);
1012
+ }
963
1013
  if (!h)
964
1014
  return { scalars, maps, ...withDefaults };
965
1015
  const kept = evalC(h.keep, env, st, plain);
@@ -1030,7 +1080,7 @@ export function compileJs(m) { return compileJsMode(m, false); }
1030
1080
  // fastStep keeps the input state persistent. Its fork can wait until every
1031
1081
  // precondition and right-hand side has been evaluated, just before the writes.
1032
1082
  function compileJsMode(m, persistent, cells) {
1033
- const { h, plain, queries, carried } = runnable(m);
1083
+ const { h, plain, queries, carried } = runnable(m), recompute = recomputedSums(m);
1034
1084
  // (a condition or a write at every key over a tuple key: the interpreter decides those, part by part)
1035
1085
  const atEvery = [...Object.values(plain.step.flags ?? {}).filter(c => c.op === 'all' && c.finite === undefined), ...Object.values(plain.step.maps ?? {}).filter(w => 'each' in w)];
1036
1086
  const arity = mapArities(plain);
@@ -1157,14 +1207,56 @@ function compileJsMode(m, persistent, cells) {
1157
1207
  const better = l.by.map((b, i) => `by[${i}] !== bb[${i}] ? by[${i}] ${b.desc ? '>' : '<'} bb[${i}] : `).join('') + 'false';
1158
1208
  lines.push(`{ const ks = $keys(maps, ${JSON.stringify(ms)}), past = ks.pop(); let lk = past; if (${where}) throw new RangeError(${id(`${m.name}: ${name} has no least (its condition holds at every key past the cells)`)}); let bk, bb; for (lk of ks.sort((a, b) => a - b)) { if (!(${where})) continue; const by = [${by.join(', ')}]; if (bk === undefined || (${better})) { bk = lk; bb = by; } } env[${id(name)}] = bk ?? 0; env[${id(l.some)}] = bk === undefined ? 0 : 1; }`);
1159
1209
  }
1210
+ const sumEx = (e, keyVar) => {
1211
+ switch (e.op) {
1212
+ case 'const': return String(e.value);
1213
+ case 'add': return `$x(${sumEx(e.a, keyVar)} + ${sumEx(e.b, keyVar)})`;
1214
+ case 'sub': return `Math.max(0, ${sumEx(e.a, keyVar)} - ${sumEx(e.b, keyVar)})`;
1215
+ case 'mul': return `$x(${e.k} * ${sumEx(e.a, keyVar)})`;
1216
+ case 'prod': return `$x(${sumEx(e.a, keyVar)} * ${sumEx(e.b, keyVar)})`;
1217
+ case 'min': return `Math.min(${sumEx(e.a, keyVar)}, ${sumEx(e.b, keyVar)})`;
1218
+ case 'max': return `Math.max(${sumEx(e.a, keyVar)}, ${sumEx(e.b, keyVar)})`;
1219
+ case 'if': return `(${sumCx(e.c, keyVar)} ? ${sumEx(e.then, keyVar)} : ${sumEx(e.else, keyVar)})`;
1220
+ case 'get': return keyVar ? `(state.maps[${id(e.map)}].get(${keyVar}) ?? dft[${id(e.map)}] ?? ${plain.maps[e.map]})` : `(dft[${id(e.map)}] ?? ${plain.maps[e.map]})`;
1221
+ case 'var':
1222
+ case 'tup':
1223
+ case 'proj': throw new Error(`${m.name}: unexpected expression ${e.op} in sum term`);
1224
+ }
1225
+ };
1226
+ const sumCx = (c, keyVar) => {
1227
+ switch (c.op) {
1228
+ case '<': return `(${sumEx(c.a, keyVar)} < ${sumEx(c.b, keyVar)})`;
1229
+ case '<=': return `(${sumEx(c.a, keyVar)} <= ${sumEx(c.b, keyVar)})`;
1230
+ case '=': return `(${sumEx(c.a, keyVar)} === ${sumEx(c.b, keyVar)})`;
1231
+ case 'and': return c.xs.length ? `(${c.xs.map(y => sumCx(y, keyVar)).join(' && ')})` : 'true';
1232
+ case 'or': return c.xs.length ? `(${c.xs.map(y => sumCx(y, keyVar)).join(' || ')})` : 'false';
1233
+ case 'not': return `(!${sumCx(c.x, keyVar)})`;
1234
+ case 'flag':
1235
+ case 'all': throw new Error(`${m.name}: unexpected condition ${c.op} in sum term`);
1236
+ }
1237
+ };
1238
+ const stepScalars = Object.entries(plain.step.state ?? {}).filter(([name]) => !recompute.has(name));
1160
1239
  lines.push(...flags.map((name, i) => `const flag${i} = ${cx(plain.step.flags[name])};`),
1161
1240
  // The rule's own assumption, as `allowed` (core/watch.ts) reads it (a history's machine assumes more: its relations).
1162
- ...(m.assume ? [`if (!${cx(m.assume)}) throw new RangeError(${id(refused(m))});`] : []), ...(plain.primitiveFailure ? [`if (${cx(plain.primitiveFailure)}) { const e = new RangeError(${id(`${m.name}: fixed-width primitive failed`)}); e.name = "PrimitiveFailure"; throw e; }`] : []), `const scalars = {...s, ${Object.entries(plain.step.state ?? {}).map(([name, e]) => `${id(name)}: ${ex(e)}`).join(', ')}};`, ...[...sharedBreaks].map(([text, bk]) => `const ${bk} = ${breaksJs(JSON.parse(text))};`), ...writes.map(([name, w], i) => ('each' in w ? `const write${i} = ${every(w, sharedOf(name))};` : `const key${i} = ${ex(w.key)}, value${i} = ${ex(w.value)};`)));
1241
+ ...(m.assume ? [`if (!${cx(m.assume)}) throw new RangeError(${id(refused(m))});`] : []), ...(plain.primitiveFailure ? [`if (${cx(plain.primitiveFailure)}) { const e = new RangeError(${id(`${m.name}: fixed-width primitive failed`)}); e.name = "PrimitiveFailure"; throw e; }`] : []), `const scalars = {${['...s', ...stepScalars.map(([name, e]) => `${id(name)}: ${ex(e)}`)].join(', ')}};`, ...[...sharedBreaks].map(([text, bk]) => `const ${bk} = ${breaksJs(JSON.parse(text))};`), ...writes.map(([name, w], i) => ('each' in w ? `const write${i} = ${every(w, sharedOf(name))};` : `const key${i} = ${ex(w.key)}, value${i} = ${ex(w.value)};`)));
1163
1242
  if (h)
1164
1243
  lines.push(`const keep = ${cx(h.keep)};`);
1165
1244
  if (persistent)
1166
1245
  lines.push('state = fork(state);');
1167
1246
  lines.push(...writes.map(([name, w], i) => ('each' in w ? `state.maps[${id(name)}] = write${i}.cells; dft[${id(name)}] = write${i}.d;` : `state.maps[${id(name)}].set(key${i}, value${i});`)));
1247
+ for (const name of recompute) {
1248
+ const sum = m.sums[name], read = mapsIn(sum.term), dfltExpr = sumEx(sum.term), atKeyExpr = sumEx(sum.term, '$k');
1249
+ const errMsg = id(`${m.name}: the sum ${name} is infinite (its term is `);
1250
+ if (!read.length) {
1251
+ lines.push(`{ const $d = ${dfltExpr}; if ($d !== 0) throw new RangeError(${errMsg} + $d + " past the stored cells)"); scalars[${id(name)}] = 0; }`);
1252
+ }
1253
+ else if (read.length === 1) {
1254
+ lines.push(`{ const $d = ${dfltExpr}; if ($d !== 0) throw new RangeError(${errMsg} + $d + " past the stored cells)"); let $sum = 0; for (const $k of state.maps[${id(read[0])}].keys()) $sum = $x($sum + ${atKeyExpr}); scalars[${id(name)}] = $sum; }`);
1255
+ }
1256
+ else {
1257
+ lines.push(`{ const $d = ${dfltExpr}; if ($d !== 0) throw new RangeError(${errMsg} + $d + " past the stored cells)"); const $ks = new Set(); ${read.map(mp => `for (const $k of state.maps[${id(mp)}].keys()) $ks.add($k);`).join(' ')} let $sum = 0; for (const $k of $ks) $sum = $x($sum + ${atKeyExpr}); scalars[${id(name)}] = $sum; }`);
1258
+ }
1259
+ }
1168
1260
  if (h)
1169
1261
  lines.push(`if (keep) records.push({${h.record.map(f => `${id(f)}: env[${id(f)}]`).join(', ')}});`,
1170
1262
  // Drop the spent prefix now and then, not every step: amortized, each record is moved a bounded number of times.
@@ -1,7 +1,16 @@
1
- import type { Machine, Law } from './machine.js';
1
+ import type { E, Machine, Law } from './machine.js';
2
+ import type { AggregateCertificate } from './aggregate-search.js';
3
+ import type { AggregateKinds } from './aggregate-kinds.js';
2
4
  import type { Instances, Liveness, StepLaw, Tree } from '../kernel/kernel.js';
3
5
  import type { proveLaws, proveLiveness, proveProgress, proveStepLaws } from '../kernel/prove.js';
4
6
  export type ProofOutputNode = {
7
+ kind: 'aggregate';
8
+ machine: Machine;
9
+ law: Law;
10
+ certificate: AggregateCertificate;
11
+ kinds?: AggregateKinds;
12
+ terms: E[];
13
+ } | {
5
14
  kind: 'counted';
6
15
  machine: Machine;
7
16
  laws: Law[];
@@ -85,6 +94,7 @@ export declare function retainCounted<T extends object>(result: T, family: {
85
94
  certs: Record<string, import('../kernel/kernel.ts').CountCert>;
86
95
  };
87
96
  }): T;
97
+ export declare function retainAggregate<T extends object>(result: T, machine: Machine, law: Law, certificate: AggregateCertificate, kinds?: AggregateKinds): T;
88
98
  export declare function retainFrom<T extends object>(result: T, parents: object[], context?: unknown): T;
89
99
  export declare function publishProof<T extends object>(result: T, machine: Machine, laws: Law[]): T;
90
100
  export {};
@@ -1,3 +1,4 @@
1
+ import { snapshotKernelTermState } from "../kernel/kernel.js";
1
2
  // Synchronous public rule invocations can recursively prove a Skolem family.
2
3
  let publicRuleDepth = 0;
3
4
  export function withPublicRule(run) {
@@ -65,6 +66,11 @@ export function retainCounted(result, family) {
65
66
  records.set(result, { kind: 'counted', machine: family.m, laws: family.laws, proof: family.proof });
66
67
  return result;
67
68
  }
69
+ export function retainAggregate(result, machine, law, certificate, kinds) {
70
+ if (proofOutput.on)
71
+ records.set(result, { kind: 'aggregate', machine, law, certificate, ...(kinds ? { kinds } : {}), terms: snapshotKernelTermState().terms });
72
+ return result;
73
+ }
68
74
  export function retainFrom(result, parents, context = { kind: 'projection' }) {
69
75
  if (proofOutput.on)
70
76
  records.set(result, { kind: 'derived', parents: parents.map(parent => records.get(parent)), context });
@@ -0,0 +1,31 @@
1
+ import { type C, type E, type Law, type Machine } from '../core/machine.js';
2
+ import { type Goal, type Tree } from './kernel.js';
3
+ export type FiniteSumLayout = {
4
+ map: string;
5
+ bound: string;
6
+ key: string;
7
+ offset: number;
8
+ fields: {
9
+ field: string;
10
+ value: number;
11
+ }[];
12
+ };
13
+ export type FiniteSumCertificate = {
14
+ kind: 'finite-sum';
15
+ layout: FiniteSumLayout;
16
+ trees: Record<string, Tree>;
17
+ };
18
+ export type SumLocal = {
19
+ name: string;
20
+ assumptions: C[];
21
+ conclusion: C;
22
+ };
23
+ export declare const sumLocalGoal: (l: SumLocal) => Goal;
24
+ export declare function finiteSumTheory(m: Machine, law: Law, p: FiniteSumLayout): {
25
+ locals: SumLocal[];
26
+ coordinate: string;
27
+ point: E;
28
+ bound: E;
29
+ reset: C;
30
+ } | undefined;
31
+ export declare function checkFiniteSum(m: Machine, law: Law, p: FiniteSumCertificate): boolean;
@@ -0,0 +1,74 @@
1
+ // Lean twin: FiniteSumComposition.state_law, restricted to a symbolic prefix,
2
+ // one touched site or a zero-row rebuild, and unit site capacity.
3
+ import { atMost, get, n, not, plus, same, walkOnce, x } from "../core/machine.js";
4
+ import { check, mapArities, obligations, own, substC, substE } from "./kernel.js";
5
+ export const sumLocalGoal = (l) => ({ name: l.name, hyps: [...l.assumptions, not(l.conclusion)] });
6
+ const zero = n(0);
7
+ const safeNat = (x) => typeof x === 'number' && Number.isSafeInteger(x) && x >= 0;
8
+ // The caller supplies the source and claim, not the packet. Only site/field
9
+ // coordinates are proposals. Build the obligations over actual source terms.
10
+ export function finiteSumTheory(m, law, p) {
11
+ const maps = m.maps ?? {}, writes = m.step.maps ?? {}, defaultCell = own(maps, p.map), wr = own(writes, p.map);
12
+ if (m.history || m.primitiveFailure || Object.keys(m.sums ?? {}).length || Object.keys(m.counts ?? {}).length ||
13
+ Object.keys(m.fns ?? {}).length || m.facts?.length || m.inputMaps?.length || m.leasts && Object.keys(m.leasts).length ||
14
+ law.forall !== undefined || law.keys?.length || law.some?.length || law.ex || law.finite !== undefined ||
15
+ !m.assume || Object.keys(maps).length !== 1 || Object.keys(writes).length !== 1 || !safeNat(defaultCell) ||
16
+ !wr || !('each' in wr) || wr.value.op !== 'if' ||
17
+ !m.params.includes(p.bound) || !m.inputs.includes(p.key) || !safeNat(p.offset) || !Array.isArray(p.fields) || !p.fields.length)
18
+ return;
19
+ if (new Set(p.fields.map(f => f.field)).size !== p.fields.length ||
20
+ !p.fields.every(f => safeNat(f.value) && f.value !== defaultCell && own(m.state, f.field) && own(m.step.state ?? {}, f.field)))
21
+ return;
22
+ let unsupported = false;
23
+ walkOnce([m, law.holds], o => {
24
+ const t = o;
25
+ if (t.op === 'all' || t.op === 'get' && t.map?.startsWith('worddiv$') || t.op === 'const' && !safeNat(t.value) || t.op === 'mul' && !safeNat(t.k))
26
+ unsupported = true;
27
+ });
28
+ if (unsupported || (own(mapArities(m, [law]), p.map) ?? 1) !== 1)
29
+ return;
30
+ // Existing scope/natural checks establish disjoint params, inputs, state,
31
+ // flags and source binders. In particular, no step can assign the bound.
32
+ obligations(m, [law]);
33
+ let coordinate = 'agg$coordinate';
34
+ const occupied = JSON.stringify([m, law]);
35
+ while (occupied.includes(coordinate))
36
+ coordinate += '0';
37
+ const flags = Object.create(null);
38
+ for (const [name, c] of Object.entries(m.step.flags ?? {}))
39
+ flags[name] = substC(c, { vars: {}, maps: {}, flags });
40
+ const inline = { vars: {}, maps: {}, flags }, step = m.step.state ?? {};
41
+ const assume = substC(m.assume, inline), bound = x(p.bound), input = x(p.key), j = x(coordinate);
42
+ const point = p.offset ? { op: 'sub', a: input, b: n(p.offset) } : input;
43
+ const addr = (k) => p.offset ? plus(k, n(p.offset)) : k;
44
+ const after = (k) => substE(wr.value, { ...inline, vars: { [wr.each]: k } });
45
+ const reset = substC(wr.value.c, { ...inline, vars: { [wr.each]: input } }), coord = addr(j), atPoint = addr(point);
46
+ const local = (name, assumptions, conclusion) => ({ name, assumptions, conclusion });
47
+ const locals = [
48
+ local('point_inside', [assume], { op: '<', a: point, b: bound }),
49
+ local('other_cells_frame', [assume, not(reset), not(same(j, point))], same(after(coord), get(p.map, coord))),
50
+ local('broadcast_reset', [assume, reset], same(after(coord), n(defaultCell))),
51
+ local('capacity_entails_claim', [atMost(p.fields.map(f => x(f.field)).reduce(plus), bound)], law.holds),
52
+ ];
53
+ const indicator = (value, cell) => ({ op: 'if', c: same(cell, n(value)), then: n(1), else: zero });
54
+ for (const [i, f] of p.fields.entries()) {
55
+ const next = substE(own(step, f.field), inline);
56
+ locals.push(local(`field${i}_init`, [], same(own(m.state, f.field), zero)), local(`field${i}_reset`, [assume, reset], same(next, zero)), local(`field${i}_delta`, [assume, not(reset)], same(plus(next, indicator(f.value, get(p.map, atPoint))), plus(x(f.field), indicator(f.value, after(atPoint))))));
57
+ }
58
+ locals.push(local('disjoint_capacity', [], atMost(p.fields.map(f => indicator(f.value, get(p.map, coord))).reduce(plus), n(1))));
59
+ return { locals, coordinate, point, bound, reset };
60
+ }
61
+ export function checkFiniteSum(m, law, p) {
62
+ try {
63
+ if (p.kind !== 'finite-sum')
64
+ return false;
65
+ const theory = finiteSumTheory(m, law, p.layout);
66
+ return !!theory && Object.keys(p.trees).length === theory.locals.length && theory.locals.every(local => {
67
+ const tree = own(p.trees, local.name);
68
+ return !!tree && check(sumLocalGoal(local), tree);
69
+ });
70
+ }
71
+ catch {
72
+ return false;
73
+ }
74
+ }
@@ -0,0 +1,117 @@
1
+ import { type C, type E, type Law, type Machine } from '../core/machine.js';
2
+ import { type Instances, type Tree } from './kernel.js';
3
+ export type GhostWriteRecipe = {
4
+ ghostMap: string;
5
+ point: E;
6
+ gates: [column: string, value: number][];
7
+ group: string;
8
+ weight: string;
9
+ observer: string;
10
+ };
11
+ export type GhostWriteCertificate = {
12
+ kind: 'ghost-write';
13
+ recipe: GhostWriteRecipe;
14
+ projection: {
15
+ omitMap: string;
16
+ };
17
+ target: Machine;
18
+ laws: Law[];
19
+ pointLaw: string;
20
+ proof: {
21
+ instances: Record<string, Instances>;
22
+ trees: Record<string, Tree>;
23
+ };
24
+ };
25
+ export declare function ghostWriteTheory(source: Machine, law: Law, p: GhostWriteCertificate): {
26
+ orig: {
27
+ params: string[];
28
+ step: {
29
+ flags: Record<string, C>;
30
+ state?: Record<string, E>;
31
+ maps?: Record<string, import("../core/machine.ts").MapUpdate>;
32
+ };
33
+ primitiveFailure?: C;
34
+ name: string;
35
+ inputs: string[];
36
+ state: Record<string, E>;
37
+ maps?: Record<string, number>;
38
+ inputMaps?: string[];
39
+ pre?: C;
40
+ assume?: C;
41
+ history?: import("../core/machine.ts").History;
42
+ sums?: Record<string, import("../core/machine.ts").Sum>;
43
+ counts?: Record<string, import("../core/machine.ts").Counted>;
44
+ fns?: Record<string, import("../core/machine.ts").Fn>;
45
+ facts?: Law[];
46
+ leasts?: Record<string, import("../core/machine.ts").Least>;
47
+ relations?: Record<string, string[]>;
48
+ };
49
+ lift: {
50
+ orig: {
51
+ params: string[];
52
+ step: {
53
+ flags: Record<string, C>;
54
+ state?: Record<string, E>;
55
+ maps?: Record<string, import("../core/machine.ts").MapUpdate>;
56
+ };
57
+ primitiveFailure?: C;
58
+ name: string;
59
+ inputs: string[];
60
+ state: Record<string, E>;
61
+ maps?: Record<string, number>;
62
+ inputMaps?: string[];
63
+ pre?: C;
64
+ assume?: C;
65
+ history?: import("../core/machine.ts").History;
66
+ sums?: Record<string, import("../core/machine.ts").Sum>;
67
+ counts?: Record<string, import("../core/machine.ts").Counted>;
68
+ fns?: Record<string, import("../core/machine.ts").Fn>;
69
+ facts?: Law[];
70
+ leasts?: Record<string, import("../core/machine.ts").Least>;
71
+ relations?: Record<string, string[]>;
72
+ };
73
+ vars: {};
74
+ maps: {
75
+ [x: string]: {
76
+ start: number;
77
+ write: {
78
+ key: E;
79
+ value: E;
80
+ };
81
+ };
82
+ };
83
+ };
84
+ target: {
85
+ state: {
86
+ [x: string]: E;
87
+ };
88
+ sums: {
89
+ [x: string]: {
90
+ term: E;
91
+ key: string;
92
+ };
93
+ };
94
+ primitiveFailure?: C;
95
+ name: string;
96
+ params: string[];
97
+ inputs: string[];
98
+ maps?: Record<string, number>;
99
+ inputMaps?: string[];
100
+ step: {
101
+ flags?: Record<string, C>;
102
+ state?: Record<string, E>;
103
+ maps?: Record<string, import("../core/machine.ts").MapUpdate>;
104
+ };
105
+ pre?: C;
106
+ assume?: C;
107
+ history?: import("../core/machine.ts").History;
108
+ counts?: Record<string, import("../core/machine.ts").Counted>;
109
+ fns?: Record<string, import("../core/machine.ts").Fn>;
110
+ facts?: Law[];
111
+ leasts?: Record<string, import("../core/machine.ts").Least>;
112
+ relations?: Record<string, string[]>;
113
+ };
114
+ laws: Law[];
115
+ publicEntry: number;
116
+ } | undefined;
117
+ export declare function checkGhostWrite(source: Machine, law: Law, p: GhostWriteCertificate): boolean;
@@ -0,0 +1,89 @@
1
+ // Lean twin: GhostWriteTransport.checkedTransport, using the complete original
2
+ // post-row functional. Closed flags and a fresh observer are just views.
3
+ import { get, n, same, walkOnce, x } from "../core/machine.js";
4
+ import { checkLaws, ghostedMachine, ghostedOk, mapArities, obligations, own, sideGoals, substC } from "./kernel.js";
5
+ const text = (x) => JSON.stringify(x);
6
+ const eq = (a, b) => text(a) === text(b);
7
+ const safeNat = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
8
+ const noSub = { vars: {}, maps: {}, flags: {} };
9
+ export function ghostWriteTheory(source, law, p) {
10
+ const r = p.recipe, ghost = r.ghostMap;
11
+ if (p.kind !== 'ghost-write' || Object.keys(p.projection).length !== 1 || p.projection.omitMap !== ghost ||
12
+ !law.forall || law.keys?.length || law.some?.length || law.ex || law.finite !== undefined ||
13
+ source.history || source.primitiveFailure || Object.keys(source.counts ?? {}).length || Object.keys(source.sums ?? {}).length ||
14
+ Object.keys(source.fns ?? {}).length || source.facts?.length || source.inputMaps?.length || Object.keys(source.leasts ?? {}).length)
15
+ return;
16
+ const sums = Object.entries(p.target.sums ?? {});
17
+ if (sums.length !== 1)
18
+ return;
19
+ const [sum, sd] = sums[0], used = text([source, law]);
20
+ const fresh = [r.observer, ghost, sum, sd.key];
21
+ if (new Set(fresh).size !== fresh.length || fresh.some(key => !key || used.includes(text(key))) ||
22
+ !eq(sd, { term: get(ghost, x(sd.key)), key: sd.key }))
23
+ return;
24
+ let unsupported = false;
25
+ walkOnce([source, law.holds, r.point], o => {
26
+ const t = o;
27
+ if (t.op === 'all' || t.op === 'get' && t.map?.startsWith('worddiv$') || t.op === 'const' && !safeNat(t.value) || t.op === 'mul' && !safeNat(t.k))
28
+ unsupported = true;
29
+ });
30
+ if (unsupported)
31
+ return;
32
+ obligations(source, [law]);
33
+ if (!Object.values(source.maps ?? {}).every(safeNat) || Object.values(mapArities(source, [law])).some(n => n !== 1))
34
+ return;
35
+ const written = (name) => { const w = own(source.step.maps ?? {}, name); return w && !('each' in w) ? w : undefined; };
36
+ if (!r.gates.length || !r.gates.every(([map, val]) => safeNat(val) && !!written(map)) || !written(r.group) || !written(r.weight) ||
37
+ !r.gates.some(([map]) => eq(written(map).key, r.point)))
38
+ return;
39
+ const post = (map, key) => {
40
+ const w = written(map);
41
+ return eq(key, w.key) ? w.value :
42
+ { op: 'if', c: same(key, w.key), then: w.value, else: get(map, key) };
43
+ };
44
+ const contribution = (read) => ({ op: 'if',
45
+ c: r.gates.reduceRight((tail, [map, val]) => ({ op: 'and', xs: [same(read(map), n(val)), tail] }), same(read(r.group), x(r.observer))),
46
+ then: read(r.weight), else: n(0) });
47
+ // Match the existing Lean closed-flag view of the same machine. Its dummy
48
+ // binders occur nowhere in the actual body or in the source machine.
49
+ let stem = 'internal$';
50
+ while (text([source, law, fresh]).includes(stem))
51
+ stem += 'a';
52
+ const closed = Object.create(null), inlined = Object.create(null);
53
+ for (const [i, [name, condition]] of Object.entries(source.step.flags ?? {}).entries()) {
54
+ const c = substC(condition, { ...noSub, flags: inlined });
55
+ inlined[name] = c;
56
+ closed[name] = { op: 'all', key: `${stem}${i}`, c };
57
+ }
58
+ const orig = { ...source, params: [...source.params, r.observer], step: { ...source.step, flags: closed } };
59
+ const lift = { orig, vars: {}, maps: { [ghost]: { start: 0, write: { key: r.point, value: contribution(map => post(map, r.point)) } } } };
60
+ if (!ghostedOk(lift))
61
+ return;
62
+ const full = ghostedMachine(lift);
63
+ const target = { ...full, state: { ...full.state, [sum]: n(0) }, sums: { [sum]: { term: get(ghost, x(sd.key)), key: sd.key } } };
64
+ if (!eq(target, p.target))
65
+ return;
66
+ const publicEntry = p.laws.findIndex(l => l.name === law.name), pointEntry = p.laws.findIndex(l => l.name === p.pointLaw);
67
+ if (publicEntry < 0 || pointEntry < 0 || publicEntry === pointEntry)
68
+ return;
69
+ const publicLaw = { name: law.name, holds: substC(law.holds, { ...noSub, vars: { [law.forall]: x(r.observer) } }) };
70
+ const binder = p.laws[pointEntry].forall;
71
+ if (!binder)
72
+ return;
73
+ const rowLaw = { name: p.pointLaw, forall: binder, holds: same(get(ghost, x(binder)), contribution(map => get(map, x(binder)))) };
74
+ if (!eq(publicLaw, p.laws[publicEntry]) || !eq(rowLaw, p.laws[pointEntry]))
75
+ return;
76
+ const laws = p.laws.map((entry, i) => i === publicEntry ? publicLaw : i === pointEntry ? rowLaw : entry);
77
+ if (laws.some(l => l.keys?.length || l.some?.length || l.ex || l.finite !== undefined))
78
+ return;
79
+ return { orig, lift, target, laws, publicEntry };
80
+ }
81
+ export function checkGhostWrite(source, law, p) {
82
+ try {
83
+ const t = ghostWriteTheory(source, law, p);
84
+ return !!t && sideGoals(t.target, t.laws).length === 0 && checkLaws(t.target, t.laws, p.proof);
85
+ }
86
+ catch {
87
+ return false;
88
+ }
89
+ }
@@ -7,6 +7,9 @@ import { type CountCert, type CountDecl, type CountedGoal, type CountInst, type
7
7
  import { proveStepLaws } from '../kernel/prove.js';
8
8
  import { type Cyclic } from '../kernel/cyclic.js';
9
9
  import { leanLibrary } from './library.js';
10
+ import type { FiniteSumCertificate } from '../kernel/finite-sum.js';
11
+ import type { GhostWriteCertificate } from '../kernel/ghost-write.js';
12
+ import type { AggregateKinds } from '../core/aggregate-kinds.js';
10
13
  export { leanLibrary };
11
14
  export type Exported = {
12
15
  name: string;
@@ -338,6 +341,14 @@ export type LeanItem = {
338
341
  k?: number;
339
342
  ms?: number;
340
343
  };
344
+ } | {
345
+ id: string;
346
+ aggregate: {
347
+ source: Machine;
348
+ law: Law;
349
+ certificate: FiniteSumCertificate | GhostWriteCertificate;
350
+ kinds?: AggregateKinds;
351
+ };
341
352
  } | {
342
353
  id: string;
343
354
  countedGoal: CountedGoal;
@@ -18,6 +18,8 @@ import { proveKInduction } from "../core/kind.js";
18
18
  import { quantifiedRenames } from "./qalpha.js";
19
19
  import { countsForReads } from "../core/count-facts.js";
20
20
  import { requireSourceTranslation } from "../core/source-check.js";
21
+ import { finiteSumToLean } from "./finite-sum-export.js";
22
+ import { ghostWriteToLean } from "./ghost-write-export.js";
21
23
  export { leanLibrary };
22
24
  // --- to Lean ------------------------------------------------------------------------------------------------------------
23
25
  const varsOf = (c) => [...JSON.stringify(c).matchAll(/"op":"var","name":"([^"]+)"/g)].map(m => m[1]);
@@ -2553,6 +2555,8 @@ export function toLean(items, opts = {}) {
2553
2555
  requireSourceTranslation(item.machine, [...item.laws, ...(item.stepLaws ?? []), ...(item.liveness ?? [])]);
2554
2556
  else if ('kInduction' in item)
2555
2557
  requireSourceTranslation(item.kInduction.machine, [...item.kInduction.laws, item.kInduction.law]);
2558
+ else if ('aggregate' in item)
2559
+ requireSourceTranslation(item.aggregate.source, [item.aggregate.law]);
2556
2560
  else if ('countedMachine' in item)
2557
2561
  requireSourceTranslation(item.countedMachine, item.laws);
2558
2562
  else if ('refinement' in item) {
@@ -2609,7 +2613,23 @@ function toLeanWith(items, opts) {
2609
2613
  }).join('');
2610
2614
  for (let item of items) {
2611
2615
  const id = ident(item.id), tItem = performance.now();
2612
- if ('countedGoal' in item) {
2616
+ if ('aggregate' in item) {
2617
+ const { source, law, certificate, kinds } = item.aggregate;
2618
+ if (kinds) {
2619
+ const kindId = `${id}_kinds`;
2620
+ parts.push(retainedSMachineToLean(kindId, source, kinds.laws, kinds.proof));
2621
+ theorems.push(`${kindId}_laws`);
2622
+ }
2623
+ const save = checkBy;
2624
+ checkBy = 'decide +kernel';
2625
+ try {
2626
+ parts.push(certificate.kind === 'finite-sum' ? finiteSumToLean(id, source, law, certificate) : ghostWriteToLean(id, source, law, certificate));
2627
+ }
2628
+ finally {
2629
+ checkBy = save;
2630
+ }
2631
+ }
2632
+ else if ('countedGoal' in item) {
2613
2633
  if (!checkCounted(item.countedGoal, item.certificate))
2614
2634
  throw new Error(`${item.id}: counted certificate does not check`);
2615
2635
  parts.push(countedToLean(id, item.countedGoal, item.certificate));
@@ -2729,8 +2749,10 @@ function toLeanWith(items, opts) {
2729
2749
  console.error(`lean item ${item.id}: ${Math.round(performance.now() - tItem)} ms, ${parts.at(-1)?.length ?? 0} bytes`);
2730
2750
  }
2731
2751
  // The file the items need: Live.lean for a liveness or a loop, Sets.lean (which imports Steps.lean) for any machine.
2752
+ const finiteImport = items.some(item => 'aggregate' in item && item.aggregate.certificate.kind === 'finite-sum') ? 'import FiniteSumComposition\n' : '';
2753
+ const ghostImport = items.some(item => 'aggregate' in item && item.aggregate.certificate.kind === 'ghost-write') ? 'import Sums\nimport GhostWriteTransport\nimport GhostSourceViews\n' : '';
2732
2754
  return `import History
2733
- ${wordReads(items).length ? 'import WordFacts\nimport WordSMachine\n' : ''}${items.some(item => 'countedGoal' in item || 'countedMachine' in item) ? 'import QAlpha\n' : ''}${items.some(item => 'machine' in item && item.machine.sums && Object.keys(item.machine.sums).length) ? 'import Sums\n' : ''}${items.some(item => 'neverEnds' in item) ? 'import NonTerm\n' : ''}${items.some(item => 'kInduction' in item) ? 'import KInd\n' : ''}${cycTexts ? 'import BridgeRules\n' : ''}${items.some(item => 'cyclic' in item) ? (items.some(item => 'cyclic' in item && (item.bridge || item.recur || item.fold)) ? 'import Bridge\n' : 'import Cyclic\n') : ''}${items.some(item => 'cyclic' in item && item.data) ? 'import Data\n' : ''}import ${items.some(item => 'refinement' in item) ? 'Refine' : items.some(item => 'machine' in item && (item.ghosts?.length || item.laws.some(l => l.some?.length))) ? 'Ghost' : items.some(item => ('machine' in item && item.liveness?.length) || 'loop' in item) ? 'Live' : items.some(item => 'machine' in item) ? 'Sets' : 'Steps'}
2755
+ ${finiteImport}${ghostImport}${wordReads(items).length ? 'import WordFacts\nimport WordSMachine\n' : ''}${items.some(item => 'countedGoal' in item || 'countedMachine' in item) ? 'import QAlpha\n' : ''}${items.some(item => 'machine' in item && item.machine.sums && Object.keys(item.machine.sums).length) ? 'import Sums\n' : ''}${items.some(item => 'neverEnds' in item) ? 'import NonTerm\n' : ''}${items.some(item => 'kInduction' in item) ? 'import KInd\n' : ''}${cycTexts ? 'import BridgeRules\n' : ''}${items.some(item => 'cyclic' in item) ? (items.some(item => 'cyclic' in item && (item.bridge || item.recur || item.fold)) ? 'import Bridge\n' : 'import Cyclic\n') : ''}${items.some(item => 'cyclic' in item && item.data) ? 'import Data\n' : ''}import ${items.some(item => 'refinement' in item) ? 'Refine' : items.some(item => 'machine' in item && (item.ghosts?.length || item.laws.some(l => l.some?.length))) ? 'Ghost' : items.some(item => ('machine' in item && item.liveness?.length) || 'loop' in item) ? 'Live' : items.some(item => 'machine' in item) ? 'Sets' : 'Steps'}
2734
2756
  open Kern Cert
2735
2757
  set_option maxRecDepth 100000
2736
2758
  set_option maxHeartbeats 0
@@ -0,0 +1,3 @@
1
+ import type { Law, Machine } from '../core/machine.js';
2
+ import { type FiniteSumCertificate } from '../kernel/finite-sum.js';
3
+ export declare function finiteSumToLean(id: string, m: Machine, law: Law, certificate: FiniteSumCertificate): string;