gdp-wired 0.49.0 → 0.50.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.md +4 -0
  2. package/dist/core/candidate-seeds.d.ts +25 -0
  3. package/dist/core/candidate-seeds.js +90 -0
  4. package/dist/core/chart.js +28 -4
  5. package/dist/core/cli.js +3 -0
  6. package/dist/core/compose.js +4 -3
  7. package/dist/core/count-support.d.ts +1 -0
  8. package/dist/core/count-support.js +23 -2
  9. package/dist/core/counted-candidate-seeds.d.ts +12 -0
  10. package/dist/core/counted-candidate-seeds.js +31 -0
  11. package/dist/core/counts.js +9 -2
  12. package/dist/core/dsl-binders.d.ts +15 -0
  13. package/dist/core/dsl-binders.js +129 -0
  14. package/dist/core/dsl.d.ts +28 -2
  15. package/dist/core/dsl.js +147 -52
  16. package/dist/core/exists.js +2 -1
  17. package/dist/core/field-laws.js +23 -5
  18. package/dist/core/infer.js +10 -5
  19. package/dist/core/laws.js +2 -1
  20. package/dist/core/lift-cli.d.ts +11 -0
  21. package/dist/core/lift-cli.js +113 -0
  22. package/dist/core/proof-output.d.ts +53 -0
  23. package/dist/core/proof-output.js +38 -0
  24. package/dist/core/quorum-laws.js +55 -16
  25. package/dist/kernel/function-instances.d.ts +45 -0
  26. package/dist/kernel/function-instances.js +460 -0
  27. package/dist/kernel/prove.d.ts +12 -3
  28. package/dist/kernel/prove.js +164 -90
  29. package/dist/lean-kernel/axiom-audit.d.ts +11 -0
  30. package/dist/lean-kernel/axiom-audit.js +50 -0
  31. package/dist/lean-kernel/emit.d.ts +25 -2
  32. package/dist/lean-kernel/emit.js +75 -10
  33. package/dist/lean-kernel/legacy-family-order.d.ts +1 -0
  34. package/dist/lean-kernel/legacy-family-order.js +26 -0
  35. package/dist/lean-kernel/library.js +22 -0
  36. package/dist/lean-kernel/lift/counted-source-data.d.ts +7 -0
  37. package/dist/lean-kernel/lift/counted-source-data.js +78 -0
  38. package/dist/lean-kernel/lift/index.d.ts +82 -0
  39. package/dist/lean-kernel/lift/index.js +116 -0
  40. package/dist/lean-kernel/lift/project.d.ts +4 -0
  41. package/dist/lean-kernel/lift/project.js +15 -0
  42. package/dist/lean-kernel/lift/proof-capture.d.ts +104 -0
  43. package/dist/lean-kernel/lift/proof-capture.js +216 -0
  44. package/dist/lean-kernel/lift/proof-codec.d.ts +28 -0
  45. package/dist/lean-kernel/lift/proof-codec.js +299 -0
  46. package/dist/lean-kernel/lift/proof-counted-source.d.ts +16 -0
  47. package/dist/lean-kernel/lift/proof-counted-source.js +68 -0
  48. package/dist/lean-kernel/lift/proof-frontier.d.ts +19 -0
  49. package/dist/lean-kernel/lift/proof-frontier.js +153 -0
  50. package/dist/lean-kernel/lift/proof-graph.d.ts +17 -0
  51. package/dist/lean-kernel/lift/proof-graph.js +130 -0
  52. package/dist/lean-kernel/lift/proof-parts.d.ts +29 -0
  53. package/dist/lean-kernel/lift/proof-parts.js +131 -0
  54. package/dist/lean-kernel/lift/proof-prelude.d.ts +2 -0
  55. package/dist/lean-kernel/lift/proof-prelude.js +38 -0
  56. package/dist/lean-kernel/lift/proof-witness.d.ts +30 -0
  57. package/dist/lean-kernel/lift/proof-witness.js +283 -0
  58. package/dist/lean-kernel/lift/shape.d.ts +5 -0
  59. package/dist/lean-kernel/lift/shape.js +57 -0
  60. package/dist/lean-kernel/lift/source-projection.d.ts +16 -0
  61. package/dist/lean-kernel/lift/source-projection.js +81 -0
  62. package/dist/lean-kernel/lift/source.d.ts +23 -0
  63. package/dist/lean-kernel/lift/source.js +111 -0
  64. package/dist/lean-kernel/lift/witness-alpha.d.ts +9 -0
  65. package/dist/lean-kernel/lift/witness-alpha.js +31 -0
  66. package/dist/lean-kernel/lift-legacy.d.ts +58 -0
  67. package/dist/lean-kernel/lift-legacy.js +84 -0
  68. package/dist/lean-kernel/lift-names.d.ts +22 -0
  69. package/dist/lean-kernel/lift-names.js +36 -0
  70. package/dist/lean-kernel/lift-simulation/index.d.ts +29 -0
  71. package/dist/lean-kernel/lift-simulation/index.js +352 -0
  72. package/dist/lean-kernel/lift-simulation/shape.d.ts +41 -0
  73. package/dist/lean-kernel/lift-simulation/shape.js +173 -0
  74. package/dist/lean-kernel/lift-special/index.d.ts +36 -0
  75. package/dist/lean-kernel/lift-special/index.js +241 -0
  76. package/dist/lean-kernel/lift-special/structural.d.ts +25 -0
  77. package/dist/lean-kernel/lift-special/structural.js +126 -0
  78. package/dist/lean-kernel/lift-typed/index.d.ts +35 -0
  79. package/dist/lean-kernel/lift-typed/index.js +256 -0
  80. package/dist/lean-kernel/lift-typed/roles.d.ts +17 -0
  81. package/dist/lean-kernel/lift-typed/roles.js +170 -0
  82. package/dist/lean-kernel/lift-typed/shape.d.ts +1 -0
  83. package/dist/lean-kernel/lift-typed/shape.js +12 -0
  84. package/dist/lean-kernel/lift.d.ts +30 -0
  85. package/dist/lean-kernel/lift.js +97 -0
  86. package/package.json +8 -2
