gdp-wired 0.51.0 → 0.53.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 (89) 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/aggregate-kinds.d.ts +10 -0
  5. package/dist/core/aggregate-kinds.js +44 -0
  6. package/dist/core/aggregate-search.d.ts +9 -0
  7. package/dist/core/aggregate-search.js +74 -0
  8. package/dist/core/aggregate-weighted/candidates.d.ts +18 -0
  9. package/dist/core/aggregate-weighted/candidates.js +128 -0
  10. package/dist/core/aggregate-weighted/search.d.ts +17 -0
  11. package/dist/core/aggregate-weighted/search.js +68 -0
  12. package/dist/core/cli.d.ts +2 -0
  13. package/dist/core/cli.js +8 -1
  14. package/dist/core/cycles.d.ts +2 -0
  15. package/dist/core/cycles.js +12 -9
  16. package/dist/core/dsl.d.ts +7 -1
  17. package/dist/core/dsl.js +158 -26
  18. package/dist/core/filtered-sum-candidates.d.ts +17 -0
  19. package/dist/core/filtered-sum-candidates.js +77 -0
  20. package/dist/core/live-support.d.ts +5 -0
  21. package/dist/core/live-support.js +148 -0
  22. package/dist/core/live.js +194 -37
  23. package/dist/core/lockstep.d.ts +5 -0
  24. package/dist/core/lockstep.js +23 -0
  25. package/dist/core/ordered-pair-seeds.d.ts +2 -0
  26. package/dist/core/ordered-pair-seeds.js +109 -0
  27. package/dist/core/proof-output.d.ts +49 -2
  28. package/dist/core/proof-output.js +44 -0
  29. package/dist/core/search-termination.d.ts +4 -0
  30. package/dist/core/search-termination.js +1 -1
  31. package/dist/core/source-check.d.ts +4 -1
  32. package/dist/core/source-check.js +5 -2
  33. package/dist/core/sparse-kind-proof.d.ts +7 -0
  34. package/dist/core/sparse-kind-proof.js +49 -0
  35. package/dist/core/step-seeds.d.ts +46 -0
  36. package/dist/core/step-seeds.js +316 -0
  37. package/dist/kernel/finite-sum.d.ts +31 -0
  38. package/dist/kernel/finite-sum.js +74 -0
  39. package/dist/kernel/ghost-write.d.ts +117 -0
  40. package/dist/kernel/ghost-write.js +89 -0
  41. package/dist/lean-kernel/Cert.lean +222 -0
  42. package/dist/lean-kernel/Count.lean +1568 -0
  43. package/dist/lean-kernel/Ghost.lean +373 -0
  44. package/dist/lean-kernel/GhostMap.lean +426 -0
  45. package/dist/lean-kernel/Kernel.lean +2881 -0
  46. package/dist/lean-kernel/Live.lean +1168 -0
  47. package/dist/lean-kernel/Progress.lean +543 -0
  48. package/dist/lean-kernel/Sets.lean +1975 -0
  49. package/dist/lean-kernel/StepLaw.lean +128 -0
  50. package/dist/lean-kernel/Steps.lean +477 -0
  51. package/dist/lean-kernel/Sums.lean +916 -0
  52. package/dist/lean-kernel/emit.d.ts +15 -0
  53. package/dist/lean-kernel/emit.js +47 -6
  54. package/dist/lean-kernel/finite-sum-export.d.ts +3 -0
  55. package/dist/lean-kernel/finite-sum-export.js +163 -0
  56. package/dist/lean-kernel/ghost-write-export.d.ts +3 -0
  57. package/dist/lean-kernel/ghost-write-export.js +81 -0
  58. package/dist/lean-kernel/lean-aggregate/FiniteFold.lean +44 -0
  59. package/dist/lean-kernel/lean-aggregate/GroupedTransport.lean +308 -0
  60. package/dist/lean-kernel/lean-aggregate/aggregate.d.ts +13 -0
  61. package/dist/lean-kernel/lean-aggregate/aggregate.js +68 -0
  62. package/dist/lean-kernel/lean-aggregate/assets.d.ts +5 -0
  63. package/dist/lean-kernel/lean-aggregate/assets.js +7 -0
  64. package/dist/lean-kernel/lean-aggregate/audit.d.ts +3 -0
  65. package/dist/lean-kernel/lean-aggregate/audit.js +13 -0
  66. package/dist/lean-kernel/lean-aggregate/exact.d.ts +15 -0
  67. package/dist/lean-kernel/lean-aggregate/exact.js +51 -0
  68. package/dist/lean-kernel/lean-aggregate/index.d.ts +19 -0
  69. package/dist/lean-kernel/lean-aggregate/index.js +52 -0
  70. package/dist/lean-kernel/lean-aggregate/point-fold.d.ts +27 -0
  71. package/dist/lean-kernel/lean-aggregate/point-fold.js +79 -0
  72. package/dist/lean-kernel/lean-aggregate/replay-fold.d.ts +2 -0
  73. package/dist/lean-kernel/lean-aggregate/replay-fold.js +163 -0
  74. package/dist/lean-kernel/lean-aggregate/source.d.ts +2 -0
  75. package/dist/lean-kernel/lean-aggregate/source.js +141 -0
  76. package/dist/lean-kernel/lean-aggregate/weighted-flags.d.ts +2 -0
  77. package/dist/lean-kernel/lean-aggregate/weighted-flags.js +26 -0
  78. package/dist/lean-kernel/lean-aggregate/weighted-replay.d.ts +7 -0
  79. package/dist/lean-kernel/lean-aggregate/weighted-replay.js +53 -0
  80. package/dist/lean-kernel/lean-aggregate/weighted-seeded.d.ts +30 -0
  81. package/dist/lean-kernel/lean-aggregate/weighted-seeded.js +64 -0
  82. package/dist/lean-kernel/lean-aggregate/weighted.d.ts +18 -0
  83. package/dist/lean-kernel/lean-aggregate/weighted.js +115 -0
  84. package/dist/lean-kernel/lean-aggregate/worker.d.ts +10 -0
  85. package/dist/lean-kernel/lean-aggregate/worker.js +46 -0
  86. package/dist/lean-kernel/library.js +3 -0
  87. package/dist/lean-kernel/lift-simulation/shape.js +5 -5
  88. package/docs/lean-aggregate.md +29 -0
  89. package/package.json +6 -1
