gdp-wired 0.34.0 → 0.35.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.
@@ -0,0 +1,31 @@
1
+ import { type C, type E, type Law, type Machine, type State } from './machine.js';
2
+ import { type CountCert, type CountInst, type Instances, type MapRead } from '../kernel/kernel.js';
3
+ type Env = Record<string, number>;
4
+ export declare function guardLaws(m: Machine): {
5
+ counts: Machine['counts'];
6
+ laws: Law[];
7
+ };
8
+ export declare function pairLaws(m: Machine): Law[];
9
+ export declare function small(m: Machine, p: Env, b: number, cap?: number): State[];
10
+ export declare function certFor(goal: {
11
+ hyps: C[];
12
+ }, decls: {
13
+ map: string;
14
+ below: E;
15
+ }[]): {
16
+ reads: MapRead[];
17
+ insts: CountInst[];
18
+ wits: string[];
19
+ };
20
+ export type Counted = {
21
+ proven: boolean;
22
+ laws: Law[];
23
+ m: Machine;
24
+ proof?: {
25
+ instances: Record<string, Instances>;
26
+ certs: Record<string, CountCert>;
27
+ };
28
+ why?: string;
29
+ };
30
+ export declare function searchCounted(m0: Machine, caller: Law[], ms?: number): Counted;
31
+ export {};
@@ -0,0 +1,264 @@
1
+ // The search for a machine with counts (Machine.counts; the kernel's countedObligations and checkCountedLaws, Lean's
2
+ // CountMachine.lean): untrusted. It proposes laws that read counts of the state, filters every candidate on the small
3
+ // instances' reachable states, and keeps the largest set the kernel accepts (Houdini), each goal's certificate built
4
+ // here: the count cells the goal reads, Count.lean's instances over pairs of them, and the laws and quantified flags at
5
+ // the instances' witnesses.
6
+ // - The guard's shape: a step writes P[t] where a quantified flag says every member of a set the request counts
7
+ // satisfies R(member, t), and the assumption compares that count with a bound (2·|Q| > size, |Q| ≥ n − t, …). Then
8
+ // a state count c_R(x) = |{k < bound: R(k, x)}| is declared, and P[a] ⇒ the same comparison with c_R[a] for |Q| is
9
+ // proposed: what every majority, quorum or threshold protocol keeps of its decisions.
10
+ // - A guard comparing a state count at the written key (2·voters[n] > size, Leader[n] := 1): P[a] ⇒ that comparison
11
+ // at a.
12
+ // - Each map's cells at most what the small instances reach.
13
+ import { carriedView, evalC, interpret } from "./machine.js";
14
+ import { checkCountedLaws, countedObligations, mcGoal, substC } from "../kernel/kernel.js";
15
+ import { clock, grow } from "../kernel/prove.js";
16
+ import { env } from "./solver.js";
17
+ const v = (name) => ({ op: 'var', name }), k = (value) => ({ op: 'const', value });
18
+ const json = (t) => JSON.stringify(t);
19
+ const one = k(1), zero = k(0);
20
+ // Every term t with `get(map, t)` in t0.
21
+ function reads(t0, map, out = new Map()) {
22
+ const go = (x) => {
23
+ if (!x || typeof x !== 'object')
24
+ return;
25
+ const o = x;
26
+ if (o.op === 'get' && map(o.map))
27
+ out.set(json([o.map, o.key]), [o.map, o.key]);
28
+ for (const y of Object.values(o))
29
+ go(y);
30
+ };
31
+ go(t0);
32
+ return out;
33
+ }
34
+ const mentions = (t, name) => json(t).includes(`"name":${json(name)}`);
35
+ const atoms = (c) => (c.op === 'and' || c.op === 'or' ? c.xs.flatMap(atoms) : c.op === 'not' ? atoms(c.x) : [c]);
36
+ // --- candidates from the guard's shape -----------------------------------------------------------------------------------
37
+ export function guardLaws(m) {
38
+ const counts = {}, laws = [];
39
+ const flags = m.step.flags ?? {}, fsub = { vars: {}, maps: {}, flags: Object.fromEntries(Object.entries(flags).map(([f, fc]) => [f, fc.op === 'all' ? { op: '=', a: v(`?${f}`), b: one } : fc])) };
40
+ const inline = (c) => { let x = c; for (let i = 0; i < 4 && json(x).includes('"op":"flag"'); i++)
41
+ x = substC(x, fsub); return x; };
42
+ const guards = m.assume ? atoms(m.assume).filter(a => a.op === '<' || a.op === '<=') : [];
43
+ const isCount = (mp) => !!m.counts?.[mp];
44
+ for (const [mp, w] of Object.entries(m.step.maps ?? {})) {
45
+ if ('each' in w || w.key.op !== 'var' || !m.inputs.includes(w.key.name))
46
+ continue;
47
+ const t = w.key.name, written = inline({ op: '<=', a: one, b: w.value });
48
+ const law = (name, cmp) => ({ name, forall: 'a$c', holds: { op: 'or', xs: [{ op: 'not', x: { op: '<=', a: one, b: { op: 'get', map: mp, key: v('a$c') } } }, cmp] } });
49
+ // A comparison with a state count at the written key.
50
+ for (const g of guards)
51
+ for (const [, [c, key]] of reads(g, isCount)) {
52
+ if (json(key) !== json(v(t)) || mentions(m.counts[c].body, t))
53
+ continue;
54
+ if (m.inputs.some(i => i !== t && mentions(g, i)))
55
+ continue;
56
+ laws.push(law(`${mp} keeps ${c}'s bound`, substC(g, { vars: { [t]: v('a$c') }, maps: {}, flags: {} })));
57
+ }
58
+ // A quantified flag the write reads: every member of a counted set satisfies R(member, t).
59
+ for (const [f, q] of Object.entries(flags)) {
60
+ if (q.op !== 'all' || q.keys?.length || !mentions(written, `?${f}`) || q.c.op !== 'or' || q.c.xs.length !== 2)
61
+ continue;
62
+ const [h, r] = q.c.xs[0].op === 'not' ? [q.c.xs[0].x, q.c.xs[1]] : [q.c.xs[1].op === 'not' ? q.c.xs[1].x : undefined, q.c.xs[0]];
63
+ if (!h || !r)
64
+ continue;
65
+ for (const [c, d] of Object.entries(m.counts ?? {})) {
66
+ // the set: the count's body is the flag's hypothesis at its key
67
+ const body = d.body.op === 'if' ? d.body.c : undefined;
68
+ if (!body || json(substC(body, { vars: { [d.key]: v(q.key) }, maps: {}, flags: {} })) !== json(h))
69
+ continue;
70
+ if (m.inputs.some(i => i !== t && mentions(r, i)))
71
+ continue;
72
+ const name = `${c}$${mp}`, j = `${name}$x`, key = `${name}$k`;
73
+ counts[name] = { j, key, below: d.below, body: { op: 'if', c: substC(r, { vars: { [q.key]: v(key), [t]: v(j) }, maps: {}, flags: {} }), then: one, else: zero } };
74
+ for (const g of guards)
75
+ if (reads(g, x => x === c).size)
76
+ laws.push(law(`${mp} keeps ${c}'s bound through ${name}`, substC(g, { vars: {}, maps: { [c]: () => ({ op: 'get', map: name, key: v('a$c') }) }, flags: {} })));
77
+ }
78
+ }
79
+ }
80
+ return { counts, laws };
81
+ }
82
+ // --- relations over pairs: one value per first key, and one relation inside another ---------------------------------
83
+ // A map written at x·N + y (a relation, x's row) is a candidate for "at most one y in a row", and each two such maps for
84
+ // "one holds where the other does", at the same pair or the swapped one; the small instances keep the true ones.
85
+ export function pairLaws(m) {
86
+ const widths = new Map();
87
+ for (const [mp, w] of Object.entries(m.step.maps ?? {}))
88
+ if (!('each' in w) && w.key.op === 'add' && w.key.a.op === 'mul' && w.key.a.a.op === 'var' && w.key.b.op === 'var')
89
+ widths.set(mp, w.key.a.k);
90
+ const at = (mp, x, y, n) => ({ op: 'get', map: mp, key: { op: 'add', a: { op: 'mul', k: n, a: v(x) }, b: v(y) } });
91
+ const has = (e) => ({ op: '<=', a: one, b: e }), lt = (x, n) => ({ op: '<', a: v(x), b: k(n) });
92
+ const out = [];
93
+ for (const [mp, n] of widths)
94
+ out.push({ name: `${mp}: one per row`, forall: 'p$c', keys: ['q$c', 'r$c'], holds: { op: 'or', xs: [{ op: 'not', x: { op: 'and', xs: [lt('q$c', n), lt('r$c', n), has(at(mp, 'p$c', 'q$c', n)), has(at(mp, 'p$c', 'r$c', n))] } }, { op: '=', a: v('q$c'), b: v('r$c') }] } });
95
+ for (const [a, n] of widths)
96
+ for (const [b, n2] of widths)
97
+ if (a !== b && n === n2)
98
+ for (const swap of [false, true])
99
+ out.push({ name: `${a} inside ${b}${swap ? ', swapped' : ''}`, forall: 'p$c', keys: ['q$c'], holds: { op: 'or', xs: [{ op: 'not', x: { op: 'and', xs: [lt('q$c', n), lt('p$c', n), has(at(a, 'p$c', 'q$c', n))] } }, has(swap ? at(b, 'q$c', 'p$c', n) : at(b, 'p$c', 'q$c', n))] } });
100
+ // (and over one key: where one map's cell is set, another's is)
101
+ const singles = Object.entries(m.step.maps ?? {}).filter(([, w]) => !('each' in w) && w.key.op === 'var').map(([mp]) => mp);
102
+ for (const a of singles)
103
+ for (const b of singles)
104
+ if (a !== b)
105
+ out.push({ name: `${a} inside ${b}`, forall: 'p$c', holds: { op: 'or', xs: [{ op: 'not', x: has({ op: 'get', map: a, key: v('p$c') }) }, has({ op: 'get', map: b, key: v('p$c') })] } });
106
+ return out;
107
+ }
108
+ // --- the small instances --------------------------------------------------------------------------------------------------
109
+ // Every state reached from the start with the params at `p`, each input below `b`, each carried map a subset of 0 .. b − 1.
110
+ export function small(m, p, b, cap = 3000) {
111
+ const run = interpret(m), start = run.init(p);
112
+ const subsets = Array.from({ length: 1 << b }, (_, s) => new Map(Array.from({ length: b }, (_, i) => i).filter(i => (s >> i) & 1).map(i => [i, 1])));
113
+ let reqs = [{}];
114
+ for (const i of m.inputs)
115
+ reqs = reqs.flatMap(r => Array.from({ length: b }, (_, x) => ({ ...r, [i]: x })));
116
+ for (const c of m.inputMaps ?? [])
117
+ reqs = reqs.flatMap(r => subsets.map(s => ({ ...r, [c]: s })));
118
+ const seen = new Map([[json(start), start]]), queue = [start];
119
+ while (queue.length && seen.size < cap) {
120
+ const st = queue.shift();
121
+ for (const r of reqs) {
122
+ let next;
123
+ try {
124
+ next = run.step(p, st, r);
125
+ }
126
+ catch {
127
+ continue;
128
+ }
129
+ const key = json([next.scalars, Object.entries(next.maps).map(([n, cs]) => [n, [...cs].filter(([, x]) => x).sort((a, c) => a[0] - c[0])])]);
130
+ if (!seen.has(key)) {
131
+ seen.set(key, next);
132
+ queue.push(next);
133
+ }
134
+ }
135
+ }
136
+ return [...seen.values()];
137
+ }
138
+ // A law at a state, its counts the state's, at every key below b.
139
+ function holdsAt(m, law, p, st, b) {
140
+ const empty = Object.fromEntries((m.inputMaps ?? []).map(c => [c, new Map()]));
141
+ const view = carriedView(m, st, empty, undefined, p), keys = [law.forall, ...(law.keys ?? [])].filter((x) => !!x);
142
+ const go = (env, ks) => (ks.length ? Array.from({ length: b }, (_, x) => x).every(x => go({ ...env, [ks[0]]: x }, ks.slice(1))) : evalC(law.holds, { ...env, ...st.scalars }, view, m));
143
+ return go({ ...p }, keys);
144
+ }
145
+ // --- a goal's certificate -------------------------------------------------------------------------------------------------
146
+ // The count cells the goal reads (each before the step with its post name's twin), instances over pairs of them with one
147
+ // bound (a count that doesn't drop, +1 and −1; two that meet, +1, +1 and −1), each with a fresh witness; and the laws and
148
+ // quantified flags at the witnesses (returned, for the goal's law's instances).
149
+ export function certFor(goal, decls) {
150
+ const byMap = new Map(decls.map(d => [d.map, d])), last = goal.hyps.at(-1);
151
+ // (the conclusion's reads first, then those at a constant or the law's own names, then the rest)
152
+ const own = (t) => t.op === 'const' || (t.op === 'var' && json(last).includes(`"name":${json(t.name)}`));
153
+ const all0 = [...reads(goal.hyps, mp => byMap.has(mp)).values()], inLast = [...reads(last, mp => byMap.has(mp)).keys()];
154
+ const rank = ([mp, t]) => (inLast.includes(json([mp, t])) ? 0 : own(t) ? 1 : 2);
155
+ const rs = all0.sort((x, y) => rank(x) - rank(y));
156
+ // (each read after the step beside its twin before it, when the goal declares both)
157
+ for (const [mp, t] of [...rs])
158
+ if (mp.endsWith('#') && byMap.has(mp.slice(0, -1)) && !rs.some(([m2, t2]) => m2 === mp.slice(0, -1) && json(t2) === json(t)))
159
+ rs.push([mp.slice(0, -1), t]);
160
+ const named = rs.slice(0, 6).map(([mp, t], i) => [`r$${i}`, mp, t]);
161
+ const bound = (r) => json(byMap.get(r[1]).below);
162
+ const insts = [], wits = [];
163
+ const add = (terms, unit, below) => { const w = `w$${insts.length}`; wits.push(w); insts.push({ wit: w, below, terms, unit }); };
164
+ // first: a count after the step at least each other one (it doesn't drop; what the step adds); then two counts before it
165
+ // that meet, the first of the pair one the conclusion or the law's own names read; then the rest at most another
166
+ const post = (r) => r[1].endsWith('#'), ranked = (r) => rank([r[1], r[2]]) <= 1;
167
+ for (const c of named)
168
+ if (post(c))
169
+ for (const a of named)
170
+ if (a !== c && !post(a) && bound(a) === bound(c))
171
+ add([[1, a[0]], [-1, c[0]]], 0, byMap.get(c[1]).below);
172
+ for (const [i, a] of named.entries())
173
+ for (const [j, c] of named.entries())
174
+ if (i < j && (ranked(a) || ranked(c)) && bound(a) === bound(c) && !post(a) && !post(c))
175
+ add([[1, a[0]], [1, c[0]]], -1, byMap.get(a[1]).below);
176
+ for (const [i, a] of named.entries())
177
+ for (const [j, c] of named.entries())
178
+ if (i < j && !(ranked(a) || ranked(c)) && bound(a) === bound(c) && !post(a) && !post(c))
179
+ add([[1, a[0]], [1, c[0]]], -1, byMap.get(a[1]).below);
180
+ return { reads: named, insts: insts.slice(0, 10), wits: wits.slice(0, 10) };
181
+ }
182
+ export function searchCounted(m0, caller, ms = 60_000) {
183
+ const until = clock() + ms, g = guardLaws(m0), m = { ...m0, counts: { ...m0.counts, ...g.counts } };
184
+ // The small instances: each param 2 and 3 (where the precondition allows), inputs and sets below 3.
185
+ const insts = [2, 3].map(x => Object.fromEntries(m.params.map(p => [p, x])));
186
+ const states = insts.map(p => {
187
+ try {
188
+ return { p, sts: small(m, p, 3) };
189
+ }
190
+ catch {
191
+ return { p, sts: [] };
192
+ }
193
+ });
194
+ const kinds = Object.keys(m.maps ?? {}).map(mp => {
195
+ const most = Math.max(0, ...states.flatMap(({ sts }) => sts.flatMap(st => [...(st.maps[mp]?.values() ?? [])])));
196
+ return { name: `${mp} at most ${most}`, forall: 'a$c', holds: { op: '<=', a: { op: 'get', map: mp, key: v('a$c') }, b: k(most) } };
197
+ });
198
+ const trueAll = (l) => states.every(({ p, sts }) => sts.every(st => holdsAt(m, l, p, st, 4)));
199
+ if (!caller.every(trueAll))
200
+ return { proven: false, laws: caller, m, why: 'a law fails on the small instances' };
201
+ let set = [...caller, ...[...kinds, ...pairLaws(m), ...g.laws].filter(trueAll)];
202
+ if (env.GDP_COUNTS_TRACE)
203
+ console.error(`counts: candidates ${set.map(l => l.name).join('; ')}`);
204
+ for (let round = 0; clock() < until; round++) {
205
+ const terms = (l) => [...(l.forall ? [v(`${l.forall}#`)] : []), ...(l.keys ?? []).map(v), ...m.inputs.map(v)];
206
+ const instances = {}, certs = {}, failed = new Set();
207
+ for (const law of set) {
208
+ if (clock() > until)
209
+ return { proven: false, laws: set, m, why: 'time' };
210
+ const ts = terms(law);
211
+ const inst = (wits) => {
212
+ const out = {};
213
+ for (const l of set) {
214
+ if (l.keys?.length === 1)
215
+ out[l.name] = ts.flatMap(x => ts.flatMap(y => (json(x) === json(y) ? [] : [x, y])));
216
+ else if (l.keys?.length === 2)
217
+ out[l.name] = ts.flatMap(x => ts.flatMap(y => ts.flatMap(z => (json(y) === json(z) ? [] : [x, y, z]))));
218
+ else if (l.forall)
219
+ out[l.name] = [...ts, ...wits.map(v)];
220
+ }
221
+ for (const [f, q] of Object.entries(m.step.flags ?? {}))
222
+ if (q.op === 'all' && !q.keys?.length)
223
+ out[`?${f}`] = [...wits.map(v), ...m.inputs.map(v)];
224
+ return out;
225
+ };
226
+ // The goals' certificates: first with no instances of the lemma, then with the cells' (one set of witnesses a law).
227
+ let ok = true;
228
+ for (const pass of [0, 1]) {
229
+ const wits0 = pass ? Array.from({ length: 10 }, (_, i) => `w$${i}`) : [];
230
+ instances[law.name] = inst(wits0);
231
+ ok = true;
232
+ for (const { goal, decls } of countedObligations(m, set, instances, set.indexOf(law))) {
233
+ const c = pass ? certFor(goal, decls) : { reads: [], insts: [] };
234
+ const gg = mcGoal(goal.hyps, decls, c);
235
+ const o = gg && grow(gg, new Map(), { nodes: 0, until: Math.min(until, clock() + 10_000) });
236
+ if (!o || !('tree' in o)) {
237
+ ok = false;
238
+ if (env.GDP_COUNTS_TRACE && pass)
239
+ console.error(`counts: ${goal.name}: ${gg ? json(o).slice(0, 300) : 'a read of no count'} (reads ${c.reads.map(r => `${r[1]}[${json(r[2])}]`).join(' ')})`);
240
+ break;
241
+ }
242
+ certs[goal.name] = { reads: c.reads, insts: c.insts, tree: o.tree };
243
+ }
244
+ if (ok)
245
+ break;
246
+ }
247
+ if (!ok)
248
+ failed.add(law.name);
249
+ }
250
+ if (!failed.size) {
251
+ const proof = { instances, certs };
252
+ return checkCountedLaws(m, set, proof) ? { proven: true, laws: set, m, proof } : { proven: false, laws: set, m, why: 'the kernel refused the set' };
253
+ }
254
+ if (caller.some(l => failed.has(l.name)) && set.length === caller.length)
255
+ return { proven: false, laws: set, m, why: `not proven: ${[...failed].join(', ')}` };
256
+ const next = set.filter(l => !failed.has(l.name) || caller.includes(l));
257
+ if (next.length === set.length) {
258
+ // only callers fail: drop nothing more, give up
259
+ return { proven: false, laws: set, m, why: `not proven: ${[...failed].join(', ')}` };
260
+ }
261
+ set = next;
262
+ }
263
+ return { proven: false, laws: set, m, why: 'time' };
264
+ }
@@ -528,6 +528,10 @@ type Spec = {
528
528
  nodes?: [string, Kind<unknown>, string[], Record<string, NodeFold<unknown, string>>][];
529
529
  kinded?: [string, Kind<unknown>][];
530
530
  carried?: string[];
531
+ counts?: [string, (env: never) => {
532
+ below: TermLike;
533
+ body: (x: Term, k: Term) => Cond | TermLike;
534
+ }][];
531
535
  seqs?: string[];
532
536
  seqTables?: string[];
533
537
  lists2?: [string, Kind<unknown>, Record<string, ListFold<unknown>>, Record<string, ListLemma>][];
@@ -601,6 +605,12 @@ export declare class Rule<P extends Obj = {}, I extends Obj = {}, S extends Obj
601
605
  carries<const N extends string>(...names: N[]): Rule<P, I & {
602
606
  [k in N]: MapRef;
603
607
  }, S, M, F, R, Su, Q>;
608
+ counts<T extends Record<string, (env: P & I & S & M) => {
609
+ below: TermLike;
610
+ body: (x: Term, k: Term) => Cond | TermLike;
611
+ }>>(cs: T): Rule<P, I & {
612
+ [k in keyof T]: MapRef;
613
+ }, S, M, F, R, Su, Q>;
604
614
  carriesSeq<const N extends string>(...names: N[]): Rule<P, I & {
605
615
  [k in N]: SeqRef;
606
616
  }, S, M, F, R, Su, Q>;
package/dist/core/dsl.js CHANGED
@@ -15,6 +15,7 @@
15
15
  //
16
16
  // A step returns its updates as one object: every right-hand side reads the state before the step, as the kernel and
17
17
  // both runtimes do.
18
+ import { searchCounted } from "./counts.js";
18
19
  import { argsKey, machineTerms, carriedView, compileFunction, divName, divisor, divisorsIn, evalC, evalE, interpret, isArithmetic, loadJs, modName, numbersOf, pairedArgs, seeded, withArithmetic } from "./machine.js";
19
20
  import { allowed, keysOf, requestEnv, watch, watchWork } from "./watch.js";
20
21
  import { someHolds, substVars, substVarsE } from "./exists.js";
@@ -1811,6 +1812,12 @@ export class Rule {
1811
1812
  facts(f) { return this.with({ facts: [...(this.spec.facts ?? []), f] }); }
1812
1813
  // Maps each request carries whole (a set of names, say: cells 0 or 1), every cell past them 0; read like any map.
1813
1814
  carries(...names) { return this.with({ carried: [...(this.spec.carried ?? []), ...names] }); }
1815
+ // Counts (Machine.counts): `.counts({votes: env => ({below: env.size, body: (x, k) => env.Vote.at(k).eq(x.plus(1))})})`;
1816
+ // each a map no step writes, at x the number of keys k below the bound where the body holds (or its sum), read by the
1817
+ // flags, the assumption and the step at the request's view, and by a law at the state.
1818
+ counts(cs) {
1819
+ return this.with({ counts: [...(this.spec.counts ?? []), ...Object.entries(cs)] });
1820
+ }
1814
1821
  // Sequences each request carries (SeqRef): `.carriesSeq('Path')`, then `Path.at(i)`, `Path.len`, `A.prefixOf(B)`; the
1815
1822
  // request gives each as an array of naturals.
1816
1823
  carriesSeq(...names) {
@@ -2097,6 +2104,8 @@ export class Rule {
2097
2104
  out[n] = k.value(n);
2098
2105
  for (const n of this.spec.carried ?? [])
2099
2106
  out[n] = new MapRef(n, 0);
2107
+ for (const [n] of this.spec.counts ?? [])
2108
+ out[n] = new MapRef(n, 0);
2100
2109
  for (const n of this.spec.seqs ?? []) {
2101
2110
  delete out[`${n}_len`];
2102
2111
  out[n] = new SeqRef(new MapRef(n, 0), v(`${n}_len`));
@@ -2274,6 +2283,10 @@ export class Rule {
2274
2283
  state: Object.fromEntries(s.state.map(([n, init]) => [n, typeof init === 'number' ? termOf(init) : termOf(init(pEnv))])),
2275
2284
  ...(s.maps.length ? { maps: Object.fromEntries(s.maps) } : {}),
2276
2285
  ...(s.carried?.length ? { inputMaps: s.carried } : {}),
2286
+ ...(s.counts?.length ? { counts: Object.fromEntries(s.counts.map(([n, f]) => {
2287
+ const c = f(env), j = `${n}$x`, key = `${n}$k`, b = c.body(v(j), v(key));
2288
+ return [n, { j, key, below: termOf(c.below), body: b instanceof Cond ? { op: 'if', c: b.c, then: { op: 'const', value: 1 }, else: { op: 'const', value: 0 } } : termOf(b) }];
2289
+ })) } : {}),
2277
2290
  step: { ...(Object.keys(flags).length ? { flags } : {}), ...(Object.keys(state).length ? { state } : {}), ...(Object.keys(maps).length ? { maps } : {}) },
2278
2291
  ...(pre.length ? { pre: pre.length === 1 ? pre[0] : { op: 'and', xs: pre } } : {}),
2279
2292
  ...(assume.length ? { assume: assume.length === 1 ? assume[0] : { op: 'and', xs: assume } } : {}),
@@ -2361,7 +2374,7 @@ export class Rule {
2361
2374
  }
2362
2375
  // One step: the flags, the updates and the step laws, each against what the interpreter computed.
2363
2376
  crossStep(params, st, input, next, stepLaws, bound, count) {
2364
- const s = this.spec, m = this.machine, run = interpret(m), seen = carriedView(m, st, input), req = requestEnv(m, run, params, st, input);
2377
+ const s = this.spec, m = this.machine, run = interpret(m), seen = carriedView(m, st, input, undefined, params), req = requestEnv(m, run, params, st, input);
2365
2378
  const keys = keysOf(bound, seen, next), vars = { ...params, ...st.scalars, ...req };
2366
2379
  const sc = { vars, maps: Object.fromEntries(Object.entries(seen.maps).map(([n, cells]) => [n, { cells, dflt: seen.defaults?.[n] ?? m.maps?.[n] ?? 0 }])), keys: exactKeys(keys, vars, seen, next), flags: {} };
2367
2380
  // Flags: every callback in order, each name's last definition winning, until the values settle (a name defined
@@ -2914,6 +2927,11 @@ export function proveRule(r, laws, opts = {}) {
2914
2927
  // (A step law broken so is refused, proveSteps below: it holds from every state the laws allow, reached or not.)
2915
2928
  if (refuted)
2916
2929
  return refuted.run ? refutedVerdict(refuted) : searched(r, laws, [], refutedVerdict(refuted), opts);
2930
+ // A rule with counts: its goals are the counted ones (core/counts.ts searches them; the kernel checks the set).
2931
+ if (r.machine.counts && Object.keys(r.machine.counts).length) {
2932
+ const c = searchCounted(r.machine, withKinds(r, laws), typeof opts.search === 'object' ? opts.search.ms ?? 60_000 : 60_000);
2933
+ return { proven: c.proven, checked: c.proven, ...(c.why ? { why: c.why } : {}), found: { laws: c.laws.map(l => ({ text: l.name })) } };
2934
+ }
2917
2935
  const out = (opts.fast ? proveSetFast : proveLaws)(r.machine, withKinds(r, laws));
2918
2936
  const v = { ...verdictOf(out), ...(out.witnesses && out.proven ? { witnesses: out.witnesses } : {}) };
2919
2937
  return searched(r, laws, [], v, opts);
@@ -70,6 +70,7 @@ export type Machine = {
70
70
  assume?: C;
71
71
  history?: History;
72
72
  sums?: Record<string, Sum>;
73
+ counts?: Record<string, Counted>;
73
74
  fns?: Record<string, Fn>;
74
75
  facts?: Law[];
75
76
  leasts?: Record<string, Least>;
@@ -136,6 +137,12 @@ export type Sum = {
136
137
  key: string;
137
138
  term: E;
138
139
  };
140
+ export type Counted = {
141
+ j: string;
142
+ key: string;
143
+ below: E;
144
+ body: E;
145
+ };
139
146
  export type MapUpdate = {
140
147
  key: E;
141
148
  value: E;
@@ -219,7 +226,7 @@ export declare function evalC(c: C, env: Env, st: State, m: Machine): boolean;
219
226
  export declare function compileE(e: E, m: Machine): (env: Env, st: State) => number;
220
227
  export declare function compileC(c: C, m: Machine): (env: Env, st: State) => boolean;
221
228
  export declare function leastsIn(m: Machine, env: Env, st: State): Env;
222
- export declare function carriedView(m: Machine, st: State, input: Request, rename?: (map: string) => string): State;
229
+ export declare function carriedView(m: Machine, st: State, input: Request, rename?: (map: string) => string, params?: Env): State;
223
230
  export declare const numbersOf: (input: Request) => Record<string, number>;
224
231
  export declare function interpret(m: Machine): {
225
232
  init: (params: Env) => State;
@@ -448,11 +448,26 @@ export function leastsIn(m, env, st) {
448
448
  }
449
449
  const empty = { scalars: {}, maps: {} };
450
450
  // The state as a step reads it: with the maps the request carries (cells past them read 0), each checked natural.
451
- export function carriedView(m, st, input, rename = map => map) {
452
- if (!m.inputMaps?.length)
451
+ // A request's counts (Machine.counts) are read at this view too: each count map's cell at x, computed when read, the sum
452
+ // of its body over the keys below its bound, j at x (CountMachine.lean's cntOf at CReach's view: the params, the request's
453
+ // numbers, the state, the maps it carries).
454
+ class CountCells extends Map {
455
+ at;
456
+ constructor(at) {
457
+ super();
458
+ this.at = at;
459
+ }
460
+ get(x) { let v = super.get(x); if (v === undefined) {
461
+ v = this.at(x);
462
+ super.set(x, v);
463
+ } return v; }
464
+ }
465
+ export function carriedView(m, st, input, rename = map => map, params) {
466
+ const counts = Object.entries(m.counts ?? {});
467
+ if (!m.inputMaps?.length && !counts.length)
453
468
  return st;
454
469
  const maps = { ...st.maps }, defaults = { ...st.defaults };
455
- for (const map of m.inputMaps) {
470
+ for (const map of m.inputMaps ?? []) {
456
471
  const cells = input[map];
457
472
  if (!(cells instanceof Map))
458
473
  throw new RangeError(`input ${map} must be a Map of naturals`);
@@ -463,6 +478,21 @@ export function carriedView(m, st, input, rename = map => map) {
463
478
  maps[rename(map)] = cells;
464
479
  defaults[rename(map)] = 0;
465
480
  }
481
+ if (counts.length) {
482
+ if (!params)
483
+ throw new Error(`${m.name}: a request's counts read the params`);
484
+ const view = { ...st, maps, defaults }, env0 = { ...params, ...numbersOf(input) };
485
+ for (const [c, d] of counts) {
486
+ maps[rename(c)] = new CountCells(x => {
487
+ const e1 = { ...env0, [d.j]: x }, n = evalE(d.below, e1, view, m);
488
+ let sum = 0;
489
+ for (let k = 0; k < n; k++)
490
+ sum = exact(sum + evalE(d.body, { ...e1, [d.key]: k }, view, m));
491
+ return sum;
492
+ });
493
+ defaults[rename(c)] = 0;
494
+ }
495
+ }
466
496
  return { ...st, maps, defaults };
467
497
  }
468
498
  // A request's numbers (its inputs), without the maps it carries.
@@ -482,7 +512,7 @@ export function interpret(m) {
482
512
  env[i] = naturalIn(input[i], `input ${i}`);
483
513
  return env;
484
514
  };
485
- const viewed = (st, input) => carriedView(m, st, input);
515
+ const viewed = (st, input, params) => carriedView(m, st, input, undefined, params);
486
516
  // The records a request's queries read: with pruning, those not yet spent at its order.
487
517
  const live = (env, st) => {
488
518
  const records = st.history;
@@ -530,7 +560,7 @@ export function interpret(m) {
530
560
  return m.leasts ? { ...qs, ...leastsIn(m, { ...env, ...qs }, viewed(st, input)) } : qs;
531
561
  },
532
562
  step: (params, given, input) => {
533
- const env = args(params, input), st = viewed(given, input);
563
+ const env = args(params, input), st = viewed(given, input, params);
534
564
  let records = [];
535
565
  if (h) {
536
566
  ordered(env, st);
@@ -23,7 +23,7 @@ export const allowed = (m, run, params, st, input) => {
23
23
  const order = m.history?.prune?.order;
24
24
  if (order !== undefined && st.last !== undefined && input[order] < st.last)
25
25
  return false;
26
- return !m.assume || evalC(m.assume, requestEnv(m, run, params, st, input), carriedView(m, st, input), m);
26
+ return !m.assume || evalC(m.assume, requestEnv(m, run, params, st, input), carriedView(m, st, input, undefined, params), m);
27
27
  };
28
28
  // The keys a law about every key is read at: 0 to bound + 1, and every key a map holds.
29
29
  export const keysOf = (bound, ...states) => {
@@ -313,6 +313,31 @@ export declare function checkCounted(g: CountedGoal, cert: {
313
313
  tree: Tree;
314
314
  }): boolean;
315
315
  export declare function countedGoal(g: CountedGoal, insts: CountInst[]): Goal | undefined;
316
+ export type CountDecl = {
317
+ map: string;
318
+ j: string;
319
+ key: string;
320
+ below: E;
321
+ body: E;
322
+ };
323
+ export type MapRead = [string, string, E];
324
+ export type CountCert = {
325
+ reads: MapRead[];
326
+ insts: CountInst[];
327
+ tree: Tree;
328
+ };
329
+ export declare const postName: (map: string) => string;
330
+ export declare const stateCounts: (m: Machine) => string[];
331
+ export declare function checkMC(hyps: C[], ds: CountDecl[], k: CountCert): boolean;
332
+ export declare function mcGoal(hyps: C[], ds: CountDecl[], k: Pick<CountCert, 'reads' | 'insts'>): Goal | undefined;
333
+ export declare function countedObligations(m: Machine, laws: Law[], instances?: Record<string, Instances>, only?: number): {
334
+ goal: Goal;
335
+ decls: CountDecl[];
336
+ }[];
337
+ export declare function checkCountedLaws(m: Machine, laws: Law[], proof: {
338
+ instances: Record<string, Instances>;
339
+ certs: Record<string, CountCert>;
340
+ }): boolean;
316
341
  export type GhostMap = {
317
342
  start: number;
318
343
  write: MapUpdate;
@@ -803,7 +803,9 @@ const distinct = (what, names) => { const seen = new Set(); for (const name of n
803
803
  // step reads params, inputs and the state before it; a flag reads the flags declared before it; a start value reads the
804
804
  // params; a law reads the params, the state, the maps and its own key.
805
805
  export function scope(m, laws = []) {
806
- const state = Object.keys(m.state), maps = Object.keys(m.maps ?? {}), flags = Object.keys(m.step.flags ?? {}), carried = m.inputMaps ?? [], fns = Object.keys(m.fns ?? {});
806
+ const state = Object.keys(m.state), maps = Object.keys(m.maps ?? {}), flags = Object.keys(m.step.flags ?? {}), fns = Object.keys(m.fns ?? {});
807
+ // (a count map is read as a map the request carries; a law reads the counts of the state, countsScope says which)
808
+ const counts = Object.keys(m.counts ?? {}), carried = [...(m.inputMaps ?? []), ...counts];
807
809
  const names = [...m.params, ...m.inputs, ...state];
808
810
  distinct(m.name, [...names, ...maps, ...carried, ...fns]);
809
811
  for (const name of [...names, ...maps, ...carried, ...fns, ...flags])
@@ -883,7 +885,8 @@ export function scope(m, laws = []) {
883
885
  }
884
886
  const keysOf = (l) => [...(l.forall ? [l.forall] : []), ...(l.keys ?? [])];
885
887
  for (const law of laws)
886
- inScope(`law ${law.name}`, [law.holds], [...m.params, ...state, ...keysOf(law)], [...maps, ...fns]);
888
+ inScope(`law ${law.name}`, [law.holds], [...m.params, ...state, ...keysOf(law)], [...maps, ...fns, ...stateCounts(m)]);
889
+ countsScope(m, laws);
887
890
  // A fact reads the params and the functions alone: what holds of them holds at every state.
888
891
  for (const fact of facts)
889
892
  inScope(`fact ${fact.name}`, [fact.holds], [...m.params, ...keysOf(fact)], fns);
@@ -1222,6 +1225,9 @@ export function obligations(m, laws, instances = {}, only) {
1222
1225
  const goals = only === undefined ? sideGoals(m, laws) : [];
1223
1226
  return [...obligations(plainOf(m), laws, instances, only), ...goals];
1224
1227
  }
1228
+ // (a count changes with the state: a law reading one is read after the step at its post name, countedObligations')
1229
+ if (m.counts && Object.keys(m.counts).length)
1230
+ throw new Error(`${m.name} counts: its goals are countedObligations'`);
1225
1231
  scope(m, laws);
1226
1232
  const ok = [...Object.values(m.state), ...Object.values(m.step.state ?? {}), ...Object.values(m.step.maps ?? {}).flatMap(w => ('each' in w ? [w.value] : [w.key, w.value]))].every(natural)
1227
1233
  && Object.values(m.step.flags ?? {}).every(naturalC) && laws.every(l => naturalC(l.holds)) && Object.values(m.maps ?? {}).every(c => Number.isInteger(c) && c >= 0);
@@ -2016,6 +2022,157 @@ export function countedGoal(g, insts) {
2016
2022
  const hs = countHyps(g.counts, insts);
2017
2023
  return hs && { name: g.name, hyps: [...g.hyps, ...hs] };
2018
2024
  }
2025
+ export const postName = (map) => `${map}#`;
2026
+ const declsOf = (m) => Object.entries(m.counts ?? {}).map(([map, c]) => ({ map, j: c.j, key: c.key, below: c.below, body: c.body }));
2027
+ // stateOnly: the bound and body read no input and no map a request carries (Lean: avoidsE (extVars ++ flagVars) and
2028
+ // avoidsMapsE carried; a count reads no flag, quantified flag or witness here, countsScope's).
2029
+ const stateOnly = (m, d) => [d.below, d.body].every(t => {
2030
+ const r = reads(t);
2031
+ return m.inputs.every(i => !r.vars.has(i)) && [...(m.inputMaps ?? []), ...Object.keys(m.counts ?? {})].every(mp => !r.maps.has(mp));
2032
+ });
2033
+ export const stateCounts = (m) => Object.entries(m.counts ?? {}).filter(([, d]) => stateOnly(m, d)).map(([c]) => c);
2034
+ // Each count, as Lean's cDeclOk and cApart: its post name none of the machine's; j and key distinct plain names that are
2035
+ // none of its names, bound keys, quantified flags or witnesses, nor a law's key or skolem (k, k#); the bound reading
2036
+ // the params, inputs, state and j, the body those and key, each of the maps, carried maps and functions (no count, no
2037
+ // post name, no flag); naturals only.
2038
+ function countsScope(m, laws) {
2039
+ const counts = m.counts ?? {};
2040
+ if (!Object.keys(counts).length)
2041
+ return;
2042
+ const state = Object.keys(m.state), maps = Object.keys(m.maps ?? {}), carried = m.inputMaps ?? [], fns = Object.keys(m.fns ?? {});
2043
+ const names = [...m.params, ...m.inputs, ...state], declared = [...names, ...maps, ...carried, ...fns, ...Object.keys(counts), ...Object.keys(m.step.flags ?? {})];
2044
+ const bound = [...quantified(m).flatMap(([f, q]) => [`?${f}`, ...witnessesOf(f, q), ...boundOf(q)]), ...Object.values(m.step.maps ?? {}).flatMap(w => ('each' in w ? [w.each] : []))];
2045
+ const lawNames = [...laws, ...(m.facts ?? [])].flatMap(l => [l.forall, ...(l.keys ?? [])].flatMap(k => (k ? [k, `${k}#`] : [])));
2046
+ for (const [c, d] of Object.entries(counts)) {
2047
+ const what = `${m.name}'s count ${c}`;
2048
+ if (declared.includes(postName(c)))
2049
+ throw new Error(`${what}: its post name ${postName(c)} is already a name of ${m.name}`);
2050
+ plainName(what, d.j);
2051
+ plainName(what, d.key);
2052
+ if (d.j === d.key)
2053
+ throw new Error(`${what}: j and key are one name`);
2054
+ for (const x of [d.j, d.key])
2055
+ if ([...declared, ...bound, ...lawNames].includes(x))
2056
+ throw new Error(`${what}: ${x} is already a name of ${m.name} or a law`);
2057
+ unquantified(what, d.below);
2058
+ unquantified(what, d.body);
2059
+ inScope(`${what}'s bound`, [d.below], [...names, d.j], [...maps, ...carried, ...fns]);
2060
+ inScope(`${what}'s body`, [d.body], [...names, d.j, d.key], [...maps, ...carried, ...fns]);
2061
+ if (!natural(d.below) || !natural(d.body))
2062
+ throw new Error(`${what}: a negative constant or factor is outside the kernel`);
2063
+ }
2064
+ }
2065
+ // toCount: a read cell as Count.lean's count (its variable, the declaration with j at the key term); toCounts: each.
2066
+ const toCount = (ds, r) => {
2067
+ const d = ds.find(x => x.map === r[1]);
2068
+ if (!d)
2069
+ return undefined;
2070
+ const at = { vars: { [d.j]: r[2] }, maps: {}, flags: {} };
2071
+ return { v: r[0], key: d.key, below: substE(d.below, at), body: substE(d.body, at) };
2072
+ };
2073
+ function toCounts(ds, rs) {
2074
+ const out = [];
2075
+ for (const r of rs) {
2076
+ const c = toCount(ds, r);
2077
+ if (!c)
2078
+ return undefined;
2079
+ out.push(c);
2080
+ }
2081
+ return out;
2082
+ }
2083
+ const readHyp = (r) => ({ op: '=', a: { op: 'var', name: r[0] }, b: { op: 'get', map: r[1], key: r[2] } });
2084
+ // readFresh: no hypothesis, declaration or key term reads v, and v is no declaration's j or key.
2085
+ const readFresh = (hyps, ds, rs, v) => hyps.every(h => !readsVar(h, v)) && ds.every(d => !readsVar(d.below, v) && !readsVar(d.body, v) && d.j !== v && d.key !== v) && rs.every(r => !readsVar(r[2], v));
2086
+ // readsOk: the variables distinct (cDistinct), each fresh, each key term reading no declaration's key.
2087
+ const readsOk = (hyps, ds, rs) => new Set(rs.map(r => r[0])).size === rs.length && rs.every(r => readFresh(hyps, ds, rs, r[0]) && ds.every(d => !readsVar(r[2], d.key)));
2088
+ // TypeScript's own condition on the certificate, an input from outside: each read a name, a map's name and a term over
2089
+ // the naturals (Lean's E: every constant and factor a safe integer, which `safeTerm` checks), each instance's bound too.
2090
+ const safeTerm = (t) => {
2091
+ if (!t || typeof t !== 'object')
2092
+ return false;
2093
+ const e = t;
2094
+ switch (e.op) {
2095
+ case 'var': return typeof e.name === 'string';
2096
+ case 'const': return Number.isSafeInteger(e.value) && e.value >= 0;
2097
+ case 'mul': return Number.isSafeInteger(e.k) && e.k >= 0 && safeTerm(e.a);
2098
+ case 'get': return typeof e.map === 'string' && safeTerm(e.key);
2099
+ case 'add':
2100
+ case 'sub':
2101
+ case 'min':
2102
+ case 'max':
2103
+ case 'prod': return safeTerm(e.a) && safeTerm(e.b);
2104
+ case 'if': return safeCond(e.c) && safeTerm(e.then) && safeTerm(e.else);
2105
+ default: return false;
2106
+ }
2107
+ };
2108
+ const safeCond = (c) => !!c && typeof c === 'object' && (c.op === '<' || c.op === '<=' || c.op === '=' ? safeTerm(c.a) && safeTerm(c.b)
2109
+ : c.op === 'not' ? safeCond(c.x) : (c.op === 'and' || c.op === 'or') && Array.isArray(c.xs) && c.xs.every(safeCond));
2110
+ const readsTyped = (rs) => Array.isArray(rs) && rs.every(r => Array.isArray(r) && r.length === 3 && typeof r[0] === 'string' && typeof r[1] === 'string' && safeTerm(r[2]));
2111
+ // witFreshW, countedOkW, checkCountedW: Count.lean's checkCounted with each witness fresh for the counts and the
2112
+ // instances' bounds only. A machine's goal may read a witness in its instances of laws, facts and quantified flags,
2113
+ // which hold at every value of a variable the machine never reads (witsOk): CountMachine.lean's countedW_sound asks the
2114
+ // hypotheses at every value of the witnesses.
2115
+ const witFreshW = (cs, is, w) => cs.every(c => c.v !== w && !readsVar(c.below, w) && !readsVar(c.body, w)) && is.every(j => !readsVar(j.below, w));
2116
+ const countedOkW = (cs, is) => { const ws = is.map(i => i.wit); return new Set(ws).size === ws.length && is.every(i => witFreshW(cs, is, i.wit)); };
2117
+ function checkCountedW(hyps, cs, cert) {
2118
+ if (!(countedOkW(cs, cert.insts) && typed(cert.insts)))
2119
+ return false;
2120
+ const hs = countHyps(cs, cert.insts);
2121
+ return hs !== undefined && check({ name: 'counted', hyps: [...hyps, ...hs] }, cert.tree);
2122
+ }
2123
+ // checkMC: each declaration's j and key differ, the reads are fresh, no read is a witness or reads one in its key
2124
+ // term, and checkCountedW accepts the counted goal they make (the goal's hypotheses, each read variable equal to its
2125
+ // cell; Lean's names the hypotheses it uses, each the goal's).
2126
+ export function checkMC(hyps, ds, k) {
2127
+ if (!(ds.every(d => d.j !== d.key) && readsTyped(k.reads) && Array.isArray(k.insts) && k.insts.every(i => !!i && safeTerm(i.below)) && readsOk(hyps, ds, k.reads)))
2128
+ return false;
2129
+ if (!k.reads.every(r => k.insts.every(i => i.wit !== r[0] && !readsVar(r[2], i.wit))))
2130
+ return false;
2131
+ const cs = toCounts(ds, k.reads);
2132
+ return cs !== undefined && checkCountedW([...hyps, ...k.reads.map(readHyp)], cs, { insts: k.insts, tree: k.tree });
2133
+ }
2134
+ // The goal a certificate's tree refutes (what the search and the exporter read), or none.
2135
+ export function mcGoal(hyps, ds, k) {
2136
+ const cs = toCounts(ds, k.reads);
2137
+ return cs && countedGoal({ name: 'counted', hyps: [...hyps, ...k.reads.map(readHyp)], counts: cs }, k.insts);
2138
+ }
2139
+ // The goals of a machine with counts: obligations', each law proven renamed (renLaw), with the counts each declares.
2140
+ export function countedObligations(m, laws, instances = {}, only) {
2141
+ if (m.history || (m.sums && Object.keys(m.sums).length))
2142
+ throw new Error(`${m.name}: counts go with no history and no sums`);
2143
+ scope(m, laws);
2144
+ const ok = [...Object.values(m.state), ...Object.values(m.step.state ?? {}), ...Object.values(m.step.maps ?? {}).flatMap(w => ('each' in w ? [w.value] : [w.key, w.value]))].every(natural)
2145
+ && Object.values(m.step.flags ?? {}).every(naturalC) && laws.every(l => naturalC(l.holds)) && Object.values(m.maps ?? {}).every(c => Number.isInteger(c) && c >= 0);
2146
+ if (!ok || !(m.facts ?? []).every(l => naturalC(l.holds)) || laws.some(l => mentions(l.holds, m.inputs)))
2147
+ throw new Error('a negative constant or factor, or a law about a request, is outside the kernel');
2148
+ const ren = { vars: {}, maps: Object.fromEntries(Object.keys(m.counts ?? {}).map(c => [c, (key) => ({ op: 'get', map: postName(c), key })])), flags: {} };
2149
+ const proven = (law) => { const h = substC(law.holds, ren); return law.forall ? substC(h, { vars: { [law.forall]: { op: 'var', name: `${law.forall}#` } }, maps: {}, flags: {} }) : h; };
2150
+ const all = declsOf(m), st = all.filter(d => stateOnly(m, d));
2151
+ const after = (at) => st.map(d => ({ map: postName(d.map), j: d.j, key: d.key, below: substE(d.below, at), body: substE(d.body, at) }));
2152
+ const pre = preOf(m), u = updateOf(m), assume = m.assume ? [inlineFlags(m, m.assume)] : [];
2153
+ return laws.flatMap((law, i) => {
2154
+ if (only !== undefined && i !== only)
2155
+ return [];
2156
+ const start = given(m, holds(from(startOf(m)), pre), instances[law.name] ?? {});
2157
+ const turn = step(holds(given(m, from(), instances[law.name] ?? {}), [...pre, ...assume, ...assumed(laws, instances[law.name] ?? {}), ...closing(m, instances[law.name] ?? {})]), u);
2158
+ return [{ goal: goal(`${law.name} @start`, start, atEnd(start, proven(law))), decls: after(start.at) },
2159
+ { goal: goal(`${law.name} @step`, turn, atEnd(turn, proven(law))), decls: [...all, ...after(turn.at)] }];
2160
+ });
2161
+ }
2162
+ // witsOk: a certificate's witnesses are names nothing of the machine or its laws reads or binds: none of its names, bound
2163
+ // keys, quantified flags or witnesses, nor a law's key or skolem (Lean's witsOk: fresh for the machine, the precondition
2164
+ // and the laws, no entry's skolem or further key).
2165
+ function witsOk(m, laws, k) {
2166
+ const flags = Object.keys(m.step.flags ?? {});
2167
+ const taken = new Set([...m.params, ...m.inputs, ...Object.keys(m.state), ...Object.keys(m.maps ?? {}), ...(m.inputMaps ?? []), ...Object.keys(m.fns ?? {}), ...Object.keys(m.counts ?? {}), ...flags,
2168
+ ...flags.map(f => `?${f}`), ...quantified(m).flatMap(([f, q]) => [...witnessesOf(f, q), ...boundOf(q)]), ...Object.values(m.step.maps ?? {}).flatMap(w => ('each' in w ? [w.each] : [])),
2169
+ ...[...laws, ...(m.facts ?? [])].flatMap(l => [l.forall, ...(l.keys ?? [])].flatMap(x => (x ? [x, `${x}#`] : [])))]);
2170
+ return Array.isArray(k.insts) && k.insts.every(i => !!i && typeof i.wit === 'string' && !taken.has(i.wit));
2171
+ }
2172
+ // Lean's checkCMachine: every goal has a certificate, its witnesses fresh, and every certificate checks.
2173
+ export function checkCountedLaws(m, laws, proof) {
2174
+ return countedObligations(m, laws, proof.instances).every(({ goal: g, decls }) => { const k = proof.certs[g.name]; return k !== undefined && witsOk(m, laws, k) && checkMC(g.hyps, decls, k); });
2175
+ }
2019
2176
  // SGhostedM.full: the original with each ghost's start and step after its own (Lean: lists appended; here records, whose
2020
2177
  // names smghostOk keeps apart from the original's).
2021
2178
  export function ghostedMachine(g) {
@@ -1,6 +1,6 @@
1
1
  import type { C, E, Law, Machine, Recurrence } from '../core/machine.js';
2
2
  import { type Lin, type Step } from '../core/solver.js';
3
- import { type CountedGoal, type CountInst, type Ghosted, type Fold, type Goal, type Instances, type KInduction, type Liveness, type Loop, type Path, type Recur, type RecurCases, type StepLaw, type Tree } from '../kernel/kernel.js';
3
+ import { type CountCert, type CountedGoal, type CountInst, type Ghosted, type Fold, type Goal, type Instances, type KInduction, type Liveness, type Loop, type Path, type Recur, type RecurCases, type StepLaw, type Tree } from '../kernel/kernel.js';
4
4
  import { proveStepLaws } from '../kernel/prove.js';
5
5
  import { type Cyclic } from '../kernel/cyclic.js';
6
6
  import { leanLibrary } from './library.js';
@@ -34,6 +34,13 @@ export declare function countedToLean(id: string, g: CountedGoal, cert: {
34
34
  what: string;
35
35
  insts: CountInst[];
36
36
  }[]): string;
37
+ export declare function cmachineToLean(id: string, m: Machine, laws: Law[], proof: {
38
+ instances: Record<string, Instances>;
39
+ certs: Record<string, CountCert>;
40
+ }, tampers?: {
41
+ what: string;
42
+ certs: Record<string, CountCert>;
43
+ }[]): string;
37
44
  export declare function machineToLean(id: string, m: Machine, laws: Law[], corollary?: string): string;
38
45
  export declare const TRUE = ".le (.const 0) (.const 0)";
39
46
  export declare const grown: (g: Goal) => Tree;
@@ -1,6 +1,6 @@
1
1
  import { atMost, n, not, pointWrite } from "../core/machine.js";
2
2
  import { add, k, scale, sub } from "../core/solver.js";
3
- import { countedGoal, countHyps, boundOf, caseGoals, check, checkRecur, checkRecurCases, coverGoal, recurGoal, canon, decided, factorsOf, isCell, isMonomial, columnTerm, stateName, termColumn, truth, historyMachine, sumMachine, sumCovers, sumParts, foldObligations, kInductionStart, kInductionSteps, leafConstraints, loopLiveness, loopMachine, linear, livenessHelpful, livenessParts, livenessLevels, livenessRanks, strongly, loopObligations, trueC, obligations, progressObligations, stepLawObligations, substC, witnessesOf, withProducts } from "../kernel/kernel.js";
3
+ import { countedGoal, countedObligations, countHyps, mcGoal, postName, boundOf, caseGoals, check, checkRecur, checkRecurCases, coverGoal, recurGoal, canon, decided, factorsOf, isCell, isMonomial, columnTerm, stateName, termColumn, truth, historyMachine, sumMachine, sumCovers, sumParts, foldObligations, kInductionStart, kInductionSteps, leafConstraints, loopLiveness, loopMachine, linear, livenessHelpful, livenessParts, livenessLevels, livenessRanks, strongly, loopObligations, trueC, obligations, progressObligations, stepLawObligations, substC, witnessesOf, withProducts } from "../kernel/kernel.js";
4
4
  import { chooseLevels, clock, grow, minimal, proveBuilt, proveLaws, proveSetFast, proveStepLaws, withDeadline } from "../kernel/prove.js";
5
5
  import { refinement, refinementSides } from "../core/compose.js";
6
6
  import { leanSurface, leanTerms } from "./lean-terms.js";
@@ -402,6 +402,73 @@ theorem ${id} : ∀ ρ M, (∀ cn ∈ ${id}_goal.counts, cn.Holds ρ M) → ¬
402
402
  -- TAMPERED: ${t.what}. Lean computes the check to false, as kernel.ts refuses it.
403
403
  example : checkCounted ${id}_goal ${instsLit(t.insts)} ${id}_tab ${id}_tree = false := by ${checkBy}`).join('')}`;
404
404
  }
405
+ // A machine with counts through CountMachine.lean's cmachine_sound: Lean builds the goals and the counts they declare;
406
+ // each certificate names the kernel's goal's hypotheses (each one Lean builds), the cells it reads, Count.lean's
407
+ // instances and the tree. The count maps go to Lean as maps the request carries, each with its post name. `tampers`:
408
+ // certificates kernel.ts refuses, which Lean computes to false.
409
+ export function cmachineToLean(id, m, laws, proof, tampers = []) {
410
+ const obl = countedObligations(m, laws, proof.instances), counts = Object.entries(m.counts ?? {});
411
+ const sm = { ...m, counts: undefined, inputMaps: [...(m.inputMaps ?? []), ...counts.map(([cn]) => cn)] };
412
+ const named = machineNames(sm, laws, [], [], {});
413
+ const allCerts = [proof.certs, ...tampers.map(t => t.certs)];
414
+ const goals = obl.map(o => { const g = mcGoal(o.goal.hyps, o.decls, proof.certs[o.goal.name]); if (!g)
415
+ throw new Error(`${id}: ${o.goal.name}: a read of no count`); return g; });
416
+ const certVars = allCerts.flatMap(cs => Object.values(cs).flatMap(k => [...k.reads.flatMap(r => [r[0], ...varsOfE(r[2])]), ...k.insts.flatMap(i => [i.wit, ...varsOfE(i.below)])]));
417
+ const vars = [...new Set([...named.vars, ...counts.flatMap(([, d]) => [d.j, d.key, ...varsOfE(d.below), ...varsOfE(d.body)]), ...laws.map(l => (l.forall ? `${l.forall}#` : '#')),
418
+ ...goals.flatMap(g => g.hyps.flatMap(varsOf)), ...certVars])];
419
+ const maps = [...new Set([...named.maps, ...counts.flatMap(([cn]) => [cn, postName(cn)]), ...goals.flatMap(g => g.hyps.flatMap(mapsOf)),
420
+ ...allCerts.flatMap(cs => Object.values(cs).flatMap(k => k.reads.map(r => r[1])))])];
421
+ const { e, c } = leanTerms(vars, maps, id);
422
+ const ix = (name) => { const j = vars.indexOf(name); if (j < 0)
423
+ throw new Error(`${id}: no variable for ${name}`); return j; };
424
+ const mx = (name) => { const j = maps.indexOf(name); if (j < 0)
425
+ throw new Error(`${id}: no map for ${name}`); return j; };
426
+ const lawIx = (name) => laws.findIndex(l => l.name === name);
427
+ const facts = m.facts ?? [], facts1 = facts.filter(f => !f.keys?.length), factsN = facts.filter(f => f.keys?.length);
428
+ const tuples = (keys, n2) => Array.from({ length: Math.floor(keys.length / n2) }, (_, t) => keys.slice(t * n2, t * n2 + n2));
429
+ const insts = (inst) => Object.entries(inst).filter(([name]) => lawIx(name) >= 0 && !laws[lawIx(name)].keys?.length).flatMap(([name, keys]) => keys.map(key => `(${lawIx(name)}, ${e(key)})`));
430
+ const pinsts = (inst) => Object.entries(inst).filter(([name]) => lawIx(name) >= 0 && laws[lawIx(name)].keys?.length)
431
+ .flatMap(([name, keys]) => tuples(keys, laws[lawIx(name)].keys.length + 1).map(t => `(${lawIx(name)}, ${e(t[0])}, ${list(t.slice(1).map(e))})`));
432
+ const finsts = (inst) => Object.entries(inst).flatMap(([name, keys]) => { const j = facts1.findIndex(f => f.name === name); return j < 0 ? [] : keys.map(key => `(${j}, ${e(key)})`); });
433
+ const pfinsts = (inst) => Object.entries(inst).flatMap(([name, keys]) => {
434
+ const j = factsN.findIndex(f => f.name === name);
435
+ return j < 0 ? [] : tuples(keys, factsN[j].keys.length + 1).map(t => `(${j}, ${e(t[0])}, ${list(t.slice(1).map(e))})`);
436
+ });
437
+ const qinsts = (inst) => Object.entries(inst).filter(([name]) => name.startsWith('?')).flatMap(([f, keys]) => {
438
+ const q = m.step.flags?.[f.slice(1)], n2 = q?.op === 'all' ? boundOf(q).length : 1;
439
+ return tuples(keys, n2).map(t => `(${ix(f)}, ${list(t.map(e))})`);
440
+ });
441
+ // A certificate: the kernel's goal's hypotheses (Lean checks each is one it builds), the reads, the instances, the
442
+ // table and tree of the goal with the reads' and instances' hypotheses after them.
443
+ const certLit = (name, certs) => {
444
+ // (a tampered certificate keeps the table and tree of the one it tampers with)
445
+ const o = obl.find(o2 => o2.goal.name === name), k = certs[name], k0 = proof.certs[name];
446
+ const tt = encode({ name: `${id}: ${name}`, goal: mcGoal(o.goal.hyps, o.decls, k0), tree: k0.tree }, false, true, vars, maps);
447
+ return `⟨${list(o.goal.hyps.map(c))},
448
+ ${list(k.reads.map(r => `(${ix(r[0])}, ${mx(r[1])}, ${e(r[2])})`))},
449
+ ${list(k.insts.map(i => `⟨${ix(i.wit)}, ${e(i.below)}, ${list(i.terms.map(([z, v2]) => `(${int(z)}, ${ix(v2)})`))}, ${int(i.unit)}⟩`))},
450
+ ${tt.tab},
451
+ ${tt.tree}⟩`;
452
+ };
453
+ const entries = (certs) => laws.map(law => {
454
+ const inst = proof.instances[law.name] ?? {};
455
+ return `⟨⟨⟨${c(law.holds)}, ${law.forall ? `some ${ix(law.forall)}` : 'none'}⟩, ${ix(law.forall ? `${law.forall}#` : '#')}, ${list((law.keys ?? []).map(key => String(ix(key))))}, ${list(insts(inst))}, ${list(qinsts(inst))}, ${list(finsts(inst))}, ${list(pinsts(inst))}, ${list(pfinsts(inst))},
456
+ ([], [], .leaf [] [] [] []), ([], [], .leaf [] [] [] [])⟩,
457
+ ${certLit(`${law.name} @start`, certs)},
458
+ ${certLit(`${law.name} @step`, certs)}⟩`;
459
+ });
460
+ return `-- ${m.name}: ${laws.map(l => l.name).join('; ')}, with counts ${counts.map(([cn]) => cn).join(', ')}
461
+ -- (variables ${vars.map((v2, j) => `${j} ${v2}`).join(', ')}; maps ${maps.map((v2, j) => `${j} ${v2}`).join(', ')})
462
+ def ${id}_machine : SMachine := ${machineLit(sm, { e, c }, ix, mx)}
463
+ def ${id}_decls : List CDecl := ${list(counts.map(([cn, d]) => `⟨${mx(cn)}, ${mx(postName(cn))}, ${ix(d.j)}, ${ix(d.key)}, ${e(d.below)}, ${e(d.body)}⟩`))}
464
+ def ${id}_proof : List CEntry := ${list(entries(proof.certs))}
465
+ theorem ${id}_check : checkCMachine ${id}_machine ${id}_decls ${id}_proof = true := by ${checkBy}
466
+ /-- ${laws.map(l => l.name).join('; ')}: each holds in every reachable state, each count map read as the state's count. -/
467
+ theorem ${id}_laws : ∀ ρ M, CReach ${id}_machine ${id}_decls ρ M → ∀ ce ∈ ${id}_proof, ce.e.Holds ρ (withCnt ${id}_decls ρ M) :=
468
+ cmachine_sound ${id}_machine ${id}_decls ${id}_proof ${id}_check${tampers.map(t => `
469
+ -- TAMPERED: ${t.what}. Lean computes the check to false, as kernel.ts refuses it.
470
+ example : checkCMachine ${id}_machine ${id}_decls ${list(entries(t.certs))} = false := by ${checkBy}`).join('')}`;
471
+ }
405
472
  // Whole machines through Kern.machine_sound: Lean builds the goals from the machine; the trees are the kernel's.
406
473
  export function machineToLean(id, m, laws, corollary) {
407
474
  if (m.maps && Object.keys(m.maps).length)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gdp-wired",
3
- "version": "0.34.0",
3
+ "version": "0.35.0",
4
4
  "description": "An automatic prover for stateful rules (budgets, caps, windows, workflows, policies): laws proven with no proof to write, checked again in Lean, counterexamples found on the GPU, the rule shipped as code",
5
5
  "keywords": [
6
6
  "verification",