@@ -1,3 +1,4 @@
1
+ import { retainFrom } from "./proof-output.js";
1
2
  import { searchNow as countedSearchNow, checkWorkEndpoint } from "./wall.js";
2
3
  // Invariants nobody wrote: a law that holds but isn't inductive, proven with laws the search finds. Nothing here is
3
4
  // trusted; what it finds is proven by the kernel with the rule's own laws, as laws of the same rule.
@@ -1034,7 +1035,11 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
1034
1035
  // (GDP_INFER_TRACE=2: each phase's progress too, to stderr)
1035
1036
  if (env.GDP_INFER_TRACE === '2' && !opts.progress)
1036
1037
  opts = { ...opts, progress: (phase, info) => globalThis.process.stderr.write(`[infer ${phase}] ${JSON.stringify(info)}\n`) };
1037
- const t0 = countedSearchNow(), ms = opts.ms ?? 20000, wallUntil = opts.wall ?? t0 + ms, rule = isRule(target) ? target.withSumsOf(laws, stepLaws) : undefined;
1038
+ const t0 = countedSearchNow(), ms = opts.ms ?? 20000, wallUntil = opts.wall ?? t0 + ms;
1039
+ // Divisor declarations are mutable rule metadata. Keep a private copy even
1040
+ // when withSumsOf would return the original rule: candidate search and returned
1041
+ // remainder laws must not add arithmetic facts to the caller's next proof.
1042
+ const rule = isRule(target) ? target.withDivisors().withSumsOf(laws, stepLaws) : undefined;
1038
1043
  // The clock the budgets read (counted milliseconds since the start, or wall time where `timed`), and the stop.
1039
1044
  const timed = !!opts.timed, w0 = work.n, used = { tries: 0, rows: 0, evals: 0, watched: 0, erows: 0, etries: 0 };
1040
1045
  const now = () => (timed ? countedSearchNow() - t0
@@ -1070,7 +1075,7 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
1070
1075
  const m = rule ? rule.machine : target;
1071
1076
  let proofs = 0;
1072
1077
  // The rule (or machine) the kernel proves the candidates with: once a remainder is among them, one that declares
1073
- // div$k and mod$k for its divisors (rule.withDivisors leaves the caller's rule as it was until a found law needs them).
1078
+ // div$k and mod$k for its divisors (all declarations stay on the private rule copy).
1074
1079
  // Only the laws proven read: a search none of whose chosen candidates is a remainder proves with the rule as it is.
1075
1080
  const byDivisors = new Map();
1076
1081
  const forLaws = (ls) => {
@@ -1104,7 +1109,7 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
1104
1109
  const first = opts.first ?? (refuted?.run ? { proven: false, checked: false, stuck: 'sat', ...refuted }
1105
1110
  : opts.cubes ? { proven: false, checked: false } : prove(laws));
1106
1111
  if ((first.proven && first.checked) || first.run)
1107
- return { ...first, found: [], stats: stats(0, 0, 0) };
1112
+ return retainFrom({ ...first, found: [], stats: stats(0, 0, 0) }, [first]);
1108
1113
  // --- runs ------------------------------------------------------------------------------------------------------------
1109
1114
  const run = interpret(m), stepSample = sampleStep(m, run), rand = seeded(17), kinds = rule ? rule.kindsOfState() : [];
1110
1115
  const given = rule ? [...rule.kindLaws().filter(k => !laws.some(l => l.name === k.name)), ...laws] : laws;
@@ -2729,7 +2734,7 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
2729
2734
  return { used, g: g };
2730
2735
  };
2731
2736
  let at = inst;
2732
- const { result } = withModels(mm, ls, inst, i2 => (at = i2, goalOf(i2)), gs => ask(gs, at), x => (mapNames.length && x.stuck === 'sat' && x.witness ? { goal: x.g, w: x.witness } : undefined), x => !!x.used || x.stuck === 'sat');
2737
+ const { result } = withModels(mm, ls, inst, i2 => (at = i2, goalOf(i2)), gs => ask(gs, at), x => (mapNames.length && x.stuck === 'sat' && x.witness ? { goal: x.g, w: x.witness } : undefined), x => !!x.used || (x.stuck === 'sat' && !!x.witness), (x, _why) => ({ g: x.g, stuck: 'unknown' }));
2733
2738
  return result.used ? { used: result.used } : { stuck: result.stuck, witness: result.witness };
2734
2739
  };