@@ -9,5 +9,5 @@ export const terminationWhy = (t) => `${t.kind === 'wall-deadline' ? 'wall deadl
9
9
  export const completedSourceRefusal = (v) => !!v && v.proven === false && v.checked === false && v.kernelProven === true &&
10
10
  (v.translation === 'unchecked' || v.translation === 'error') &&
11
11
  v.stopped === undefined && v.termination === undefined && !v.stats?.stopped && v.stats?.termination === undefined;
12
- export const completedSearch = (v) => !!v && (v.proven && v.checked || v.run !== undefined || completedSourceRefusal(v));
12
+ export const completedSearch = (v) => !!v && (v.proven && v.checked || v.run !== undefined || !!v.fairRing || v.acceleratedRun?.checked === true || completedSourceRefusal(v));
13
13
  export const stoppedSearch = (v, termination) => ({ ...v, stopped: true, termination, context: searchContext(v), why: terminationWhy(termination) });
@@ -28,6 +28,7 @@ export type TranslationFields = {
28
28
  translationWitness?: NativeObservation;
29
29
  kernelProven?: boolean;
30
30
  };
31
+ export declare const isSourceBound: (rule: object, laws: object[]) => boolean;
31
32
  export declare function inheritSource(from: object, to: object, transparent?: boolean): void;
32
33
  export declare function bindSourceMachine(rule: object, machine: object): void;
33
34
  export declare function rememberNative(e: object, journal: NativeJournal): void;
@@ -42,7 +43,9 @@ export declare function translationVerdict<V extends {
42
43
  checked: boolean;
43
44
  why?: string;
44
45
  stuck?: string;
45
- }>(rule: object, laws: object[], verdict: V): TranslatedVerdict<V>;
46
+ fairRing?: unknown;
47
+ acceleratedRun?: unknown;
48
+ }>(rule: object, laws: object[], input: V): TranslatedVerdict<V>;
46
49
  export declare function requireSourceTranslation(rule: object, laws: object[]): void;
47
50
  export declare const nativeSame: (a: unknown, b: unknown) => boolean;
48
51
  export declare function nativeSnapshot(value: unknown, seen?: Map<object, unknown>): unknown;
@@ -2,6 +2,8 @@
2
2
  // the private observations must downgrade a source proof, not turn it into a DSL proof.
3
3
  const sourceMarker = Symbol.for('gdp-wired.source-proof.v1');
4
4
  const marked = (value) => Object.prototype.hasOwnProperty.call(value, sourceMarker);
5
+ // A model counterexample is not a native source replay.
6
+ export const isSourceBound = (rule, laws) => marked(rule) || laws.some(marked);
5
7
  const mark = (value, enumerable = false) => { if (!marked(value))
6
8
  Object.defineProperty(value, sourceMarker, { value: true, enumerable }); };
7
9
  const markRule = (value) => {
@@ -44,10 +46,11 @@ export function attachNativeLaw(rule, law, name, method, evaluate) {
44
46
  mark(law);
45
47
  nativeLaws.set(law, { rule: sources.get(rule)?.root ?? rule, name, method, evaluate });
46
48
  }
47
- export function translationVerdict(rule, laws, verdict) {
49
+ export function translationVerdict(rule, laws, input) {
48
50
  const source = sources.get(rule), bound = laws.map(l => nativeLaws.get(l)).filter(x => x !== undefined);
49
51
  if (!source && !bound.length && !marked(rule) && !laws.some(marked))
50
- return verdict;
52
+ return input;
53
+ const verdict = input.fairRing === undefined && input.acceleratedRun === undefined ? input : { ...input, fairRing: undefined, acceleratedRun: undefined };
51
54
  const journal = source?.journal;
52
55
  const unchecked = (why) => ({ ...verdict, proven: false, checked: false, kernelProven: verdict.proven && verdict.checked, translation: 'unchecked', why: `source translation unchecked: ${why}` });
53
56
  if (!journal?.enabled || !journal.complete)
@@ -0,0 +1,7 @@
1
+ import { type Law, type Machine } from './machine.js';
2
+ import { type Instances, type Tree } from '../kernel/kernel.js';
3
+ export declare function kindConjuncts(kinds: Law[], reserved: Law[]): Law[];
4
+ export declare function sparseKindProof(m: Machine, laws: Law[], until: number): {
5
+ instances: Record<string, Instances>;
6
+ trees: Record<string, Tree>;
7
+ } | undefined;
@@ -0,0 +1,49 @@
1
+ // Try a small instantiation of the ordinary family. Only the unchanged
2
+ // kernel's checkLaws can accept it. This is useful when numerous kind guards
3
+ // share a record but each output only needs the previous kind at its own key.
4
+ import { walkOnce } from "./machine.js";
5
+ import { checkLaws, obligations } from "../kernel/kernel.js";
6
+ import { grow } from "../kernel/prove.js";
7
+ // A conjunction of state laws at one arbitrary key holds exactly when all
8
+ // of its conjuncts hold at that same key. Preserve the binders and check the
9
+ // entire resulting family; this only removes branching between kind fields.
10
+ export function kindConjuncts(kinds, reserved) {
11
+ const names = new Set([...kinds, ...reserved].map(l => l.name));
12
+ const flatten = (c) => c.op === 'and' && c.xs.length ? c.xs.flatMap(flatten) : [c];
13
+ return kinds.flatMap(law => {
14
+ if (law.some?.length || law.finite || law.keys?.length)
15
+ return [law];
16
+ const parts = flatten(law.holds);
17
+ return parts.length === 1 ? [law] : parts.map((holds, i) => {
18
+ let name = `${law.name} [conjunct ${i + 1}]`;
19
+ while (names.has(name))
20
+ name += '_';
21
+ names.add(name);
22
+ return { ...law, name, holds };
23
+ });
24
+ });
25
+ }
26
+ export function sparseKindProof(m, laws, until) {
27
+ if (laws.some(l => l.keys?.length || l.some?.length || l.finite))
28
+ return undefined;
29
+ const instances = Object.fromEntries(laws.filter(l => l.forall).map(law => {
30
+ const reads = new Set(), key = { op: 'var', name: `${law.forall}#` };
31
+ walkOnce(law.holds, x => { const t = x; if (t.op === 'get')
32
+ reads.add(t.map); });
33
+ const addresses = [...reads].flatMap(map => {
34
+ const w = m.step.maps?.[map];
35
+ return w && 'key' in w ? [w.key] : [];
36
+ });
37
+ const terms = [...new Map([key, ...addresses].map(t => [JSON.stringify(t), t])).values()];
38
+ return [law.name, { [law.name]: terms }];
39
+ }));
40
+ const trees = Object.create(null);
41
+ for (const goal of obligations(m, laws, instances)) {
42
+ const got = grow(goal, new Map(), { nodes: 0, until });
43
+ if (!('tree' in got))
44
+ return undefined;
45
+ trees[goal.name] = got.tree;
46
+ }
47
+ const proof = { instances, trees };
48
+ return checkLaws(m, laws, proof) ? proof : undefined;
49
+ }
@@ -0,0 +1,46 @@
1
+ import { type Law, type Machine } from './machine.js';
2
+ import { type Instances, type StepLaw, type Tree } from '../kernel/kernel.js';
3
+ export declare function stepSeedFamilies(m: Machine, sl: StepLaw): Law[][];
4
+ export declare function tryStepSeed(m: Machine, laws: Law[], kinds: Law[], sl: StepLaw, seeds: Law[], sparse?: boolean): {
5
+ family: Law[];
6
+ checked: import("../kernel/prove.ts").Report & {
7
+ laws?: Law[];
8
+ machine?: Machine;
9
+ stepLaws?: StepLaw[];
10
+ proof?: {
11
+ laws: {
12
+ instances: Record<string, Instances>;
13
+ trees: Record<string, Tree>;
14
+ };
15
+ instances: Instances;
16
+ perStep?: Record<string, Instances>;
17
+ trees: Record<string, Tree>;
18
+ };
19
+ uncovered?: string[];
20
+ };
21
+ kindProof?: undefined;
22
+ } | {
23
+ family: Law[];
24
+ checked: import("../kernel/prove.ts").Report & {
25
+ laws?: Law[];
26
+ machine?: Machine;
27
+ stepLaws?: StepLaw[];
28
+ proof?: {
29
+ laws: {
30
+ instances: Record<string, Instances>;
31
+ trees: Record<string, Tree>;
32
+ };
33
+ instances: Instances;
34
+ perStep?: Record<string, Instances>;
35
+ trees: Record<string, Tree>;
36
+ };
37
+ uncovered?: string[];
38
+ };
39
+ kindProof: {
40
+ laws: Law[];
41
+ proof: {
42
+ instances: Record<string, Instances>;
43
+ trees: Record<string, Tree>;
44
+ };
45
+ };
46
+ } | undefined;
@@ -0,0 +1,316 @@
1
+ // Search-only proposals. The existing step checker proves all the proposed state
2
+ // invariants and the original step law, or this stage contributes nothing.
3
+ import { hasFinite } from "./machine.js";
4
+ import { checkWorkEndpoint } from "./wall.js";
5
+ import { checkStepLaws, obligations, stepLawObligations } from "../kernel/kernel.js";
6
+ import { grow, proveStepLaws } from "../kernel/prove.js";
7
+ import { kindConjuncts, sparseKindProof } from "./sparse-kind-proof.js";
8
+ const repr = (x) => JSON.stringify(x);
9
+ const same = (a, b) => repr(a) === repr(b);
10
+ const v = (name) => ({ op: 'var', name });
11
+ const n = (value) => ({ op: 'const', value });
12
+ const get = (map, key) => ({ op: 'get', map, key });
13
+ const eq = (a, b) => ({ op: '=', a, b });
14
+ const le = (a, b) => ({ op: '<=', a, b });
15
+ const neg = (x) => ({ op: 'not', x });
16
+ const imp = (a, b) => ({ op: 'or', xs: [neg(a), b] });
17
+ // Bound the syntax walk even on hand-built machines with shared subterms. Abort
18
+ // rather than interpreting a partial walk as evidence that no other write exists.
19
+ class TooWide extends Error {
20
+ }
21
+ function objects(t) {
22
+ const seen = new Set(), out = [], stack = [t];
23
+ while (stack.length) {
24
+ const x = stack.pop();
25
+ if (!x || typeof x !== 'object' || seen.has(x))
26
+ continue;
27
+ if ((seen.size & 255) === 0)
28
+ checkWorkEndpoint('step seed syntax');
29
+ if (seen.size >= 8192)
30
+ throw new TooWide();
31
+ seen.add(x);
32
+ if (!Array.isArray(x))
33
+ out.push(x);
34
+ const xs = Object.values(x);
35
+ for (let i = xs.length - 1; i >= 0; i--)
36
+ stack.push(xs[i]);
37
+ }
38
+ return out;
39
+ }
40
+ const nodes = (t, op) => objects(t).filter(x => x.op === op);
41
+ const values = (t, depth = 0) => {
42
+ if (depth > 16)
43
+ throw new TooWide();
44
+ return t.op === 'if' ? [...values(t.then, depth + 1), ...values(t.else, depth + 1)] : [t];
45
+ };
46
+ function flagClosure(m, t) {
47
+ const roots = [t], seen = new Set();
48
+ for (let i = 0; i < roots.length; i++)
49
+ for (const f of nodes(roots[i], 'flag')) {
50
+ const c = m.step.flags?.[f.name];
51
+ if (c && !seen.has(f.name)) {
52
+ seen.add(f.name);
53
+ roots.push(c);
54
+ }
55
+ if (roots.length > 64)
56
+ throw new TooWide();
57
+ }
58
+ return roots;
59
+ }
60
+ function conjuncts(m, c, active = new Set(), depth = 0) {
61
+ if (depth > 16)
62
+ throw new TooWide();
63
+ if (c.op === 'and')
64
+ return c.xs.flatMap(x => conjuncts(m, x, active, depth + 1));
65
+ if (c.op === 'flag' && !active.has(c.name) && m.step.flags?.[c.name])
66
+ return conjuncts(m, m.step.flags[c.name], new Set([...active, c.name]), depth + 1);
67
+ return [c];
68
+ }
69
+ function seed(holds, name, forall) {
70
+ return { name: `step seed: ${name}`, holds, ...(forall === undefined ? {} : { forall }) };
71
+ }
72
+ // Find the access guards for the exact fields the step law expects to stay
73
+ // unchanged (or only change in one direction). An old-state tag on one field
74
+ // can make a default-valued allocation guard on a sibling field impossible.
75
+ function compatible(m, sl) {
76
+ if (!sl.forall || sl.keys?.length || sl.then.op !== 'or' || !m.maps)
77
+ return [];
78
+ const ante = sl.then.xs.find(x => x.op === 'not')?.x, k = v(sl.forall);
79
+ if (!ante || nodes(ante, 'var').some(x => x.name !== k.name))
80
+ return [];
81
+ const getters = nodes(ante, 'get'), maps = [...new Set(getters.map(x => x.map))], old = maps[0];
82
+ if (!old || maps.length !== 1 || !(old in m.maps) || !getters.every(x => same(x.key, k)))
83
+ return [];
84
+ const changed = [...new Set(nodes(sl.then, 'get').filter(x => x.map.endsWith("'")).map(x => x.map.slice(0, -1)))];
85
+ const kept = new Map();
86
+ for (const name of changed) {
87
+ const w = m.step.maps?.[name];
88
+ if (!w)
89
+ continue;
90
+ // Try the negation of actual default tests, and likewise the complement of
91
+ // a negated Boolean test on a zero-default cell. Merely occurring in a guard
92
+ // does not make the proposal true; it just gives the prover a useful guess.
93
+ for (const o of objects(flagClosure(m, w.value))) {
94
+ if (o.op !== '=' && o.op !== 'not')
95
+ continue;
96
+ const inverted = o.op === 'not', c = (inverted ? o.x : o);
97
+ if (c.op !== '=')
98
+ continue;
99
+ const [a, b] = c.a.op === 'get' ? [c.a, c.b] : [c.b, c.a];
100
+ if (a.op !== 'get' || b.op !== 'const' || a.map === old || kept.has(a.map))
101
+ continue;
102
+ if (inverted ? !(m.maps[a.map] === 0 && b.value === 1) : m.maps[a.map] !== b.value)
103
+ continue;
104
+ const test = eq(get(a.map, k), b);
105
+ kept.set(a.map, inverted ? test : neg(test));
106
+ }
107
+ }
108
+ const dot = old.lastIndexOf('.'), prefix = dot === -1 ? undefined : old.slice(0, dot + 1);
109
+ const local = (x) => Number(prefix !== undefined && x.startsWith(prefix));
110
+ return [...kept].sort(([a], [b]) => local(b) - local(a)).slice(0, 4)
111
+ .map(([a, test]) => [seed(imp(ante, test), `${old} excludes the allocation test for ${a}`, k.name)]);
112
+ }
113
+ // Derive a cursor anchor from an actual equality guard and corresponding writes
114
+ // of both the old and successor cursor. Match copied values by exact expression,
115
+ // not by names or adjacency in the user's source.
116
+ function coherence(m, sl) {
117
+ const state = m.step.state, maps = m.step.maps, defaults = m.maps;
118
+ if (sl.forall || !maps || !state || !defaults || !sl.when)
119
+ return [];
120
+ const inputs = new Set(m.inputs), vars = Object.keys(state);
121
+ const used = new Set([...m.inputs, ...m.params, ...Object.keys(m.state), ...nodes(m, 'var').map(x => x.name)]);
122
+ const key = ['$', '$$', '$$$'].find(x => !used.has(x));
123
+ if (!key)
124
+ return [];
125
+ const k = v(key);
126
+ const mvs = Object.fromEntries(Object.entries(maps).map(([a, w]) => [a, values(w.value)]));
127
+ const svs = Object.fromEntries(Object.entries(state).map(([a, e]) => [a, values(e)]));
128
+ const gvars = new Set(nodes([sl.then, sl.when], 'var').map(x => x.name.replace(/'$/, '')));
129
+ const clocks = new Map();
130
+ for (const { a, b } of nodes(m.assume, '<=')) {
131
+ if (a.op !== 'var' || b.op !== 'var' || !inputs.has(b.name))
132
+ continue;
133
+ const e = state[a.name];
134
+ if (e?.op === 'max' && ((same(e.a, a) && same(e.b, b)) || (same(e.b, a) && same(e.a, b))))
135
+ clocks.set(b.name, a);
136
+ }
137
+ // Normalize a guard to the stored observation and clock. It is a proposal,
138
+ // not an equivalence asserted between the original and normalized guards.
139
+ function relation(c, acting) {
140
+ let clock = false;
141
+ function rewrite(x, depth = 0) {
142
+ if (depth > 32)
143
+ throw new TooWide();
144
+ if (!x || typeof x !== 'object')
145
+ return x;
146
+ if (Array.isArray(x))
147
+ return x.map(z => rewrite(z, depth + 1));
148
+ const a = x;
149
+ if (a.op === 'if') {
150
+ const e = a.else;
151
+ if (e.op === 'get' && same(e.key, acting))
152
+ return get(e.map, k);
153
+ }
154
+ if (a.op === 'var') {
155
+ const s = a.name;
156
+ if (s === acting.name)
157
+ return k;
158
+ if (clocks.has(s)) {
159
+ clock = true;
160
+ return clocks.get(s);
161
+ }
162
+ }
163
+ return Object.fromEntries(Object.entries(a).map(([k, z]) => [k, rewrite(z, depth + 1)]));
164
+ }
165
+ const f = rewrite(c);
166
+ if (nodes(f, 'var').some(x => x.name !== key && !vars.includes(x.name) && !m.params.includes(x.name)) ||
167
+ nodes(f, 'get').some(x => !(x.map in defaults) || !same(x.key, k)) ||
168
+ objects(f).some(x => x.op === 'if' || x.op === 'all' || x.op === 'flag'))
169
+ return;
170
+ return { f, clock };
171
+ }
172
+ for (const test of nodes(flagClosure(m, sl.when), '=')) {
173
+ const [cur, cell] = test.a.op === 'get' ? [test.b, test.a] : [test.a, test.b];
174
+ if (cur.op !== 'var' || cell.op !== 'get' || cell.key.op !== 'var' || !inputs.has(cell.key.name))
175
+ continue;
176
+ const act = cell.key, primary = cell.map;
177
+ const next = svs[cur.name]?.find(e => e.op === 'add' && same(e.a, cur) && same(e.b, n(1)));
178
+ if (!next || !mvs[primary]?.some(e => same(e, next)) || !mvs[primary].some(e => same(e, cur)))
179
+ continue;
180
+ const seen = new Set(), out = [];
181
+ const push = (f, label, keyed = true) => {
182
+ const j = repr(f);
183
+ if (seen.has(j))
184
+ return;
185
+ seen.add(j);
186
+ out.push(seed(f, `${label} [${out.length}]`, keyed ? key : undefined));
187
+ };
188
+ const match = eq(get(primary, k), cur);
189
+ const secondary = Object.keys(mvs).filter(x => x !== primary && mvs[x].some(e => same(e, cur)) && !mvs[x].some(e => same(e, next)));
190
+ push(le(get(primary, k), cur), `${primary} is at most the cursor`);
191
+ for (const x of secondary)
192
+ push(le(get(x, k), get(primary, k)), `${x} is at most ${primary}`);
193
+ const identity = new Set();
194
+ let copies = 0;
195
+ for (const s of vars.filter(x => gvars.has(x) && x !== cur.name))
196
+ for (const mp of Object.keys(mvs)) {
197
+ if (mp === primary || secondary.includes(mp))
198
+ continue;
199
+ const both = svs[s].filter(e => e.op !== 'const' && !same(e, v(s)) && mvs[mp].some(t => same(t, e)));
200
+ if (!both.length)
201
+ continue;
202
+ const now = both.find(e => e.op === 'var' && clocks.has(e.name));
203
+ if (now?.op === 'var')
204
+ push(le(v(s), clocks.get(now.name)), `${s} is not past the clock`, false);
205
+ push(imp(match, now ? le(v(s), get(mp, k)) : eq(get(mp, k), v(s))), `${mp} is current on a matched cursor`);
206
+ copies++;
207
+ if (both.some(e => same(e, act)))
208
+ identity.add(mp);
209
+ }
210
+ if (!copies)
211
+ continue;
212
+ const timeGoal = nodes(sl.then, 'var').some(x => clocks.has(x.name)), post = nodes(sl.then, 'var').some(x => x.name.endsWith("'"));
213
+ const readers = new Set(nodes(flagClosure(m, [sl.when, ...vars.filter(x => gvars.has(x)).map(x => state[x])]), 'get').map(x => x.map));
214
+ for (const [mp, wr] of Object.entries(maps)) {
215
+ if (!readers.has(mp) || mp === primary || secondary.includes(mp) || identity.has(mp))
216
+ continue;
217
+ const b = get(mp, k), def = defaults[mp];
218
+ if (def === undefined)
219
+ continue;
220
+ const arms = [];
221
+ const visit = (e, path) => {
222
+ if (path.length > 16 || arms.length > 6)
223
+ throw new TooWide();
224
+ if (e.op === 'if') {
225
+ visit(e.then, [...path, e.c]);
226
+ visit(e.else, [...path, neg(e.c)]);
227
+ }
228
+ else if (e.op === 'const' && e.value !== def)
229
+ arms.push({ tag: e.value, path });
230
+ };
231
+ visit(wr.value, []);
232
+ for (const { tag, path } of arms) {
233
+ const cs = flagClosure(m, path);
234
+ if (timeGoal) {
235
+ for (const c of nodes(cs, 'not').filter(x => x.x.op === 'and')) {
236
+ const r = relation(c, act);
237
+ if (r?.clock && nodes(r.f, 'get').some(x => identity.has(x.map)))
238
+ push(imp(neg(eq(b, n(def))), r.f), `${mp} retains its clock guard`);
239
+ }
240
+ }
241
+ else if (post) {
242
+ const top = path.flatMap(c => conjuncts(m, c));
243
+ for (const c of nodes(cs, '=')) {
244
+ const r = relation(c, act);
245
+ if (r?.f.op !== '=' || !nodes(r.f, 'get').some(x => identity.has(x.map)) || ![r.f.a, r.f.b].some(z => same(z, k)))
246
+ continue;
247
+ push(imp(eq(b, n(tag)), top.some(x => same(x, c)) ? r.f : neg(r.f)), `${mp} retains the identity test for ${tag}`);
248
+ }
249
+ }
250
+ }
251
+ }
252
+ if (out.length <= 16)
253
+ return [out];
254
+ }
255
+ return [];
256
+ }
257
+ export function stepSeedFamilies(m, sl) {
258
+ try {
259
+ if ((sl.steps ?? 1) !== 1 || m.history || m.sums || m.counts || !m.maps || m.primitiveFailure || m.inputMaps?.length ||
260
+ objects([m, sl]).some(x => x.finite !== undefined) || hasFinite(sl))
261
+ return [];
262
+ return sl.forall ? compatible(m, sl) : coherence(m, sl);
263
+ }
264
+ catch (error) {
265
+ if (error instanceof TooWide)
266
+ return [];
267
+ throw error;
268
+ }
269
+ }
270
+ // Only trust the resulting ordinary proof. Kind reminders can be omitted for
271
+ // an allocation-guard proposal: proving with fewer hypotheses is stronger and
272
+ // avoids instantiating unrelated record fields at all possible write keys.
273
+ function atKeyProof(m, family, sl) {
274
+ // Every supplied hypothesis is still required at initiation and preservation.
275
+ // Start with the observed key only; instantiation is a proof-search choice.
276
+ const [law] = family, key = sl.forall;
277
+ const inst = { [law.name]: [v(key)] }, inv = { [law.name]: { [law.name]: [v(`${key}#`)] } };
278
+ const lt = {}, st = {};
279
+ let count = 0;
280
+ for (const [goals, dst] of [[obligations(m, family, inv), lt], [stepLawObligations(m, family, inst, sl), st]]) {
281
+ for (const g of goals) {
282
+ const r = grow(g);
283
+ if (!('tree' in r))
284
+ return { proven: false, checked: false, nodes: count, leaves: 0, failed: { goal: g.name, stuck: r.stuck, why: r.why, witness: r.witness } };
285
+ count += r.nodes;
286
+ dst[g.name] = r.tree;
287
+ }
288
+ }
289
+ const proof = { laws: { instances: inv, trees: lt }, instances: inst, trees: st };
290
+ if (!checkStepLaws(m, family, [sl], proof))
291
+ return undefined;
292
+ return { proven: true, checked: true, proof, nodes: count, leaves: 0 };
293
+ }
294
+ export function tryStepSeed(m, laws, kinds, sl, seeds, sparse = true) {
295
+ const extraKinds = kinds.filter(k => !laws.some(l => l.name === k.name));
296
+ const given = [...extraKinds, ...laws];
297
+ if (!seeds.length || new Set(seeds.map(s => s.name)).size !== seeds.length || seeds.some(s => given.some(l => l.name === s.name)))
298
+ return undefined;
299
+ const atKey = !laws.length && seeds.length === 1 && sl.forall && seeds[0].forall === sl.forall && !m.facts?.length &&
300
+ !Object.values(m.step.flags ?? {}).some(c => c.op === 'all');
301
+ if (atKey && sparse) {
302
+ const checked = atKeyProof(m, seeds, sl);
303
+ if (!checked?.proof || !checked.proven || !checked.checked)
304
+ return undefined;
305
+ // Kind laws are independent obligations of the public call, not optional
306
+ // conclusions. Check them separately to keep the sparse step proof small.
307
+ if (!extraKinds.length)
308
+ return { family: seeds, checked };
309
+ const kindLaws = kindConjuncts(extraKinds, seeds), proof = sparseKindProof(m, kindLaws, Infinity);
310
+ return proof ? { family: seeds, checked, kindProof: { laws: kindLaws, proof } } : undefined;
311
+ }
312
+ const family = [...given, ...seeds], checked = proveStepLaws(m, family, [sl]);
313
+ if (!checked.proof || !checked.proven || !checked.checked || !checkStepLaws(m, family, [sl], checked.proof))
314
+ return undefined;
315
+ return { family, checked };
316
+ }
@@ -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
+ }