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
package/README.md CHANGED
@@ -578,6 +578,10 @@ const soon = retry.law('the next try is at most 64 after the last request', ({ne
578
578
  `leanProject(file)` a Lake project with the twin, so `lake build` checks them. Each law comes as the twin's theorem and
579
579
  as a plain statement over named variables, e.g. `theorem budget.law0 (h : SReach budget_machine ρ μ) : ρ «s» ≤
580
580
  (ρ «b» + ρ «m»)`, for a Lean development to cite.
581
+ - **Retained proof lifting** (`gdp-wired/lift`): `gdp-wired lift capsule source.json --out proof` generates a fresh
582
+ Lean project from a data-only proof capsule and source model, without invariant search. The default command checks
583
+ the source laws in Lean; `--emit-only` does not claim acceptance. See [the lift guide](docs/lift.md) for supported
584
+ transports, hash-bound receipts, and the boundary between an encoded source theorem and an external specification.
581
585
  - **Composition** (`gdp-wired/compose`): `product(a, b)`, `interleave(a, b)`, `refinement(impl, spec, {relation, witness, stutter})`,
582
586
  `steps(spec, k)` (k spec steps as one, each skippable) and `ghost(m, {name: ever(...) | count(...) | total(m, map, name)})`
583
587
  build plain machines from machines (each side's state named `a_x`, `b_x`). A refinement's laws are the relation, proven
@@ -0,0 +1,25 @@
1
+ import { type Law, type Machine, type SomeWitness } from './machine.js';
2
+ import { proveSetFast } from '../kernel/prove.js';
3
+ import { type Ghosted } from '../kernel/kernel.js';
4
+ type Closure = ReturnType<typeof proveSetFast>;
5
+ type Drop = {
6
+ name: string;
7
+ goal: string;
8
+ stuck: 'sat';
9
+ };
10
+ export type SeedGhosts = Pick<Ghosted, 'vars' | 'maps'>;
11
+ export type SeedResult = {
12
+ status: 'checked';
13
+ laws: Law[];
14
+ kept: Law[];
15
+ dropped: Drop[];
16
+ closure: Closure;
17
+ projection?: 'skolem';
18
+ } | {
19
+ status: 'inconclusive';
20
+ kept: Law[];
21
+ dropped: Drop[];
22
+ reason: string;
23
+ };
24
+ export declare function proveCandidateSeeds(machine: Machine, publicLaws: Law[], candidates: Law[], witnesses?: Record<string, SomeWitness>, ghosts?: SeedGhosts): SeedResult;
25
+ export {};
@@ -0,0 +1,90 @@
1
+ // Retained laws, witness terms and ghost definitions are proposals, never facts.
2
+ import { walk } from "./machine.js";
3
+ import { decideLaw, proveLaw, proveSetFast } from "../kernel/prove.js";
4
+ import { checkGhostedLaws, ghostedMachine, ghostedOk, someOfGhostsOk, substC } from "../kernel/kernel.js";
5
+ import { retainFrom } from "./proof-output.js";
6
+ // The caller imposes the deadline. Only the complete checked family is evidence.
7
+ // In particular neither a witness nor a ghost definition is a caller assumption.
8
+ export function proveCandidateSeeds(machine, publicLaws, candidates, witnesses = {}, ghosts = { vars: {}, maps: {} }) {
9
+ const refuse = (reason) => ({ status: 'inconclusive', kept: [], dropped: [], reason });
10
+ if (Object.keys(machine.counts ?? {}).length)
11
+ return refuse('count-bearing machine requires counted candidate admission');
12
+ const names = new Set();
13
+ for (const law of [...publicLaws, ...candidates]) {
14
+ if (!law.name || names.has(law.name))
15
+ throw Error('candidate family requires unique law names');
16
+ names.add(law.name);
17
+ }
18
+ const someKey = (c, positive = true) => c.op === 'all' ? (!positive || someKey(c.c, positive)) : c.op === 'not' ? someKey(c.x, !positive) : c.op === 'and' || c.op === 'or' ? c.xs.some(x => someKey(x, positive)) : false;
19
+ const supported = new Set(['name', 'holds', 'forall', 'keys']);
20
+ const publicSupported = new Set([...supported, 'some', 'witness']);
21
+ if (candidates.some(l => Object.keys(l).some(k => !supported.has(k)) || someKey(l.holds)) ||
22
+ publicLaws.some(l => Object.keys(l).some(k => !publicSupported.has(k)) || someKey(l.holds)))
23
+ return refuse('existential family requires projection');
24
+ if (Object.keys(witnesses).some(name => !publicLaws.some(l => l.name === name && l.some?.length)))
25
+ return refuse('witness provided for unknown existential law');
26
+ const projecting = publicLaws.some(l => l.some?.length) || Object.keys(ghosts.vars).length > 0 || Object.keys(ghosts.maps).length > 0;
27
+ const G = { orig: machine, vars: ghosts.vars, maps: ghosts.maps };
28
+ const gv = new Set(Object.keys(G.vars)), gm = new Set(Object.keys(G.maps));
29
+ const reserved = new Set([...machine.params, ...machine.inputs, ...Object.keys(machine.state), ...Object.keys(machine.maps ?? {}),
30
+ ...(machine.inputMaps ?? []), ...Object.keys(machine.fns ?? {}), ...Object.keys(machine.step.flags ?? {})]);
31
+ if ([...gv, ...gm].some(n => reserved.has(n)) || [...gv].some(n => gm.has(n)))
32
+ return refuse('ghost name collision');
33
+ let publicReadsGhost = false;
34
+ for (const law of publicLaws)
35
+ walk(law.holds, o => {
36
+ if (o.op === 'var' && gv.has(o.name) || o.op === 'get' && gm.has(o.map) ||
37
+ o.op === 'flag' && gv.has(`?${o.name}`))
38
+ publicReadsGhost = true;
39
+ });
40
+ if (publicReadsGhost)
41
+ return refuse('public law reads a proposed ghost');
42
+ if (projecting && !ghostedOk(G))
43
+ return refuse('ghost definitions not qualified');
44
+ const plains = Object.create(null);
45
+ const plainPublic = [];
46
+ for (const law of publicLaws) {
47
+ if (!law.some?.length) {
48
+ plainPublic.push(law);
49
+ continue;
50
+ }
51
+ const w = witnesses[law.name];
52
+ const sub = w?.terms;
53
+ if (!sub || w.ghost || Object.keys(sub).length !== law.some.length || !law.some.every(n => Object.hasOwn(sub, n)))
54
+ return refuse(`complete witness terms required for ${law.name}`);
55
+ const plain = { name: law.name, holds: substC(law.holds, { vars: Object.assign(Object.create(null), sub), maps: {}, flags: {} }),
56
+ ...(law.forall ? { forall: law.forall } : {}), ...(law.keys ? { keys: law.keys } : {}) };
57
+ if (!someOfGhostsOk(G, law, plain, sub))
58
+ return refuse(`existential projection not qualified: ${law.name}`);
59
+ plains[law.name] = { plain, sub };
60
+ plainPublic.push(plain);
61
+ }
62
+ const working = projecting ? ghostedMachine(G) : machine;
63
+ let kept = [...candidates];
64
+ const dropped = [];
65
+ for (;;) {
66
+ const family = [...plainPublic, ...kept];
67
+ let removed = false;
68
+ for (let i = 0; i < kept.length; i++) {
69
+ const decision = decideLaw(working, family, plainPublic.length + i) ?? proveLaw(working, family, plainPublic.length + i);
70
+ if (!decision.proven) {
71
+ if (decision.stuck !== 'sat')
72
+ return { status: 'inconclusive', kept, dropped, reason: `undecided candidate: ${kept[i].name}: ${decision.stuck}${'why' in decision && decision.why ? `: ${decision.why}` : ''}` };
73
+ dropped.push({ name: kept[i].name, goal: decision.goal, stuck: 'sat' });
74
+ kept = kept.filter((_, j) => j !== i);
75
+ removed = true;
76
+ break;
77
+ }
78
+ }
79
+ if (!removed)
80
+ break;
81
+ }
82
+ const family = [...plainPublic, ...kept];
83
+ const whole = proveSetFast(working, family);
84
+ if (!whole.proven || !whole.checked || !whole.proof)
85
+ return { status: 'inconclusive', kept, dropped, reason: whole.failed?.goal ?? 'whole-family proof not checked' };
86
+ if (projecting && !checkGhostedLaws(G, family, whole.proof))
87
+ return { status: 'inconclusive', kept, dropped, reason: 'ghosted whole-family proof not checked' };
88
+ const closure = projecting ? retainFrom({ ...whole }, [whole], { kind: 'skolem', original: machine, laws: publicLaws, G, plains, family }) : whole;
89
+ return { status: 'checked', laws: [...publicLaws, ...kept], kept, dropped, closure, ...(projecting ? { projection: 'skolem' } : {}) };
90
+ }
@@ -19,6 +19,7 @@
19
19
  import { Choice, Cond, Term, all, any, no, oneOf, proveRule, proveSteps, rule, when, yes } from "./dsl.js";
20
20
  import { interpret, numbersOf } from "./machine.js";
21
21
  import { allowed } from "./watch.js";
22
+ import { reservedName } from "./dsl-binders.js";
22
23
  export class Chart {
23
24
  s;
24
25
  constructor(s) {
@@ -71,8 +72,31 @@ export class Chart {
71
72
  }
72
73
  };
73
74
  walk('', root);
74
- return { name, field: single ? s.field ?? 'state' : name, leaves, finals, compounds };
75
+ return { name, field: single ? s.field ?? 'state' : name, leaves, finals, compounds, historyFields: new Map() };
75
76
  });
77
+ // Allocate readable legacy names first, before fallbacks, so an encoded name cannot steal one.
78
+ // Include every declared field and generated flag: history is storage, never an alias for user data.
79
+ const usedNames = new Set([...regions.map(r => r.field), ...Object.keys(s.params), ...Object.keys(s.inputs),
80
+ ...Object.keys(s.context), ...Object.keys(s.outputs), 'event', ...s.on.flatMap((_, i) => [`on${i}`, `take${i}`])]);
81
+ const histories = regions.flatMap(r => [...r.compounds].filter(([c, v]) => c && v.history).map(([c]) => ({ r, c })));
82
+ for (const { r, c } of histories) {
83
+ const legacy = `${r.field}.last.${c}`;
84
+ if (!reservedName(legacy) && !usedNames.has(legacy)) {
85
+ r.historyFields.set(c, legacy);
86
+ usedNames.add(legacy);
87
+ }
88
+ }
89
+ // Encode UTF-16 code units (including lone surrogates) injectively, in a namespace outside `.last.`.
90
+ const hex = (x) => Array.from({ length: x.length }, (_, i) => x.charCodeAt(i).toString(16).padStart(4, '0')).join('');
91
+ for (const { r, c } of histories)
92
+ if (!r.historyFields.has(c)) {
93
+ const base = `gdp$chart$history$${hex(r.field)}$${hex(c)}`;
94
+ let name = base, n = 0;
95
+ while (usedNames.has(name))
96
+ name = `${base}$${++n}`;
97
+ r.historyFields.set(c, name);
98
+ usedNames.add(name);
99
+ }
76
100
  // A path as the region and the state within it.
77
101
  const locate = (path) => {
78
102
  if (single)
@@ -107,7 +131,7 @@ export class Chart {
107
131
  });
108
132
  // Most specific source first, then the order declared: the first enabled in this order is taken.
109
133
  placed.sort((a, b) => b.depth - a.depth || a.order - b.order);
110
- const lastOf = (r, c) => `${r.field}.last${c ? `.${c}` : ''}`;
134
+ const lastOf = (r, c) => r.historyFields.get(c);
111
135
  const state = {};
112
136
  for (const r of regions) {
113
137
  const kind = oneOf(...r.leaves), enter = (path) => { const c = r.compounds.get(path); return c ? enter(path ? `${path}.${c.initial}` : c.initial) : path; };
@@ -188,7 +212,7 @@ export class Chart {
188
212
  const [head, ...rest] = single ? ['state', ...compound.split('.')] : compound.split('.'), r = regions.find(x => x.name === head), c = rest.join('.');
189
213
  if (!r?.compounds.get(c)?.history)
190
214
  throw new Error(`${this.s.name}: ${compound} keeps no history`);
191
- return env[`${r.field}.last.${c}`];
215
+ return env[r.historyFields.get(c)];
192
216
  }
193
217
  wrap(env) { return Object.assign(Object.create(null), env, { in: (p) => this.in(env, p), last: (c) => this.last(env, c) }); }
194
218
  law(name, f) { return this.rule.law(name, (env) => f(this.wrap(env))); }
@@ -199,7 +223,7 @@ export class Chart {
199
223
  // laws `prove` and `check` are given (as a rule's kind laws are), since a law about entering a compound may need it.
200
224
  chartLaws() {
201
225
  const { rule: r, regions } = this.build();
202
- return regions.flatMap(reg => [...reg.compounds].filter(([c, { history }]) => history && c).map(([c]) => r.law(`${reg.name === 'state' ? '' : `${reg.name}.`}${c} remembers one of its own states`, (env) => any(...reg.leaves.filter(l => l.startsWith(`${c}.`)).map(l => env[`${reg.field}.last.${c}`].is(l))))));
226
+ return regions.flatMap(reg => [...reg.compounds].filter(([c, { history }]) => history && c).map(([c]) => r.law(`${reg.name === 'state' ? '' : `${reg.name}.`}${c} remembers one of its own states`, (env) => any(...reg.leaves.filter(l => l.startsWith(`${c}.`)).map(l => env[reg.historyFields.get(c)].is(l))))));
203
227
  }
204
228
  prove(laws = [], stepLaws = [], opts = {}) { const given = [...this.chartLaws(), ...laws]; return stepLaws.length ? proveSteps(this.rule, given, stepLaws, opts) : proveRule(this.rule, given, opts); }
205
229
  // --- the checks a chart's author expects -------------------------------------------------------------------------
package/dist/core/cli.js CHANGED
@@ -1102,6 +1102,7 @@ function printRule(r, o) {
1102
1102
  }
1103
1103
  const label = (n) => (n.role === 'answer' ? `${n.code.split('.').pop()}(...)` : n.role === 'input' && n.method ? `${n.method}(${n.code})` : n.role === 'result' && n.method ? `${n.method}() result` : n.code);
1104
1104
  const USAGE = `gdp-wired check <file|dir>... [--entry X] [--mode standalone] [--methods a,b] [--failures kept] [--on-error discard] [--json] [--ms 10000] [--no-propose] [--clock s|ms] [--cert <dir>] [--from any] [--require-review] [--security]
1105
+ gdp-wired lift <capsule> <source.json> [--out DIR] [--emit-only] [--sha256 HASH] [--json]
1105
1106
  gdp-wired mutate <config.json> [--json]
1106
1107
  gdp-wired draft <file> --clause <text> | --clause-file <file> --cite <ref> [--llm <command> | --answer <file>] [--by <who>]
1107
1108
 
@@ -1178,6 +1179,8 @@ async function draft(target, o) {
1178
1179
  // Every target's rules and their laws, and the exit code (1: a stated law broken; 2: one not checked, or with
1179
1180
  // --require-review, one cited unreviewed).
1180
1181
  export async function main(argv) {
1182
+ if (argv[0] === 'lift')
1183
+ return (await import("./lift-cli.js")).liftMain(argv.slice(1));
1181
1184
  const { cmd, targets, o } = args(argv);
1182
1185
  if (cmd === 'mutate' && targets.length === 1) {
1183
1186
  const { checkMutations } = await import("./mutate.js");
@@ -14,9 +14,10 @@
14
14
  import { all, any, bit, not, same, unreachable, x } from "./machine.js";
15
15
  import { substC, substE } from "../kernel/kernel.js";
16
16
  import { nameQuantifiers } from "./dsl.js";
17
+ import { copyVariable, generatedVariable } from "./dsl-binders.js";
17
18
  function rename(e, prefix, m, inputs) {
18
19
  switch (e.op) {
19
- case 'var': return m.params.includes(e.name) ? e : m.inputs.includes(e.name) ? (inputs[e.name] ?? e) : x(`${prefix}${e.name}`);
20
+ case 'var': return m.params.includes(e.name) ? e : m.inputs.includes(e.name) ? (inputs[e.name] ?? e) : copyVariable(e, x(`${prefix}${e.name}`));
20
21
  case 'const': return e;
21
22
  case 'mul': return { ...e, a: rename(e.a, prefix, m, inputs) };
22
23
  case 'if': return { op: 'if', c: renameC(e.c, prefix, m, inputs), then: rename(e.then, prefix, m, inputs), else: rename(e.else, prefix, m, inputs) };
@@ -54,10 +55,10 @@ function renamed(m, p, inputs, stays) {
54
55
  maps: Object.fromEntries(Object.entries(m.maps ?? {}).map(([n, v]) => [`${p}${n}`, v])),
55
56
  step: {
56
57
  flags: Object.fromEntries(Object.entries(m.step.flags ?? {}).map(([n, c]) => [`${p}${n}`, renameC(c, p, m, inputs)])),
57
- state: Object.fromEntries(Object.entries(m.step.state ?? {}).map(([n, e]) => [`${p}${n}`, keep(rename(e, p, m, inputs), x(`${p}${n}`))])),
58
+ state: Object.fromEntries(Object.entries(m.step.state ?? {}).map(([n, e]) => [`${p}${n}`, keep(rename(e, p, m, inputs), generatedVariable(`${p}${n}`))])),
58
59
  maps: Object.fromEntries(Object.entries(m.step.maps ?? {}).map(([n, w]) => {
59
60
  if ('each' in w)
60
- return [`${p}${n}`, { each: `${p}${w.each}`, value: keep(rename(w.value, p, m, inputs), { op: 'get', map: `${p}${n}`, key: x(`${p}${w.each}`) }) }];
61
+ return [`${p}${n}`, { each: `${p}${w.each}`, value: keep(rename(w.value, p, m, inputs), { op: 'get', map: `${p}${n}`, key: generatedVariable(`${p}${w.each}`) }) }];
61
62
  const key = rename(w.key, p, m, inputs);
62
63
  return [`${p}${n}`, { key, value: keep(rename(w.value, p, m, inputs), { op: 'get', map: `${p}${n}`, key }) }];
63
64
  })),
@@ -208,6 +208,7 @@ export declare function reservePool(goal: Goal, decls: CountDecl[], pool: Return
208
208
  key: string;
209
209
  from: string;
210
210
  to: string;
211
+ reason?: "source-freshness";
211
212
  }[];
212
213
  quarantined: CountInst[];
213
214
  baseSize: number;
@@ -822,8 +822,29 @@ export function reservePool(goal, decls, pool, previous, previousDecls, chosen,
822
822
  const forbidden = sourceNames([{ ...goal, hyps: undefined }, decls, full.reads, [...previous.insts, ...full.insts].map(i => i.below)], reservationOpen);
823
823
  for (const n of reservationHypNames(goal.hyps))
824
824
  forbidden.add(n);
825
- if (owner.reserved.has(wit) || forbidden.has(wit))
826
- throw new UnsupportedCountProposal('reservation owned witness capture/source');
825
+ if (owner.reserved.has(wit) || forbidden.has(wit)) {
826
+ // Before acquisition the spelling belongs only to the proposal: a source
827
+ // name is not its binder. Never rewrite the source or a selected pick.
828
+ // Once leased, free HYPS may already mean this witness; those must refuse.
829
+ if ((prior && reservationFree(goal.hyps).has(wit)) || names((previous.picks ?? []).filter((_, i) => chosen.has(oldIds[i])), reservationOpen).has(wit))
830
+ throw new UnsupportedCountProposal('reservation owned witness capture/source');
831
+ const from = wit;
832
+ for (const n of sourceNames([previous, full, goal, decls], reservationOpen))
833
+ fresh.add(n);
834
+ for (const n of owner.reserved)
835
+ fresh.add(n);
836
+ for (const l of [...owner.leases.values(), ...leases.values()])
837
+ fresh.add(l.wit);
838
+ do {
839
+ reservationOpen();
840
+ wit = 'w$' + state.next++;
841
+ } while (fresh.has(wit));
842
+ // Optional picks have no retained meaning: alpha-rename their bound
843
+ // witness occurrences together. A selected pick was refused above.
844
+ full.picks = (full.picks ?? []).map((p, i) => chosen.has(fullIds[i]) ? p : [p[0], p[1].map(t => substE(t, { vars: { [from]: x(wit) }, maps: {}, flags: {} }))]);
845
+ fresh.add(wit);
846
+ renamed.push({ key, from, to: wit, reason: 'source-freshness' });
847
+ }
827
848
  if ([...owner.leases, ...leases].some(([id, l]) => id !== key && l.wit === wit) || full.insts.some(i => i.wit === wit && 'i' + instId(i, full.reads) !== key))
828
849
  throw new UnsupportedCountProposal('reservation different witness owner');
829
850
  if (reservationIdentity(rebound, full.reads, decls) !== identity)
@@ -0,0 +1,12 @@
1
+ import type { Law, Machine } from './machine.js';
2
+ import { type Counted } from './counts.js';
3
+ export type CountedSeedResult = {
4
+ status: 'checked';
5
+ closure: Counted;
6
+ kept: Law[];
7
+ dropped: Law[];
8
+ } | {
9
+ status: 'inconclusive';
10
+ reason: string;
11
+ };
12
+ export declare function proveCountedCandidateSeeds(machine: Machine, publicLaws: Law[], candidates: Law[], ms: number): CountedSeedResult;
@@ -0,0 +1,31 @@
1
+ import { admitCountedFamily } from "./counts.js";
2
+ import { searchWall } from "./wall.js";
3
+ import { checkCountedLaws } from "../kernel/kernel.js";
4
+ import { clock, counted, fullRate, withDeadline, withWall } from "../kernel/prove.js";
5
+ // The machine is the producer with conservative derived count declarations;
6
+ // the caller retains the unchanged source separately for source projection.
7
+ // Only public laws are admission targets. Every returned law is checked again
8
+ // as one family; no unverified proposal is published as a given.
9
+ export function proveCountedCandidateSeeds(machine, publicLaws, candidates, ms) {
10
+ if (!Number.isFinite(ms) || ms <= 0)
11
+ return { status: 'inconclusive', reason: 'invalid budget' };
12
+ const family = [...publicLaws, ...candidates], names = new Set(family.map(l => l.name));
13
+ if (names.size !== family.length || family.some(l => !l.name))
14
+ return { status: 'inconclusive', reason: 'duplicate or empty law name' };
15
+ try {
16
+ return withWall(searchWall(ms), () => counted(fullRate, () => {
17
+ const until = clock() + ms;
18
+ return withDeadline(until, () => {
19
+ const closure = admitCountedFamily(machine, publicLaws, family, new Set(candidates), until);
20
+ if (!closure.proven || !closure.proof)
21
+ return { status: 'inconclusive', reason: closure.why ?? 'counted family not proven' };
22
+ if (closure.m !== machine || !publicLaws.every(l => closure.laws.includes(l)) || closure.laws.some(l => !family.includes(l)) || !checkCountedLaws(closure.m, closure.laws, closure.proof))
23
+ return { status: 'inconclusive', reason: 'counted family custody or kernel check failed' };
24
+ return { status: 'checked', closure, kept: candidates.filter(l => closure.laws.includes(l)), dropped: candidates.filter(l => !closure.laws.includes(l)) };
25
+ });
26
+ }, true));
27
+ }
28
+ catch (error) {
29
+ return { status: 'inconclusive', reason: error instanceof Error ? error.message : String(error) };
30
+ }
31
+ }
@@ -1708,6 +1708,7 @@ export function countedAttempts(m, caller, support, until, structured = true, fo
1708
1708
  // instance by the reads it names, a pick by its read and terms, so the choice outlives the goal's rebuilds)
1709
1709
  const chosen = new Set();
1710
1710
  const selections = new Map();
1711
+ const reservationRenamings = new Map();
1711
1712
  const poolCache = new Map();
1712
1713
  const memberSources = new Map();
1713
1714
  // Demand-driven ranges (Fable b89dd77a / Lane B): retain a goal's demand
@@ -1762,7 +1763,13 @@ export function countedAttempts(m, caller, support, until, structured = true, fo
1762
1763
  selection = { chosen: new Set(ids(pick)), cap: Math.min(10, pick.insts.length + 2), previous: pick, decls, reserve: reservationState(goal, [m, ls, goal], pool), stable: stableState([m, ls, goal]) };
1763
1764
  selections.set(goal.name, selection);
1764
1765
  }
1765
- const full = reservePool(goal, decls, pool0, selection.previous, selection.decls, selection.chosen, selection.reserve, pool, reservation).full;
1766
+ const reserved = reservePool(goal, decls, pool0, selection.previous, selection.decls, selection.chosen, selection.reserve, pool, reservation);
1767
+ const full = reserved.full;
1768
+ if (reserved.record.renamed.length) {
1769
+ const prior = reservationRenamings.get(goal.name) ?? [];
1770
+ reservationRenamings.set(goal.name, [...prior, ...reserved.record.renamed]);
1771
+ countsDump.on?.({ phase: 'reservation-alpha', law: law.name, goal: goal.name, renamings: reserved.record.renamed });
1772
+ }
1766
1773
  const keys = ids(full), lazyRoom = selection.chosen.size < selection.cap;
1767
1774
  const view = chosenView(full, selection.chosen, selection.cap);
1768
1775
  const c = withRanges(goal, decls, selectedCertificate(goal, decls, view, selection.stable, lazyRoom), full.reads);
@@ -2054,7 +2061,7 @@ export function countedAttempts(m, caller, support, until, structured = true, fo
2054
2061
  return refuted(gg, o.witness, at);
2055
2062
  if (!o || !('tree' in o))
2056
2063
  return { stuck: gg ? o.stuck ?? '' : '' };
2057
- certs[goal.name] = { reads: c.reads, insts: c.insts, tree: o.tree, ...('picks' in c && c.picks.length ? { picks: c.picks } : {}) };
2064
+ certs[goal.name] = { ...(reservationRenamings.get(goal.name)?.length ? { proposalProvenance: { kind: 'reservation-alpha', renamings: reservationRenamings.get(goal.name) } } : {}), reads: c.reads, insts: c.insts, tree: o.tree, ...('picks' in c && c.picks.length ? { picks: c.picks } : {}) };
2058
2065
  }
2059
2066
  if (!again)
2060
2067
  return { proof: { instances: at, certs } };
@@ -0,0 +1,15 @@
1
+ export declare const internalName: (token: string, legacy: string) => string;
2
+ export declare const binder: (kind: string, index: number) => string;
3
+ export declare function variable(name: string): {
4
+ op: 'var';
5
+ name: string;
6
+ };
7
+ export declare function generatedVariable(name: string): {
8
+ op: 'var';
9
+ name: string;
10
+ };
11
+ export declare function copyVariable<T extends object>(from: object, to: T): T;
12
+ export declare const reservedName: (name: string) => boolean;
13
+ export declare function plainDeclaration(what: string, name: string): void;
14
+ export declare function guardReserved(value: unknown, allowedFree?: string[]): void;
15
+ export declare function encodeBinders<T>(value: T, declared: string[], allowedFree?: string[]): T;
@@ -0,0 +1,129 @@
1
+ // Private generated identities carry provenance in memory, not in their spelling.
2
+ // At the public machine/law boundary retain the historical readable name unless
3
+ // it collides with a declared or free identifier. Symbols never enter JSON/Lean.
4
+ const origin = Symbol('generated variable');
5
+ const issued = new Map();
6
+ export const internalName = (token, legacy) => { issued.set(token, legacy); return token; };
7
+ export const binder = (kind, index) => internalName(`?${kind}${index}`, `${kind}$${index}`);
8
+ const identity = (name) => {
9
+ const end = name.search(/[.$]/), root = end < 0 ? name : name.slice(0, end), legacy = issued.get(root);
10
+ return legacy === undefined ? undefined : { root, legacy, suffix: name.slice(root.length) };
11
+ };
12
+ export function variable(name) {
13
+ const out = { op: 'var', name };
14
+ if (identity(name))
15
+ Object.defineProperty(out, origin, { value: true, enumerable: true });
16
+ return out;
17
+ }
18
+ // Only generator sites may issue this mark; a matching name is not provenance.
19
+ export function generatedVariable(name) {
20
+ const out = { op: 'var', name };
21
+ Object.defineProperty(out, origin, { value: true, enumerable: true });
22
+ return out;
23
+ }
24
+ export function copyVariable(from, to) {
25
+ if (from[origin]) {
26
+ Object.defineProperty(to, origin, { value: true, enumerable: true });
27
+ const a = from.name, b = to.name;
28
+ // Composition prefixes an issued identity. Preserve its readable alias too,
29
+ // but only a marked source node can authorize this renamed identity.
30
+ if (typeof a === 'string' && typeof b === 'string' && b.endsWith(a)) {
31
+ const id = identity(a), prefix = b.slice(0, b.length - a.length);
32
+ if (id && prefix)
33
+ internalName(prefix + id.root, prefix + id.legacy);
34
+ }
35
+ }
36
+ return to;
37
+ }
38
+ export const reservedName = (name) => name === '1' || /[*[\],:#?~'⟦⟧⟨⟩|]/.test(name);
39
+ export function plainDeclaration(what, name) {
40
+ if (reservedName(name))
41
+ throw new Error(`${what}: the name ${name} is reserved (1, or * [ ] , : # ? ~ ' ⟦ ⟧ ⟨ ⟩ |)`);
42
+ }
43
+ const bindings = (node) => [
44
+ ...(node.op === 'all' && typeof node.key === 'string' ? [node.key, ...Array.isArray(node.keys) ? node.keys : []] : []),
45
+ ...(typeof node.forall === 'string' ? [node.forall, ...Array.isArray(node.keys) ? node.keys : []] : []),
46
+ ...(typeof node.each === 'string' ? [node.each] : []),
47
+ ...(typeof node.key === 'string' && 'where' in node && 'by' in node ? [node.key] : []),
48
+ ...(Array.isArray(node.some) ? node.some.filter((n) => typeof n === 'string') : []),
49
+ ];
50
+ export function guardReserved(value, allowedFree = []) {
51
+ const allowed = new Set(allowedFree);
52
+ const check = (x) => {
53
+ if (!x || typeof x !== 'object')
54
+ return;
55
+ if (Array.isArray(x)) {
56
+ x.forEach(check);
57
+ return;
58
+ }
59
+ const node = x;
60
+ if (node.op === 'var' && typeof node.name === 'string' && reservedName(node.name) && !allowed.has(node.name) && !node[origin])
61
+ throw Error(`law or rule reads free reserved name ${node.name}`);
62
+ Object.values(node).forEach(check);
63
+ };
64
+ check(value);
65
+ }
66
+ export function encodeBinders(value, declared, allowedFree = []) {
67
+ guardReserved(value, allowedFree);
68
+ const used = new Set([...declared, ...allowedFree]), groups = new Map();
69
+ const generated = (name) => {
70
+ const id = identity(name);
71
+ if (!id)
72
+ return false;
73
+ const group = groups.get(id.root) ?? { legacy: id.legacy, parts: new Set() };
74
+ group.parts.add(id.suffix);
75
+ groups.set(id.root, group);
76
+ return true;
77
+ };
78
+ const collect = (x) => {
79
+ if (!x || typeof x !== 'object')
80
+ return;
81
+ if (Array.isArray(x)) {
82
+ x.forEach(collect);
83
+ return;
84
+ }
85
+ const node = x;
86
+ for (const n of bindings(node))
87
+ if (!generated(n))
88
+ used.add(n);
89
+ if (node.op === 'var' && typeof node.name === 'string') {
90
+ if (!node[origin] || !generated(node.name))
91
+ used.add(node.name);
92
+ }
93
+ if (typeof node.map === 'string')
94
+ used.add(node.map);
95
+ if (node.op === 'flag' && typeof node.name === 'string')
96
+ used.add(node.name);
97
+ Object.values(node).forEach(collect);
98
+ };
99
+ collect(value);
100
+ if (!groups.size)
101
+ return value;
102
+ const names = new Map();
103
+ let next = 0;
104
+ for (const [root, group] of groups) {
105
+ const suffixes = [...group.parts];
106
+ let fresh = group.legacy;
107
+ if (suffixes.some(s => used.has(fresh + s)))
108
+ do {
109
+ fresh = `gdp$bound$${++next}`;
110
+ } while (used.has(fresh) || suffixes.some(s => used.has(fresh + s)));
111
+ for (const suffix of suffixes) {
112
+ const alias = fresh + suffix;
113
+ used.add(alias);
114
+ names.set(root + suffix, alias);
115
+ }
116
+ }
117
+ const rewrite = (x) => {
118
+ if (typeof x === 'string')
119
+ return names.get(x) ?? x;
120
+ if (!x || typeof x !== 'object')
121
+ return x;
122
+ if (Array.isArray(x))
123
+ return x.map(rewrite);
124
+ if (Object.getPrototypeOf(x) !== Object.prototype && Object.getPrototypeOf(x) !== null)
125
+ return x;
126
+ return Object.fromEntries(Object.entries(x).map(([k, v]) => [names.get(k) ?? k, rewrite(v)]));
127
+ };
128
+ return rewrite(value);
129
+ }
@@ -1,7 +1,7 @@
1
1
  import { type TranslationFields } from './source-check.js';
2
2
  import { type C, type E, type Fn, type Law, type Recurrence, type Machine, type Rand, type Request, type State, type Sum } from './machine.js';
3
- import { type Fold, type Goal, type Liveness, type Loop, type Recur, type StepLaw, type Tree } from '../kernel/kernel.js';
4
- import { type Report } from '../kernel/prove.js';
3
+ import { type Fold, type Ghosted, type Goal, type Liveness, type Loop, type Recur, type StepLaw, type Tree } from '../kernel/kernel.js';
4
+ import { type Report, type ModelRoundPolicy } from '../kernel/prove.js';
5
5
  import { type WorkAmount } from './work-amount.js';
6
6
  import { findRing } from './live.js';
7
7
  export type TermLike = Term | number;
@@ -501,6 +501,11 @@ export type Relation = {
501
501
  };
502
502
  export declare const relation: (holds: Cond, whenever?: Cond) => Relation;
503
503
  export declare function nameQuantifiers(m: Machine): Machine;
504
+ export declare class QuantifierAdmissionError extends Error {
505
+ readonly code: 'nested-universal' | 'binder-capture';
506
+ readonly kind: "quantifier-admission";
507
+ constructor(code: 'nested-universal' | 'binder-capture', reason: string);
508
+ }
504
509
  export type FnDef = {
505
510
  arity: number;
506
511
  js: string | ((...args: number[]) => number);
@@ -952,6 +957,18 @@ export type Found = {
952
957
  facts?: string[];
953
958
  rank?: string;
954
959
  };
960
+ export type CandidateSeedAudit = {
961
+ status: 'checked' | 'inconclusive';
962
+ kind?: 'usual' | 'counted';
963
+ kept: string[];
964
+ dropped: {
965
+ name: string;
966
+ goal?: string;
967
+ stuck?: 'sat';
968
+ reason?: string;
969
+ }[];
970
+ reason?: string;
971
+ };
955
972
  export type ProveOptions = {
956
973
  search?: boolean | {
957
974
  ms?: number;
@@ -960,6 +977,15 @@ export type ProveOptions = {
960
977
  };
961
978
  from?: 'reachable' | 'any';
962
979
  fast?: boolean;
980
+ modelRounds?: ModelRoundPolicy;
981
+ candidateSeeds?: {
982
+ kind?: 'usual' | 'counted';
983
+ laws: Law[];
984
+ counts?: NonNullable<Machine['counts']>;
985
+ witnesses?: Record<string, import('./machine.ts').SomeWitness>;
986
+ ghosts?: Pick<Ghosted, 'vars' | 'maps'>;
987
+ report?: (audit: CandidateSeedAudit) => void;
988
+ };
963
989
  };
964
990
  export declare class Unproven extends Error {
965
991
  readonly verdict: Verdict;