2735
2740
  const stateOf = (w) => {
@@ -5337,5 +5342,5 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
5337
5342
  if (kept.length)
5338
5343
  rule?.dividesBy(...kept);
5339
5344
  trace('end', { proven: true, stopped: stop(), found: chosen.map(f => textOf(f)).join('; ') });
5340
- return { ...last, found: [...chosen.map(f => { const law = lawFor(f), text = law.name, source = sourceOf(f, text); return { law, text, ...(source ? { source } : {}) }; }), ...(enumProof ? enumSome : []).map(law => ({ law, text: law.name }))], stats: stats(samples.length, forms.length, alive.length) };
5345
+ return retainFrom({ ...last, found: [...chosen.map(f => { const law = lawFor(f), text = law.name, source = sourceOf(f, text); return { law, text, ...(source ? { source } : {}) }; }), ...(enumProof ? enumSome : []).map(law => ({ law, text: law.name }))], stats: stats(samples.length, forms.length, alive.length) }, [last], { kind: 'inference', original: m, laws });
5341
5346
  }
package/dist/core/laws.js CHANGED
@@ -28,6 +28,7 @@
28
28
  // in it, the same item, not an equal one), at every two (or three) at once
29
29
  // mode == "closed", outcome == SLOW_ERROR, mode == :closed a choice by its value
30
30
  import { Choice, Int, Str, Term, all, any, forall, no, not, yes } from "./dsl.js";
31
+ import { copyVariable } from "./dsl-binders.js";
31
32
  import { attachNativeLaw } from "./source-check.js";
32
33
  import { nativeLaw } from "./native-law.js";
33
34
  import { agreement, isolation, noninterference } from "./relational.js";
