gdp-wired 0.36.0 → 0.38.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.
@@ -16,7 +16,7 @@ export type Opts = {
16
16
  cert?: string;
17
17
  [k: string]: unknown;
18
18
  };
19
- export type Lang = 'python' | 'ruby' | 'elixir' | 'java' | 'kotlin' | 'go' | 'rust' | 'swift' | 'c' | 'cpp' | 'ts';
19
+ export type Lang = 'python' | 'ruby' | 'elixir' | 'java' | 'kotlin' | 'go' | 'rust' | 'swift' | 'c' | 'cpp' | 'ts' | 'solidity';
20
20
  export declare const LANG_NAME: Record<Lang, string>;
21
21
  type Target = {
22
22
  lang: Lang;
@@ -38,6 +38,7 @@ type LawOut = {
38
38
  kind?: 'law' | 'step' | 'two runs';
39
39
  verdict: 'proven' | 'broken' | 'unknown' | 'not read';
40
40
  run?: string[];
41
+ replayed?: string;
41
42
  why?: string;
42
43
  assumes?: string[];
43
44
  found?: string[];
package/dist/core/cli.js CHANGED
@@ -42,9 +42,9 @@ function args(argv) {
42
42
  return { cmd, targets, o };
43
43
  }
44
44
  const EXT = { '.py': 'python', '.rb': 'ruby', '.ex': 'elixir', '.exs': 'elixir', '.java': 'java', '.kt': 'kotlin', '.go': 'go', '.rs': 'rust', '.swift': 'swift', '.c': 'c', '.h': 'c',
45
- '.cpp': 'cpp', '.cc': 'cpp', '.cxx': 'cpp', '.hpp': 'cpp', '.ts': 'ts', '.mts': 'ts', '.tsx': 'ts', '.js': 'ts', '.mjs': 'ts' };
46
- const COMMENT = { python: '#', ruby: '#', elixir: '#', java: '//', kotlin: '//', go: '//', rust: '//', swift: '//', c: '//', cpp: '//', ts: '//' };
47
- export const LANG_NAME = { python: 'Python', ruby: 'Ruby', elixir: 'Elixir', java: 'Java', kotlin: 'Kotlin', go: 'Go', rust: 'Rust', swift: 'Swift', c: 'C', cpp: 'C++', ts: 'TypeScript' };
45
+ '.cpp': 'cpp', '.cc': 'cpp', '.cxx': 'cpp', '.hpp': 'cpp', '.ts': 'ts', '.mts': 'ts', '.tsx': 'ts', '.js': 'ts', '.mjs': 'ts', '.sol': 'solidity' };
46
+ const COMMENT = { python: '#', ruby: '#', elixir: '#', java: '//', kotlin: '//', go: '//', rust: '//', swift: '//', c: '//', cpp: '//', ts: '//', solidity: '//' };
47
+ export const LANG_NAME = { python: 'Python', ruby: 'Ruby', elixir: 'Elixir', java: 'Java', kotlin: 'Kotlin', go: 'Go', rust: 'Rust', swift: 'Swift', c: 'C', cpp: 'C++', ts: 'TypeScript', solidity: 'Solidity' };
48
48
  function targetsOf(p) {
49
49
  const abs = path.resolve(p);
50
50
  if (!fs.existsSync(abs))
@@ -137,6 +137,10 @@ async function extractWith(t, o) {
137
137
  const { extractC } = await import("./extract-c.js");
138
138
  return extractC(f, o, t.lang === 'cpp');
139
139
  }
140
+ case 'solidity': {
141
+ const { extractSolidity } = await import("./extract-sol.js");
142
+ return extractSolidity(f, { root: up(dir, d => ['foundry.toml', 'hardhat.config.js', 'hardhat.config.ts', 'package.json'].some(m => fs.existsSync(path.join(d, m)))) ?? dir, ...o });
143
+ }
140
144
  case 'ts': {
141
145
  // (Effect and XState run on the package the file's own project has, imported here as the code imports it)
142
146
  const code = fs.readFileSync(f, 'utf8'), file = path.relative(proc.cwd(), f) || f, { createRequire } = proc.getBuiltinModule('node:module');
@@ -285,6 +289,9 @@ async function rulesOf(t, o, laws) {
285
289
  const named = Object.keys(cfg.rules).filter(k => t.files.some(f => new RegExp(`\\b${k.replace(/[^\w]/g, '\\$&')}\\b`).test(fs.readFileSync(f, 'utf8'))));
286
290
  if (named.length)
287
291
  return Promise.all(named.map(k => one(k)));
292
+ // (a contract's file names its contracts: refused with none named, the refusal is the rule's)
293
+ if (t.lang === 'solidity')
294
+ return [first];
288
295
  // (else each class the refusal names, and each function outside a class a law is stated on)
289
296
  const what = first.x.refusals[0]?.what ?? '';
290
297
  const several = /several (?:classes|structs) (?:write their state|written by the file's functions) \(([^)]*)\)/.exec(what)?.[1].split(', ') ?? [];
@@ -296,7 +303,7 @@ function scoped(file) {
296
303
  return lawsIn(text, path.basename(file)).map(l => {
297
304
  let cls, fn;
298
305
  for (let i = l.line - 1; i >= 0 && !cls; i--) {
299
- const m = /\b(?:class|struct|actor|defmodule|module|object|impl|record|interface)\s+([\w.:]+)|\btype\s+(\w+)\s+struct\b/.exec(lines[i].replace(/(#|\/\/).*$/, ''));
306
+ const m = /\b(?:class|struct|actor|defmodule|module|object|impl|record|interface|contract)\s+([\w.:]+)|\btype\s+(\w+)\s+struct\b/.exec(lines[i].replace(/(#|\/\/).*$/, ''));
300
307
  if (m)
301
308
  cls = (m[1] ?? m[2]).split(/[.:]/).pop();
302
309
  }
@@ -387,7 +394,17 @@ function prove(x, l, ms, proven, ctx) {
387
394
  catch (e) {
388
395
  return { ...base, kind, verdict: 'unknown', why: e.message, ms: Date.now() - t0 };
389
396
  }
390
- const verdict = v.proven && v.checked ? 'proven' : v.run ? 'broken' : 'unknown';
397
+ let verdict = v.proven && v.checked ? 'proven' : v.run ? 'broken' : 'unknown', replayed;
398
+ // (a run the front end replays on the code: broken only where the code runs it so)
399
+ if (verdict === 'broken' && x.replay && v.run && !two) {
400
+ const r = x.replay(v.run, b.law);
401
+ if (r.ok)
402
+ replayed = r.what;
403
+ else {
404
+ verdict = 'unknown';
405
+ v.why = `a run breaks it in the rule, not on the code: ${r.what}`;
406
+ }
407
+ }
391
408
  // (a state the laws allow from which a step breaks the law, no run from the start reaching it: shown, not a break)
392
409
  const at = !v.run && v.witness && !two ? (x.names ?? []).filter(n => n.rule && n.rule in v.witness && n.role !== 'const').map(n => `${label(n)} = ${shownValue(x, n.rule, v.witness, n.none)}`) : [];
393
410
  if (verdict === 'proven' && b?.kind === 'law')
@@ -405,7 +422,7 @@ function prove(x, l, ms, proven, ctx) {
405
422
  fs.writeFileSync(cert, JSON.stringify(doc));
406
423
  }
407
424
  }
408
- return { ...base, kind, verdict, ...(v.run ? { run: two ? pairRunOf(x, v.run, two) : runOf(x, v.run) } : {}), ...(verdict === 'unknown' ? { why: [v.why ?? v.stuck ?? 'not proven', ...(at.length ? [`a state the laws allow where a step breaks it, no run from the start found reaching it: ${at.join(', ')}`] : [])].join('; ') } : {}),
425
+ return { ...base, kind, verdict, ...(replayed ? { replayed } : {}), ...(v.run && verdict === 'broken' ? { run: two ? pairRunOf(x, v.run, two) : runOf(x, v.run) } : {}), ...(verdict === 'unknown' ? { why: [v.why ?? v.stuck ?? 'not proven', ...(at.length ? [`a state the laws allow where a step breaks it, no run from the start found reaching it: ${at.join(', ')}`] : [])].join('; ') } : {}),
409
426
  ...(v.run && !two ? { assumes: assumedOf(x, v.run) } : {}), ...(found?.length ? { found } : {}), ...(cert ? { cert } : {}), ms: Date.now() - t0 };
410
427
  }
411
428
  // Two runs as calls of the code: each request once, the values the two runs take apart as `a | b`, and the run b leaves
@@ -566,6 +583,8 @@ function printRule(r, o) {
566
583
  if (l.run)
567
584
  for (const [i, s] of l.run.entries())
568
585
  out(` ${i === 0 ? 'run: ' : ' '}${paint('red', s)}`);
586
+ if (l.replayed)
587
+ out(` ${l.replayed}`);
569
588
  for (const a of l.assumes ?? [])
570
589
  out(` ${a}`);
571
590
  if (l.found)
@@ -1,12 +1,9 @@
1
- import { type C, type E, type Law, type Machine, type State } from './machine.js';
1
+ import { type C, type E, type Law, type Machine } from './machine.js';
2
2
  import { type CountCert, type CountInst, type Instances, type MapRead } from '../kernel/kernel.js';
3
- type Env = Record<string, number>;
4
3
  export declare function guardLaws(m: Machine): {
5
4
  counts: Machine['counts'];
6
5
  laws: Law[];
7
6
  };
8
- export declare function pairLaws(m: Machine): Law[];
9
- export declare function small(m: Machine, p: Env, b: number, cap?: number): State[];
10
7
  export declare function certFor(goal: {
11
8
  hyps: C[];
12
9
  }, decls: {
@@ -17,6 +14,7 @@ export declare function certFor(goal: {
17
14
  insts: CountInst[];
18
15
  wits: string[];
19
16
  };
17
+ export declare function matched(names: string[], body: C, cells: [string, E][], cap?: number): E[][];
20
18
  export type Counted = {
21
19
  proven: boolean;
22
20
  laws: Law[];
@@ -28,4 +26,3 @@ export type Counted = {
28
26
  why?: string;
29
27
  };
30
28
  export declare function searchCounted(m0: Machine, caller: Law[], ms?: number): Counted;
31
- export {};
@@ -1,21 +1,12 @@
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";
1
+ import { assumed, checkCountedLaws, countedObligations, mcGoal, substC } from "../kernel/kernel.js";
15
2
  import { clock, grow } from "../kernel/prove.js";
3
+ import { REFUTED, growCdcl } from "../kernel/cdcl.js";
4
+ import { inferLaws } from "./infer.js";
5
+ import { holdsAt, small } from "./exists.js";
16
6
  import { env } from "./solver.js";
17
7
  const v = (name) => ({ op: 'var', name }), k = (value) => ({ op: 'const', value });
18
8
  const json = (t) => JSON.stringify(t);
9
+ const knob = { pairs: env.GDP_K_PAIRS === '1', rounds: Number(env.GDP_K_ROUNDS ?? 2), cap: Number(env.GDP_K_CAP ?? 24), ts: env.GDP_K_TS !== '0', keyed: env.GDP_K_KEYED !== '0', flagTs: env.GDP_K_FLAGTS !== '0', shrink: Number(env.GDP_K_SHRINK ?? 150) };
19
10
  const one = k(1), zero = k(0);
20
11
  // Every term t with `get(map, t)` in t0.
21
12
  function reads(t0, map, out = new Map()) {
@@ -79,69 +70,6 @@ export function guardLaws(m) {
79
70
  }
80
71
  return { counts, laws };
81
72
  }
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
73
  // --- a goal's certificate -------------------------------------------------------------------------------------------------
146
74
  // The count cells the goal reads (each before the step with its post name's twin), instances over pairs of them with one
147
75
  // 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
@@ -179,6 +107,78 @@ export function certFor(goal, decls) {
179
107
  add([[1, a[0]], [1, c[0]]], -1, byMap.get(a[1]).below);
180
108
  return { reads: named, insts: insts.slice(0, 10), wits: wits.slice(0, 10) };
181
109
  }
110
+ // --- instances by the goal's own reads (E-matching, as an SMT solver instantiates a quantifier) ------------------------
111
+ // A law over keys (and a quantified flag) is assumed at the tuples where its map reads meet the cells the goal reads: each
112
+ // read of the law, its key a pattern over the law's names, matched against a cell read in the goal (a count's body at a
113
+ // witness included), the tuples one read or two cover; the goal regrown with them, twice at most.
114
+ const ground = (t0, out = new Map()) => {
115
+ const go = (x) => {
116
+ if (!x || typeof x !== 'object')
117
+ return;
118
+ const o = x;
119
+ if (o.op === 'all')
120
+ return;
121
+ if (o.op === 'get')
122
+ out.set(json([o.map, o.key]), [o.map, o.key]);
123
+ for (const y of Object.values(o))
124
+ go(y);
125
+ };
126
+ go(t0);
127
+ return out;
128
+ };
129
+ // (a name a pattern reads twice, as x·N + x, matched by a cell whose two places differ: bound to each, `alt`, so the law
130
+ // is assumed where the goal's cases make them equal)
131
+ function bindKey(p, g, names, b, alt) {
132
+ if (p.op === 'var' && names.includes(p.name)) {
133
+ const x = b[p.name];
134
+ if (!x) {
135
+ b[p.name] = g;
136
+ return true;
137
+ }
138
+ if (json(x) === json(g))
139
+ return true;
140
+ if (!alt || alt[p.name])
141
+ return false;
142
+ alt[p.name] = g;
143
+ return true;
144
+ }
145
+ if (p.op !== g.op)
146
+ return false;
147
+ const q = g;
148
+ switch (p.op) {
149
+ case 'add':
150
+ case 'sub':
151
+ case 'min':
152
+ case 'max':
153
+ case 'prod': return bindKey(p.a, q.a, names, b, alt) && bindKey(p.b, q.b, names, b, alt);
154
+ case 'mul': return p.k === q.k && bindKey(p.a, q.a, names, b, alt);
155
+ case 'var':
156
+ case 'const':
157
+ case 'get':
158
+ case 'if': return json(p) === json(g);
159
+ }
160
+ }
161
+ export function matched(names, body, cells, cap = knob.cap) {
162
+ const pats = [...reads(body, () => true).values()].filter(([, key]) => names.some(nm => mentions(key, nm)));
163
+ const per = pats.map(([mp, key]) => cells.filter(c => c[0] === mp).flatMap(([, g]) => { const b = {}, alt = {}; return bindKey(key, g, names, b, alt) ? [b, ...Object.entries(alt).map(([nm, t]) => ({ ...b, [nm]: t }))] : []; }));
164
+ const out = new Map();
165
+ const put = (b) => { if (names.every(nm => b[nm])) {
166
+ const t = names.map(nm => b[nm]);
167
+ out.set(json(t), t);
168
+ } };
169
+ for (const [i, bs] of per.entries())
170
+ for (const b of bs) {
171
+ put(b);
172
+ for (const c of per.slice(i + 1).flat()) {
173
+ if (out.size >= cap)
174
+ break;
175
+ const m2 = { ...b };
176
+ if (Object.entries(c).every(([nm, t]) => !m2[nm] || json(m2[nm]) === json(t)))
177
+ put(Object.assign(m2, c));
178
+ }
179
+ }
180
+ return [...out.values()].slice(0, cap);
181
+ }
182
182
  export function searchCounted(m0, caller, ms = 60_000) {
183
183
  const until = clock() + ms, g = guardLaws(m0), m = { ...m0, counts: { ...m0.counts, ...g.counts } };
184
184
  // The small instances: each param 2 and 3 (where the precondition allows), inputs and sets below 3.
@@ -195,43 +195,94 @@ export function searchCounted(m0, caller, ms = 60_000) {
195
195
  const most = Math.max(0, ...states.flatMap(({ sts }) => sts.flatMap(st => [...(st.maps[mp]?.values() ?? [])])));
196
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
197
  });
198
- const trueAll = (l) => states.every(({ p, sts }) => sts.every(st => holdsAt(m, l, p, st, 4)));
198
+ const trueAll = (l) => clock() < until && states.every(({ p, sts }) => sts.every(st => holdsAt(m, l, p, st, 4)));
199
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)];
200
+ return { proven: false, laws: caller, m, why: clock() < until ? 'a law fails on the small instances' : 'time' };
201
+ // (the engine's minimal ∀ cubes on its own small instances and data filter, core/infer.ts's: the supports no guard reads)
202
+ const t1 = clock(), cubes = inferLaws(m0, caller, [], { cubes: 2, ms: Math.min(15_000, ms / 4), first: { proven: false, checked: false } }).found.map(f => f.law);
203
+ if (env.GDP_COUNTS_TRACE)
204
+ console.error(`counts: cubes ${cubes.length} in ${Math.round(clock() - t1)} ms: ${cubes.map(l => l.name).join('; ')}`);
205
+ let set = [...caller, ...[...kinds, ...g.laws, ...cubes].filter(trueAll)];
202
206
  if (env.GDP_COUNTS_TRACE)
203
207
  console.error(`counts: candidates ${set.map(l => l.name).join('; ')}`);
204
208
  for (let round = 0; clock() < until; round++) {
205
- const terms = (l) => [...(l.forall ? [v(`${l.forall}#`)] : []), ...(l.keys ?? []).map(v), ...m.inputs.map(v)];
209
+ // (the law's own names and the request's values that key a map: an action's value keys none)
210
+ const keys0 = [...[...reads([m.step, m.assume ?? null], () => true).values()].map(([, key]) => key), ...Object.values(m.step.maps ?? {}).flatMap(w => ('each' in w ? [] : [w.key]))];
211
+ const keyed = m.inputs.filter(i => keys0.some(key => mentions(key, i)));
212
+ const terms = (l) => [...(l.forall ? [v(`${l.forall}#`)] : []), ...(l.keys ?? []).map(v), ...(knob.keyed ? keyed : m.inputs).map(v)];
206
213
  const instances = {}, certs = {}, failed = new Set();
207
214
  for (const law of set) {
208
215
  if (clock() > until)
209
216
  return { proven: false, laws: set, m, why: 'time' };
210
217
  const ts = terms(law);
211
- const inst = (wits) => {
218
+ // (the laws over one key at pairs of the law's own names and the request's, every-key laws at those; the rest, and
219
+ // the witnesses, by the goal's reads below)
220
+ const inst = () => {
212
221
  const out = {};
213
222
  for (const l of set) {
214
- if (l.keys?.length === 1)
223
+ if (l.keys?.length === 1 && knob.pairs)
215
224
  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)];
225
+ else if (!l.keys?.length && l.forall && knob.ts)
226
+ out[l.name] = [...ts];
220
227
  }
221
228
  for (const [f, q] of Object.entries(m.step.flags ?? {}))
222
229
  if (q.op === 'all' && !q.keys?.length)
223
- out[`?${f}`] = [...wits.map(v), ...m.inputs.map(v)];
230
+ out[`?${f}`] = knob.flagTs ? ts : m.inputs.map(v);
224
231
  return out;
225
232
  };
233
+ // (more instances where the goal's reads meet a law's: each keyed law and quantified flag, matched; at most twice)
234
+ const more = (at, hyps) => {
235
+ const cells = [...ground(hyps).values()];
236
+ let grew = false;
237
+ const add = (name, ts2) => {
238
+ const have = new Set(), cur = at[name] ?? [], n = ts2[0]?.length ?? 1;
239
+ for (let i = 0; i + n <= cur.length; i += n)
240
+ have.add(json(cur.slice(i, i + n)));
241
+ for (const t of ts2)
242
+ if (!have.has(json(t))) {
243
+ have.add(json(t));
244
+ at[name] = [...(at[name] ?? []), ...t];
245
+ grew = true;
246
+ }
247
+ };
248
+ for (const l of set)
249
+ if (l.forall)
250
+ add(l.name, matched([l.forall, ...(l.keys ?? [])], l.holds, cells));
251
+ for (const [f, q] of Object.entries(m.step.flags ?? {}))
252
+ if (q.op === 'all' && !q.keys?.length)
253
+ add(`?${f}`, matched([q.key], q.c, cells));
254
+ return grew;
255
+ };
226
256
  // The goals' certificates: first with no instances of the lemma, then with the cells' (one set of witnesses a law).
227
257
  let ok = true;
228
258
  for (const pass of [0, 1]) {
229
- const wits0 = pass ? Array.from({ length: 10 }, (_, i) => `w$${i}`) : [];
230
- instances[law.name] = inst(wits0);
259
+ instances[law.name] = inst();
231
260
  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);
261
+ let built = [];
262
+ for (let r = 0; r <= knob.rounds; r++) {
263
+ built = countedObligations(m, set, instances, set.indexOf(law)).map(({ goal, decls }) => {
264
+ const c = pass ? certFor(goal, decls) : { reads: [], insts: [] };
265
+ return { goal, c, gg: mcGoal(goal.hyps, decls, c) };
266
+ });
267
+ if (r === knob.rounds || !more(instances[law.name], built.map(b => b.gg?.hyps ?? b.goal.hyps)))
268
+ break;
269
+ }
270
+ // (a step goal past a few hundred hypotheses: the CDCL search's refutation first, its core naming the law instances
271
+ // it read; the law's instances cut to those, and its goals grown with them, the certificate's reads kept)
272
+ const step = built.at(-1);
273
+ if (step?.gg && step.gg.hyps.length > knob.shrink) {
274
+ const q = growCdcl(step.gg, new Map(), { nodes: 0, until: Math.min(until, clock() + 5_000) }, { model: true, core: true });
275
+ if (!('tree' in q) && q.why === REFUTED && q.core) {
276
+ const used = new Set(q.core.map(h => json(step.gg.hyps[h]))), at = instances[law.name], cut = {};
277
+ for (const [name, ts2] of Object.entries(at)) {
278
+ const l = set.find(x => x.name === name), n = l ? 1 + (l.keys?.length ?? 0) : 0;
279
+ cut[name] = !l ? ts2 : Array.from({ length: ts2.length / n }, (_, t) => ts2.slice(t * n, t * n + n)).filter(t => used.has(json(assumed([l], { [name]: t })[0]))).flat();
280
+ }
281
+ instances[law.name] = cut;
282
+ built = countedObligations(m, set, instances, set.indexOf(law)).map(({ goal, decls }, j) => ({ goal, c: built[j].c, gg: mcGoal(goal.hyps, decls, built[j].c) }));
283
+ }
284
+ }
285
+ for (const { goal, c, gg } of built) {
235
286
  const o = gg && grow(gg, new Map(), { nodes: 0, until: Math.min(until, clock() + 10_000) });
236
287
  if (!o || !('tree' in o)) {
237
288
  ok = false;
@@ -6,6 +6,8 @@ export declare const namesOf: (t: E | C) => string[];
6
6
  export declare function groupsOf(vars: string[]): Group[];
7
7
  export declare function substVarsE(e: E, s: Record<string, E>): E;
8
8
  export declare function substVars(c: C, s: Record<string, E>): C;
9
+ export declare function small(m: Machine, p: Env, b: number, cap?: number, work?: number): State[];
10
+ export declare function holdsAt(m: Machine, law: Law, p: Env, st: State, b: number): boolean;
9
11
  export declare function someHolds(body: C, vars: string[], env: Env, st: State, m: Machine): {
10
12
  holds: boolean;
11
13
  witness?: Env;