@@ -431,7 +432,7 @@ function val(e, c, names, dry) {
431
432
  if (one instanceof Int) {
432
433
  // (after the step: the sums over the map before it, as the state after it holds them, primed)
433
434
  const after = (m.env ?? c.a) === c.a && c.step && c.a !== c.b, src = (after ? c.b[m.n.rule] : map);
434
- const sumOf = (part) => { const t = src.sum(cell => cell[fs[0]][part]); return after && t.e.op === 'var' ? new Term({ op: 'var', name: `${t.e.name}'` }) : t; };
435
+ const sumOf = (part) => { const t = src.sum(cell => cell[fs[0]][part]); return after && t.e.op === 'var' ? new Term(copyVariable(t.e, { op: 'var', name: `${t.e.name}'` })) : t; };
435
436
  return { t: 'num', v: new Int(sumOf('pos'), sumOf('neg')) };
436
437
  }
437
438
  return { t: 'num', v: Int.of(map.sum(cell => cell[fs[0]])) };
@@ -0,0 +1,11 @@
1
+ export interface LiftArguments {
2
+ capsule: string;
3
+ source: string;
4
+ out?: string;
5
+ sha256?: string;
6
+ emitOnly: boolean;
7
+ json: boolean;
8
+ timeoutMs: number;
9
+ }
10
+ export declare function parseLiftArguments(argv: string[]): LiftArguments;
11
+ export declare function liftMain(argv: string[]): Promise<number>;
@@ -0,0 +1,113 @@
1
+ // Node-only command adapter. The capsule is data, never an executable module.
2
+ import { createHash } from 'node:crypto';
3
+ import { spawnSync } from 'node:child_process';
4
+ import { readFileSync, writeFileSync, lstatSync, realpathSync } from 'node:fs';
5
+ import { basename, isAbsolute, join, resolve, sep } from 'node:path';
6
+ import { lift } from "../lean-kernel/lift.js";
7
+ import { auditLiftLog, gate } from "../lean-kernel/axiom-audit.js";
8
+ export function parseLiftArguments(argv) {
9
+ const positional = [], seen = new Set();
10
+ const options = { capsule: '', source: '', emitOnly: false, json: false, timeoutMs: 1_800_000 };
11
+ for (let i = 0; i < argv.length; i++) {
12
+ const a = argv[i];
13
+ if (!a.startsWith('--')) {
14
+ positional.push(a);
15
+ continue;
16
+ }
17
+ if (seen.has(a))
18
+ throw Error('duplicate lift option: ' + a);
19
+ seen.add(a);
20
+ if (a === '--emit-only')
21
+ options.emitOnly = true;
22
+ else if (a === '--json')
23
+ options.json = true;
24
+ else if (a === '--out' || a === '--sha256' || a === '--timeout-ms') {
25
+ const value = argv[++i];
26
+ if (!value || value.startsWith('--'))
27
+ throw Error('missing value for ' + a);
28
+ if (a === '--out')
29
+ options.out = value;
30
+ else if (a === '--sha256') {
31
+ if (!/^[a-f0-9]{64}$/.test(value))
32
+ throw Error('invalid capsule SHA-256');
33
+ options.sha256 = value;
34
+ }
35
+ else {
36
+ const n = Number(value);
37
+ if (!Number.isSafeInteger(n) || n < 1 || n > 7_200_000)
38
+ throw Error('invalid lift timeout');
39
+ options.timeoutMs = n;
40
+ }
41
+ }
42
+ else
43
+ throw Error('unknown lift option: ' + a);
44
+ }
45
+ if (positional.length !== 2)
46
+ throw Error('usage: gdp-wired lift <capsule> <source.json> [--out DIR] [--emit-only] [--sha256 HASH] [--timeout-ms N] [--json]');
47
+ options.capsule = positional[0];
48
+ options.source = positional[1];
49
+ return options;
50
+ }
51
+ const sha = (data) => createHash('sha256').update(data).digest('hex');
52
+ function verifyFiles(directory, files) {
53
+ if (!files || typeof files !== 'object' || !Object.keys(files).length)
54
+ throw Error('missing emitted file hashes');
55
+ const realRoot = realpathSync(directory);
56
+ for (const [name, digest] of Object.entries(files)) {
57
+ const path = resolve(directory, name);
58
+ if (isAbsolute(name) || !path.startsWith(directory + sep) || !/^[a-f0-9]{64}$/.test(digest))
59
+ throw Error('invalid emitted path/hash: ' + name);
60
+ const stat = lstatSync(path);
61
+ if (!stat.isFile() || stat.isSymbolicLink() || !realpathSync(path).startsWith(realRoot + sep) || sha(readFileSync(path)) !== digest)
62
+ throw Error('emitted file changed: ' + name);
63
+ }
64
+ }
65
+ export async function liftMain(argv) {
66
+ let output;
67
+ try {
68
+ const args = parseLiftArguments(argv);
69
+ output = resolve(args.out ?? basename(args.source).replace(/\.json$/, '') + '.lift');
70
+ const manifest = lift(resolve(args.capsule), resolve(args.source), output, { expectedManifestSha256: args.sha256 });
71
+ if (args.emitOnly) {
72
+ console.log(args.json ? JSON.stringify(manifest) : `EMITTED_NOT_CHECKED: ${output}`);
73
+ return 0;
74
+ }
75
+ const emission = readFileSync(join(output, 'EMITTED.json'));
76
+ verifyFiles(output, manifest.files);
77
+ const commands = [];
78
+ const run = (label, command) => {
79
+ const result = spawnSync(command[0], command.slice(1), { cwd: output, env: { ...process.env, GDP_LEAN_NATIVE: '0' }, encoding: 'utf8', timeout: args.timeoutMs, maxBuffer: 32 * 1024 * 1024, killSignal: 'SIGKILL' });
80
+ const stdout = result.stdout ?? '', stderr = result.stderr ?? '';
81
+ writeFileSync(join(output, label + '.stdout.log'), stdout, { flag: 'wx' });
82
+ writeFileSync(join(output, label + '.stderr.log'), stderr, { flag: 'wx' });
83
+ if (result.error || result.signal || result.status !== 0)
84
+ throw Error(`${label} failed: ${result.error?.message ?? result.signal ?? result.status}`);
85
+ commands.push({ command, exitCode: result.status, stdoutSha256: sha(stdout), stderrSha256: sha(stderr) });
86
+ return stdout + '\n' + stderr;
87
+ };
88
+ const build = run('lift-build', ['lake', 'build']);
89
+ const buildErrors = gate(build, [], false);
90
+ if (buildErrors.length || /\berror:/.test(build))
91
+ throw Error(buildErrors.join('; ') || 'Lean build reported an error');
92
+ const log = run('lift-root', ['lake', 'env', 'lean', 'BapaProof.lean']);
93
+ const declarations = manifest;
94
+ const sourceTheorems = declarations.sourceProjection?.sourceTheorems;
95
+ if (!sourceTheorems?.length)
96
+ throw Error('missing original source theorem coverage');
97
+ const required = declarations.requiredTheorems ?? [declarations.familyTheorem, ...sourceTheorems];
98
+ const axioms = auditLiftLog(log, [readFileSync(join(output, 'BapaProof.lean'), 'utf8')], required);
99
+ verifyFiles(output, manifest.files);
100
+ if (sha(readFileSync(join(output, 'EMITTED.json'))) !== sha(emission))
101
+ throw Error('emission manifest changed during Lean execution');
102
+ const receipt = { schema: 'gdp-lift-check/v1', status: 'SOURCE_CHECKED', scope: 'provided source machine and laws', emissionSha256: sha(emission), files: manifest.files, commands, checkedTheorems: axioms };
103
+ writeFileSync(join(output, 'LIFT-CHECKED.json'), JSON.stringify(receipt, null, 2) + '\n', { flag: 'wx' });
104
+ console.log(args.json ? JSON.stringify(receipt) : `SOURCE_CHECKED: ${sourceTheorems.join(', ')}\n${output}`);
105
+ return 0;
106
+ }
107
+ catch (error) {
108
+ console.error(`gdp-wired lift: ${error instanceof Error ? error.message : String(error)}`);
109
+ if (output)
110
+ console.error(`No source acceptance. Any partial output is retained at ${output}.`);
111
+ return 2;
112
+ }
113
+ }
@@ -0,0 +1,53 @@
1
+ import type { Machine, Law } from './machine.js';
2
+ import type { Instances, Tree } from '../kernel/kernel.js';
3
+ export type ProofOutputNode = {
4
+ kind: 'counted';
5
+ machine: Machine;
6
+ laws: Law[];
7
+ proof: {
8
+ instances: Record<string, Instances>;
9
+ certs: Record<string, import('../kernel/kernel.ts').CountCert>;
10
+ };
11
+ } | {
12
+ kind: 'usual';
13
+ machine: Machine;
14
+ laws: Law[];
15
+ proof: {
16
+ instances: Record<string, Instances>;
17
+ trees: Record<string, Tree>;
18
+ };
19
+ } | {
20
+ kind: 'derived';
21
+ parents: (ProofOutputNode | undefined)[];
22
+ context: unknown;
23
+ };
24
+ export type PublicProofOutput = {
25
+ result: object;
26
+ original: {
27
+ machine: Machine;
28
+ laws: Law[];
29
+ };
30
+ proof: ProofOutputNode | undefined;
31
+ };
32
+ export declare function withPublicRule<T>(run: (outermost: boolean) => T): T;
33
+ export declare const proofOutput: {
34
+ on?: (event: PublicProofOutput) => void;
35
+ };
36
+ export declare function retainFamily<T extends {
37
+ proven: boolean;
38
+ checked: boolean;
39
+ }>(result: T, machine: Machine, laws: Law[], proof: {
40
+ instances: Record<string, Instances>;
41
+ trees: Record<string, Tree>;
42
+ } | undefined): T;
43
+ export declare function retainCounted<T extends object>(result: T, family: {
44
+ proven: boolean;
45
+ m: Machine;
46
+ laws: Law[];
47
+ proof?: {
48
+ instances: Record<string, Instances>;
49
+ certs: Record<string, import('../kernel/kernel.ts').CountCert>;
50
+ };
51
+ }): T;
52
+ export declare function retainFrom<T extends object>(result: T, parents: object[], context?: unknown): T;
53
+ export declare function publishProof<T extends object>(result: T, machine: Machine, laws: Law[]): T;
@@ -0,0 +1,38 @@
1
+ // Synchronous public rule invocations can recursively prove a Skolem family.
2
+ let publicRuleDepth = 0;
3
+ export function withPublicRule(run) {
4
+ const outermost = publicRuleDepth++ === 0;
5
+ try {
6
+ return run(outermost);
7
+ }
8
+ finally {
9
+ publicRuleDepth--;
10
+ }
11
+ }
12
+ let observer;
13
+ let records = new WeakMap();
14
+ // Every installation/clear starts a fresh custody window, even if a callback
15
+ // function is reused. Results from a previous invocation cannot be inherited.
16
+ export const proofOutput = {
17
+ get on() { return observer; },
18
+ set on(value) { records = new WeakMap(); observer = value; }
19
+ };
20
+ export function retainFamily(result, machine, laws, proof) {
21
+ if (proofOutput.on && result.proven && result.checked && proof)
22
+ records.set(result, { kind: 'usual', machine, laws, proof });
23
+ return result;
24
+ }
25
+ export function retainCounted(result, family) {
26
+ if (proofOutput.on && family.proven && family.proof)
27
+ records.set(result, { kind: 'counted', machine: family.m, laws: family.laws, proof: family.proof });
28
+ return result;
29
+ }
30
+ export function retainFrom(result, parents, context = { kind: 'projection' }) {
31
+ if (proofOutput.on)
32
+ records.set(result, { kind: 'derived', parents: parents.map(parent => records.get(parent)), context });
33
+ return result;
34
+ }
35
+ export function publishProof(result, machine, laws) {
36
+ proofOutput.on?.({ result, original: { machine, laws }, proof: records.get(result) });
37
+ return result;
38
+ }
@@ -1,6 +1,6 @@
1
1
  // Untrusted quorum candidates read from a stored row, a majority assumption, and
2
2
  // an action's quantified guard. No protocol vocabulary or facts live here.
3
- import { all, any, atMost, get, ite, less, n, not, plus, same, times, walk, x } from "./machine.js";
3
+ import { all, any, atMost, get, ite, less, n, not, plus, same, times, tuple, walk, x } from "./machine.js";
4
4
  import { substC, substE } from "../kernel/kernel.js";
5
5
  import { env } from "./solver.js";
6
6
  const origins = new WeakMap();
@@ -43,11 +43,13 @@ function rowOf(m, name) {
43
43
  if (cell?.op !== 'get' || !(cell.map in (m.maps ?? {})))
44
44
  return undefined;
45
45
  const k = cell.key;
46
- if (k.op !== 'add' || k.a.op !== 'mul' || k.a.k <= 1 || k.a.a.op !== 'var' || k.b.op !== 'var' || k.b.name !== d.key || !m.inputs.includes(k.a.a.name))
46
+ const packedRow = k.op === 'add' && k.a.op === 'mul' && k.a.k > 1 && k.a.a.op === 'var' && k.b.op === 'var' && k.b.name === d.key ? { input: k.a.a.name, base: k.a.k } : undefined;
47
+ const sorts = m.relations?.[cell.map];
48
+ const tupleRow = k.op === 'tup' && k.a.op === 'var' && k.b.op === 'var' && k.b.name === d.key && sorts?.length === 2 && sorts[0] === sorts[1] ? { input: k.a.name, base: 0 } : undefined;
49
+ const row = packedRow ?? tupleRow;
50
+ if (!row || !m.inputs.includes(row.input) || [d.j, ...m.inputs].some(v => vars(d.below).has(v)))
47
51
  return undefined;
48
- if ([d.j, ...m.inputs].some(v => vars(d.below).has(v)))
49
- return undefined;
50
- return { name, map: cell.map, input: k.a.a.name, base: k.a.k, below: d.below, key: d.key, body };
52
+ return { name, map: cell.map, ...row, below: d.below, key: d.key, body };
51
53
  }
52
54
  export function quorumLaws(m, provenance = env.GDP_COUNT_LIFTED === '1') {
53
55
  const counts = {}, laws = [];
@@ -80,21 +82,51 @@ export function quorumLaws(m, provenance = env.GDP_COUNT_LIFTED === '1') {
80
82
  for (const { row, sets } of rows.values()) {
81
83
  const rowBody = substC(row.body, sub({ [row.input]: x(j), [row.key]: x(key) }));
82
84
  const domain = (v) => less(x(v), row.below);
83
- const registry = new Map();
85
+ const registry = new Map(), pairCounts = new Set();
86
+ // A count map accepts a plain key only. Quantify a single paired natural
87
+ // and project its components in the law; count reads use that key directly.
88
+ const pairLaw = (law) => {
89
+ if (row.base)
90
+ return law;
91
+ const first = { op: 'proj', k: 0, a: x(a) }, second = { op: 'proj', k: 1, a: x(a) };
92
+ const project = substC(law.holds, sub({ [a]: first, [b]: second })), expected = tuple([first, second]);
93
+ let unsupported = false;
94
+ const plain = (t) => {
95
+ if (Array.isArray(t))
96
+ return t.map(plain);
97
+ if (!t || typeof t !== 'object')
98
+ return t;
99
+ const o = t;
100
+ if (o.op === 'get' && pairCounts.has(o.map)) {
101
+ if (!eq(o.key, expected)) {
102
+ unsupported = true;
103
+ return o;
104
+ }
105
+ return { ...o, key: x(a) };
106
+ }
107
+ return Object.fromEntries(Object.entries(o).map(([k, v]) => [k, plain(v)]));
108
+ };
109
+ const keys = law.keys?.filter(k => k !== b), holds = plain(project);
110
+ return unsupported ? undefined : { ...law, ...(keys?.length ? { keys } : { keys: undefined }), holds };
111
+ };
84
112
  const normal = (c) => c.op === 'and' ? text(['and', conjs(c).map(normal).sort()]) : text(c);
85
113
  const count = (body, pair, label) => {
114
+ const pairKey = (a, b) => row.base ? packed(row.base, a, b) : tuple([a, b]);
86
115
  const id = normal(body), old = registry.get(id);
87
116
  if (old)
88
- return (a, b) => get(old.name, old.pair ? packed(row.base, x(old.swap ? b : a), x(old.swap ? a : b)) : x(a));
117
+ return (a, b) => get(old.name, old.pair ? pairKey(x(old.swap ? b : a), x(old.swap ? a : b)) : x(a));
89
118
  const name = fresh(`${row.name}$${label}`);
90
- counts[name] = { j, key, below: row.below, body: indicator(body), ...(pair ? { lo, base: row.base } : {}) };
119
+ const pairBody = pair && !row.base ? substC(body, sub({ [j]: { op: 'proj', k: 0, a: x(j) }, [lo]: { op: 'proj', k: 1, a: x(j) } })) : body;
120
+ counts[name] = { j, key, below: row.below, body: indicator(pairBody), ...(pair && row.base ? { lo, base: row.base } : {}) };
91
121
  registry.set(id, { name, pair, swap: false });
92
- if (pair) {
122
+ if (pair)
123
+ pairCounts.add(name);
124
+ if (pair && row.base) {
93
125
  const swapped = normal(substC(body, sub({ [j]: x(lo), [lo]: x(j) })));
94
126
  if (!registry.has(swapped))
95
127
  registry.set(swapped, { name, pair, swap: true });
96
128
  }
97
- return (a, b) => get(name, pair ? packed(row.base, x(a), x(b)) : x(a));
129
+ return (a, b) => get(name, pair ? pairKey(x(a), x(b)) : x(a));
98
130
  };
99
131
  let size;
100
132
  const rowSize = (a) => (size ??= count(rowBody, false, 'row'))(a);
@@ -138,7 +170,10 @@ export function quorumLaws(m, provenance = env.GDP_COUNT_LIFTED === '1') {
138
170
  continue;
139
171
  const pair = vars(lifted).has(lo), c = count(all(rowBody, ...conjs(lifted)), pair, `${flag}$${bits}`);
140
172
  const atom = (a, b) => atMost(times(2, c(a, b)), rowSize(a));
141
- laws.push({ name: `${row.name}: no quorum ${flag}/${bits}`, forall: a, ...(pair ? { keys: [b] } : {}), holds: any(not(all(domain(a), ...(pair ? [domain(b)] : []))), atom(a, b)) });
173
+ const law = { name: `${row.name}: no quorum ${flag}/${bits}`, forall: a, ...(pair ? { keys: [b] } : {}), holds: any(not(all(domain(a), ...(pair ? [domain(b)] : []))), atom(a, b)) };
174
+ const proposal = pair ? pairLaw(law) : law;
175
+ if (proposal)
176
+ laws.push(proposal);
142
177
  if (!pair)
143
178
  noQuorums.push(a => atom(a));
144
179
  }
@@ -161,15 +196,17 @@ export function quorumLaws(m, provenance = env.GDP_COUNT_LIFTED === '1') {
161
196
  used.add(o.map); });
162
197
  if (used.size !== 1)
163
198
  continue;
164
- const carried = [...used][0], shifted = substE(d.body, sub({ [d.key]: { op: 'sub', a: x(update.each), b: times(row.base, x(row.input)) } }));
199
+ const carried = [...used][0], column = row.base ? { op: 'sub', a: x(update.each), b: times(row.base, x(row.input)) } : { op: 'proj', k: 1, a: x(update.each) };
200
+ const shifted = substE(d.body, sub({ [d.key]: column }));
165
201
  let stores = false;
166
202
  walk(update.value, o => {
167
- if (o.op === 'if' && flagsIn(o.c).has(action) && eq(o.then, shifted))
203
+ if (o.op === 'if' && flagsIn(o.c).has(action) && eq(o.then, shifted) && (row.base || conjs(o.c).some(c => eq(c, same({ op: 'proj', k: 0, a: x(update.each) }, x(row.input))) || eq(c, same(x(row.input), { op: 'proj', k: 0, a: x(update.each) })))))
168
204
  stores = true;
169
205
  // Boolean maps lower an if-tree to disjunctive membership clauses.
170
206
  if (o.op === 'and' && shifted.op === 'if') {
171
207
  const parts = conjs(o);
172
- if (parts.some(c => c.op === 'flag' && c.name === action) && parts.some(c => eq(c, shifted.c)))
208
+ const inRow = row.base || parts.some(c => eq(c, same({ op: 'proj', k: 0, a: x(update.each) }, x(row.input))) || eq(c, same(x(row.input), { op: 'proj', k: 0, a: x(update.each) })));
209
+ if (inRow && parts.some(c => c.op === 'flag' && c.name === action) && parts.some(c => eq(c, shifted.c)))
173
210
  stores = true;
174
211
  }
175
212
  });
@@ -231,7 +268,7 @@ export function quorumLaws(m, provenance = env.GDP_COUNT_LIFTED === '1') {
231
268
  return;
232
269
  const law = { name: `${row.name}: stored guard ${action}/${set}${suffix}`, forall: a, keys: [b, ...free.map((_, i) => i ? w : u)], holds: any(...base, ...extra) };
233
270
  // Metadata builds charged AST nodes too; it must be a no-op while the route is off.
234
- if (provenance) {
271
+ if (provenance && row.base) {
235
272
  const rowRead = rowSize(a), twins = [...mapped].flatMap(([request, value]) => {
236
273
  if (!contains(comparison, { op: 'get', map: request, key: n(0) }))
237
274
  return [];
@@ -244,7 +281,9 @@ export function quorumLaws(m, provenance = env.GDP_COUNT_LIFTED === '1') {
244
281
  if (rowRead.op === 'get')
245
282
  origins.set(law, { kind: 'stored-row-guard', formula: text(law.holds), guard: action, guardFormula: text(guard), membershipMap: row.map, rowInput: row.input, rowCount: rowRead.map, requestSet: carried, width: row.base, halves: free.map((_, i) => i ? w : u), disabled: extra.length > 0, twins, definitions: Object.fromEntries([...used].flatMap(name => { const d = counts[name] ?? m.counts[name]; return d ? [[name, text(d)]] : []; })) });
246
283
  }
247
- laws.push(law);
284
+ const proposal = pairLaw(law);
285
+ if (proposal)
286
+ laws.push(proposal);
248
287
  };
249
288
  add('', []);
250
289
  for (const [i, atom] of noQuorums.entries())
@@ -0,0 +1,45 @@
1
+ import { type Machine } from '../core/machine.js';
2
+ import { type Goal, type Instances } from './kernel.js';
3
+ export type FunctionInstanceSpec = {
4
+ sorts: Readonly<Record<string, string>>;
5
+ functions: Readonly<Record<string, {
6
+ args: readonly string[];
7
+ result?: string;
8
+ }>>;
9
+ maps?: Readonly<Record<string, {
10
+ result: string;
11
+ args?: readonly string[];
12
+ }>>;
13
+ variables?: Readonly<Record<string, string>>;
14
+ limits?: {
15
+ work?: number;
16
+ candidates?: number;
17
+ tuples?: number;
18
+ depth?: number;
19
+ };
20
+ };
21
+ export type FunctionInstanceStats = {
22
+ work: number;
23
+ matched: number;
24
+ generated: number;
25
+ candidates: number;
26
+ cyclic: boolean;
27
+ };
28
+ /** Read-only research telemetry. Inactive means no active discovery scope. */
29
+ export declare const functionInstanceProgress: () => Readonly<FunctionInstanceStats> | undefined;
30
+ /** Synchronous, scoped, default OFF. Limits never become a successful partial
31
+ * search: a cap returns not proven, and the previous context is always restored. */
32
+ export declare function withFunctionInstances<T>(source: FunctionInstanceSpec, run: () => T): {
33
+ status: 'complete';
34
+ value: T;
35
+ stats: FunctionInstanceStats;
36
+ } | {
37
+ status: 'limited';
38
+ proven: false;
39
+ checked: false;
40
+ reason: string;
41
+ stats: FunctionInstanceStats;
42
+ };
43
+ /** An inactive/nonmatching machine takes the existing prover path untouched. */
44
+ export declare function hasFunctionInstances(m: Machine): boolean;
45
+ export declare function extendFunctionInstances(m: Machine, input: Instances, goals: Goal[], legacy?: (machine: Machine, input: Instances, goals: Goal[]) => Instances): Instances;