gdp-wired 0.48.0 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (295) hide show
  1. package/README.md +2 -2
  2. package/dist/core/bmc.js +10 -7
  3. package/dist/core/check.js +7 -2
  4. package/dist/core/count-attempt-work.d.ts +29 -0
  5. package/dist/core/count-attempt-work.js +96 -0
  6. package/dist/core/count-boolean-partition.d.ts +5 -0
  7. package/dist/core/count-boolean-partition.js +47 -0
  8. package/dist/core/count-bounded-quotient.d.ts +2 -0
  9. package/dist/core/count-bounded-quotient.js +13 -0
  10. package/dist/core/count-case-compose.d.ts +20 -0
  11. package/dist/core/count-case-compose.js +289 -0
  12. package/dist/core/count-cases.js +3 -2
  13. package/dist/core/count-cert-rename.d.ts +10 -0
  14. package/dist/core/count-cert-rename.js +69 -0
  15. package/dist/core/count-cert-transport.d.ts +10 -2
  16. package/dist/core/count-cert-transport.js +60 -9
  17. package/dist/core/count-certificate-minimize.d.ts +57 -0
  18. package/dist/core/count-certificate-minimize.js +263 -0
  19. package/dist/core/count-closed-family.d.ts +32 -0
  20. package/dist/core/count-closed-family.js +143 -0
  21. package/dist/core/count-closing-budget.d.ts +10 -0
  22. package/dist/core/count-closing-budget.js +49 -0
  23. package/dist/core/count-closing-needs.d.ts +5 -0
  24. package/dist/core/count-closing-needs.js +9 -0
  25. package/dist/core/count-component-budget.d.ts +5 -0
  26. package/dist/core/count-component-budget.js +9 -0
  27. package/dist/core/count-copy-shape.d.ts +11 -0
  28. package/dist/core/count-copy-shape.js +40 -0
  29. package/dist/core/count-disjoint-funding.d.ts +75 -0
  30. package/dist/core/count-disjoint-funding.js +284 -0
  31. package/dist/core/count-emitter-frame-pool.d.ts +23 -0
  32. package/dist/core/count-emitter-frame-pool.js +87 -0
  33. package/dist/core/count-final-step.d.ts +5 -0
  34. package/dist/core/count-final-step.js +20 -0
  35. package/dist/core/count-fixed-frame.d.ts +4 -0
  36. package/dist/core/count-fixed-frame.js +30 -0
  37. package/dist/core/count-frames.d.ts +25 -0
  38. package/dist/core/count-frames.js +118 -0
  39. package/dist/core/count-frozen-guard.d.ts +2 -0
  40. package/dist/core/count-frozen-guard.js +31 -0
  41. package/dist/core/count-generation-phase.d.ts +7 -0
  42. package/dist/core/count-generation-phase.js +33 -0
  43. package/dist/core/count-guard-composition.d.ts +12 -0
  44. package/dist/core/count-guard-composition.js +48 -0
  45. package/dist/core/count-guard-context.d.ts +11 -0
  46. package/dist/core/count-guard-context.js +50 -0
  47. package/dist/core/count-guard-facts.d.ts +50 -0
  48. package/dist/core/count-guard-facts.js +97 -0
  49. package/dist/core/count-guard-proposals.d.ts +7 -0
  50. package/dist/core/count-guard-proposals.js +106 -0
  51. package/dist/core/count-guard-shape.d.ts +18 -0
  52. package/dist/core/count-guard-shape.js +100 -0
  53. package/dist/core/count-guard-tree.d.ts +17 -0
  54. package/dist/core/count-guard-tree.js +125 -0
  55. package/dist/core/count-leader-facts.d.ts +10 -0
  56. package/dist/core/count-leader-facts.js +52 -0
  57. package/dist/core/count-leader.d.ts +10 -0
  58. package/dist/core/count-leader.js +331 -0
  59. package/dist/core/count-lemma-transport.d.ts +8 -0
  60. package/dist/core/count-lemma-transport.js +47 -0
  61. package/dist/core/count-lifted-budget.d.ts +54 -0
  62. package/dist/core/count-lifted-budget.js +97 -0
  63. package/dist/core/count-lifted-copy.d.ts +3 -0
  64. package/dist/core/count-lifted-copy.js +166 -0
  65. package/dist/core/count-lifted-increment.d.ts +3 -0
  66. package/dist/core/count-lifted-increment.js +146 -0
  67. package/dist/core/count-lifted-load.d.ts +5 -0
  68. package/dist/core/count-lifted-load.js +179 -0
  69. package/dist/core/count-lifted-prerequisite.d.ts +14 -0
  70. package/dist/core/count-lifted-prerequisite.js +53 -0
  71. package/dist/core/count-lifted-replacement.d.ts +3 -0
  72. package/dist/core/count-lifted-replacement.js +540 -0
  73. package/dist/core/count-lifted-shape.d.ts +63 -0
  74. package/dist/core/count-lifted-shape.js +115 -0
  75. package/dist/core/count-lifted-strategy.d.ts +7 -0
  76. package/dist/core/count-lifted-strategy.js +226 -0
  77. package/dist/core/count-lifted-transports.d.ts +32 -0
  78. package/dist/core/count-lifted-transports.js +293 -0
  79. package/dist/core/count-load-shape.d.ts +17 -0
  80. package/dist/core/count-load-shape.js +67 -0
  81. package/dist/core/count-minimal-view.d.ts +26 -0
  82. package/dist/core/count-minimal-view.js +46 -0
  83. package/dist/core/count-operation-observation.d.ts +9 -0
  84. package/dist/core/count-operation-observation.js +22 -0
  85. package/dist/core/count-operation-order.d.ts +5 -0
  86. package/dist/core/count-operation-order.js +4 -0
  87. package/dist/core/count-phase.d.ts +9 -0
  88. package/dist/core/count-phase.js +127 -0
  89. package/dist/core/count-premise-search.d.ts +9 -0
  90. package/dist/core/count-premise-search.js +41 -0
  91. package/dist/core/count-premise-view.d.ts +19 -0
  92. package/dist/core/count-premise-view.js +220 -0
  93. package/dist/core/count-prerequisite-components.d.ts +67 -0
  94. package/dist/core/count-prerequisite-components.js +239 -0
  95. package/dist/core/count-prerequisite-memory.d.ts +24 -0
  96. package/dist/core/count-prerequisite-memory.js +37 -0
  97. package/dist/core/count-prerequisite-plan.d.ts +12 -0
  98. package/dist/core/count-prerequisite-plan.js +88 -0
  99. package/dist/core/count-primitive-budget.d.ts +1 -0
  100. package/dist/core/count-primitive-budget.js +8 -0
  101. package/dist/core/count-project-free.d.ts +3 -0
  102. package/dist/core/count-project-free.js +24 -0
  103. package/dist/core/count-project-witness.d.ts +4 -0
  104. package/dist/core/count-project-witness.js +48 -0
  105. package/dist/core/count-proof-rescope.d.ts +14 -0
  106. package/dist/core/count-proof-rescope.js +71 -0
  107. package/dist/core/count-proof-scope.d.ts +68 -0
  108. package/dist/core/count-proof-scope.js +333 -0
  109. package/dist/core/count-prune-owned-root.d.ts +5 -0
  110. package/dist/core/count-prune-owned-root.js +27 -0
  111. package/dist/core/count-query-context.d.ts +3 -0
  112. package/dist/core/count-query-context.js +7 -0
  113. package/dist/core/count-query.d.ts +15 -0
  114. package/dist/core/count-query.js +59 -0
  115. package/dist/core/count-quorum-leaf.d.ts +9 -0
  116. package/dist/core/count-quorum-leaf.js +38 -0
  117. package/dist/core/count-reachability-budget.d.ts +1 -0
  118. package/dist/core/count-reachability-budget.js +7 -0
  119. package/dist/core/count-reachability-reconcile.d.ts +11 -0
  120. package/dist/core/count-reachability-reconcile.js +19 -0
  121. package/dist/core/count-reachability.d.ts +50 -0
  122. package/dist/core/count-reachability.js +351 -0
  123. package/dist/core/count-rebase-path.d.ts +9 -0
  124. package/dist/core/count-rebase-path.js +68 -0
  125. package/dist/core/count-recipe-context.d.ts +45 -0
  126. package/dist/core/count-recipe-context.js +71 -0
  127. package/dist/core/count-recipe-controller.d.ts +115 -0
  128. package/dist/core/count-recipe-controller.js +417 -0
  129. package/dist/core/count-recipe-graph.d.ts +36 -0
  130. package/dist/core/count-recipe-graph.js +211 -0
  131. package/dist/core/count-recovery/conditional-check-cache.js +3 -2
  132. package/dist/core/count-recovery/conditional-cuts.js +5 -4
  133. package/dist/core/count-recovery/conditional-proof.d.ts +37 -3
  134. package/dist/core/count-recovery/conditional-proof.js +72 -30
  135. package/dist/core/count-recovery/derivability-closure.js +2 -1
  136. package/dist/core/count-recovery/guard-cases.js +2 -1
  137. package/dist/core/count-recovery/reframe-tree.d.ts +2 -0
  138. package/dist/core/count-recovery/reframe-tree.js +24 -0
  139. package/dist/core/count-recovery/replay-linear-skeleton.d.ts +2 -0
  140. package/dist/core/count-recovery/replay-linear-skeleton.js +28 -0
  141. package/dist/core/count-recovery/row-cases.js +2 -1
  142. package/dist/core/count-rejection-budget.d.ts +8 -0
  143. package/dist/core/count-rejection-budget.js +15 -0
  144. package/dist/core/count-replacement.d.ts +5 -0
  145. package/dist/core/count-replacement.js +129 -0
  146. package/dist/core/count-replay-diagnostic.d.ts +21 -0
  147. package/dist/core/count-replay-diagnostic.js +49 -0
  148. package/dist/core/count-replay-skeleton.d.ts +4 -0
  149. package/dist/core/count-replay-skeleton.js +28 -0
  150. package/dist/core/count-rescope-funding.d.ts +3 -0
  151. package/dist/core/count-rescope-funding.js +17 -0
  152. package/dist/core/count-restrictions.d.ts +11 -0
  153. package/dist/core/count-restrictions.js +31 -0
  154. package/dist/core/count-retry-budget.d.ts +67 -0
  155. package/dist/core/count-retry-budget.js +114 -0
  156. package/dist/core/count-retry-round.d.ts +24 -0
  157. package/dist/core/count-retry-round.js +44 -0
  158. package/dist/core/count-row-agreement.d.ts +35 -0
  159. package/dist/core/count-row-agreement.js +270 -0
  160. package/dist/core/count-row-aliases.d.ts +3 -0
  161. package/dist/core/count-row-aliases.js +59 -0
  162. package/dist/core/count-row-composition.d.ts +6 -0
  163. package/dist/core/count-row-composition.js +55 -0
  164. package/dist/core/count-row-copy-linear.d.ts +4 -0
  165. package/dist/core/count-row-copy-linear.js +83 -0
  166. package/dist/core/count-row-copy.d.ts +4 -0
  167. package/dist/core/count-row-copy.js +94 -0
  168. package/dist/core/count-row-policy.d.ts +3 -0
  169. package/dist/core/count-row-policy.js +56 -0
  170. package/dist/core/count-row-reindex.d.ts +11 -0
  171. package/dist/core/count-row-reindex.js +126 -0
  172. package/dist/core/count-row-support.d.ts +9 -0
  173. package/dist/core/count-row-support.js +42 -0
  174. package/dist/core/count-row-symmetry.d.ts +7 -0
  175. package/dist/core/count-row-symmetry.js +100 -0
  176. package/dist/core/count-scope-hyps.d.ts +2 -0
  177. package/dist/core/count-scope-hyps.js +163 -0
  178. package/dist/core/count-scope-row-reuse.d.ts +3 -0
  179. package/dist/core/count-scope-row-reuse.js +92 -0
  180. package/dist/core/count-search-allowance.d.ts +1 -0
  181. package/dist/core/count-search-allowance.js +17 -0
  182. package/dist/core/count-stabilize-tree.d.ts +9 -0
  183. package/dist/core/count-stabilize-tree.js +35 -0
  184. package/dist/core/count-stage-trace.d.ts +8 -0
  185. package/dist/core/count-stage-trace.js +45 -0
  186. package/dist/core/count-strategies.d.ts +16 -0
  187. package/dist/core/count-strategies.js +155 -0
  188. package/dist/core/count-strategy-premises.d.ts +5 -0
  189. package/dist/core/count-strategy-premises.js +14 -0
  190. package/dist/core/count-strategy.d.ts +41 -0
  191. package/dist/core/count-strategy.js +76 -0
  192. package/dist/core/count-support.js +3 -2
  193. package/dist/core/count-tier-budget.d.ts +14 -0
  194. package/dist/core/count-tier-budget.js +64 -0
  195. package/dist/core/count-unwritten-prefix.d.ts +24 -0
  196. package/dist/core/count-unwritten-prefix.js +97 -0
  197. package/dist/core/count-write-shape.d.ts +15 -0
  198. package/dist/core/count-write-shape.js +73 -0
  199. package/dist/core/counts.d.ts +37 -13
  200. package/dist/core/counts.js +990 -127
  201. package/dist/core/cycles.js +5 -4
  202. package/dist/core/cyclic.js +11 -10
  203. package/dist/core/data.js +16 -15
  204. package/dist/core/dsl-deadline.d.ts +3 -0
  205. package/dist/core/dsl-deadline.js +27 -0
  206. package/dist/core/dsl.d.ts +9 -0
  207. package/dist/core/dsl.js +156 -51
  208. package/dist/core/evaluation-admission.d.ts +1 -0
  209. package/dist/core/evaluation-admission.js +3 -0
  210. package/dist/core/exists.d.ts +6 -1
  211. package/dist/core/exists.js +51 -9
  212. package/dist/core/field-laws.d.ts +3 -1
  213. package/dist/core/field-laws.js +140 -2
  214. package/dist/core/finite-houdini.d.ts +6 -0
  215. package/dist/core/finite-houdini.js +63 -21
  216. package/dist/core/finite-tiny.js +95 -67
  217. package/dist/core/fixtures/count-completion/paxos-decision.json +1 -0
  218. package/dist/core/fresh.js +5 -1
  219. package/dist/core/infer.js +45 -30
  220. package/dist/core/kind.js +2 -1
  221. package/dist/core/lemma-cuts.js +11 -10
  222. package/dist/core/linear-admission.d.ts +14 -0
  223. package/dist/core/linear-admission.js +151 -0
  224. package/dist/core/machine.d.ts +5 -2
  225. package/dist/core/machine.js +105 -31
  226. package/dist/core/meter.d.ts +22 -0
  227. package/dist/core/meter.js +34 -0
  228. package/dist/core/nonterm.js +4 -3
  229. package/dist/core/prover-row-budget.d.ts +3 -0
  230. package/dist/core/prover-row-budget.js +106 -0
  231. package/dist/core/quorum-laws.d.ts +21 -1
  232. package/dist/core/quorum-laws.js +27 -3
  233. package/dist/core/rationals.js +3 -2
  234. package/dist/core/rejection-discovery.d.ts +34 -0
  235. package/dist/core/rejection-discovery.js +36 -0
  236. package/dist/core/rejection-stage.d.ts +39 -0
  237. package/dist/core/rejection-stage.js +205 -0
  238. package/dist/core/request-quotient.d.ts +8 -0
  239. package/dist/core/request-quotient.js +299 -0
  240. package/dist/core/row-agreement-shape.d.ts +15 -0
  241. package/dist/core/row-agreement-shape.js +68 -0
  242. package/dist/core/runtime-wall.d.ts +2 -0
  243. package/dist/core/search-policy.d.ts +15 -0
  244. package/dist/core/search-policy.js +68 -0
  245. package/dist/core/solver.d.ts +1 -1
  246. package/dist/core/solver.js +40 -6
  247. package/dist/core/step-work.d.ts +12 -0
  248. package/dist/core/step-work.js +14 -0
  249. package/dist/core/strategy-premises.d.ts +8 -0
  250. package/dist/core/strategy-premises.js +64 -0
  251. package/dist/core/system.js +4 -3
  252. package/dist/core/table-admission.d.ts +1 -0
  253. package/dist/core/table-admission.js +3 -0
  254. package/dist/core/trace-clock.d.ts +3 -0
  255. package/dist/core/trace-clock.js +16 -0
  256. package/dist/core/transfer.js +3 -2
  257. package/dist/core/translate.js +16 -3
  258. package/dist/core/wall.d.ts +6 -1
  259. package/dist/core/wall.js +23 -9
  260. package/dist/core/watch.d.ts +1 -1
  261. package/dist/core/watch.js +13 -4
  262. package/dist/core/work-admission.d.ts +164 -0
  263. package/dist/core/work-admission.js +418 -0
  264. package/dist/core/work-amount.d.ts +21 -0
  265. package/dist/core/work-amount.js +80 -0
  266. package/dist/core/work-collections.d.ts +11 -0
  267. package/dist/core/work-collections.js +198 -0
  268. package/dist/core/work-kinds.d.ts +11 -0
  269. package/dist/core/work-kinds.js +9 -0
  270. package/dist/core/work-meter.d.ts +8 -0
  271. package/dist/core/work-meter.js +83 -0
  272. package/dist/core/work-observe.d.ts +12 -0
  273. package/dist/core/work-observe.js +39 -0
  274. package/dist/core/work-profile.d.ts +10 -0
  275. package/dist/core/work-profile.js +21 -0
  276. package/dist/core/work-refusal.d.ts +1 -0
  277. package/dist/core/work-refusal.js +6 -0
  278. package/dist/interchange/format.js +2 -0
  279. package/dist/kernel/cdcl.js +93 -40
  280. package/dist/kernel/epr.js +23 -8
  281. package/dist/kernel/kernel.d.ts +47 -1
  282. package/dist/kernel/kernel.js +417 -68
  283. package/dist/kernel/prove.d.ts +49 -3
  284. package/dist/kernel/prove.js +468 -122
  285. package/dist/kernel/prover-rows.d.ts +1 -0
  286. package/dist/kernel/prover-rows.js +12 -1
  287. package/dist/kernel/reader.d.ts +1 -1
  288. package/dist/kernel/reader.js +57 -12
  289. package/dist/kernel/simplex.js +9 -2
  290. package/dist/lean-kernel/emit.d.ts +9 -1
  291. package/dist/lean-kernel/emit.js +144 -22
  292. package/dist/lean-kernel/legacy-family-library.d.ts +1 -0
  293. package/dist/lean-kernel/legacy-family-library.js +5 -0
  294. package/dist/lean-kernel/library.js +3 -3
  295. package/package.json +1 -1
@@ -26,4 +26,5 @@ export declare const rowReuseStorage: () => {
26
26
  rowEntries: number;
27
27
  constraints: number;
28
28
  };
29
+ export declare function proverRowsReusingFacts(goal: Goal, path: Path): Constraint[];
29
30
  export declare function proverRows(goal: Goal, path: Path): Constraint[];
@@ -1,5 +1,9 @@
1
1
  import { env } from "../core/solver.js";
2
2
  import { canon, leafConstraintsReusing } from "./kernel.js";
3
+ import { budgetedLeafRows } from "../core/prover-row-budget.js";
4
+ import { completeWorkProfile } from "../core/work-profile.js";
5
+ import { inBudget } from "./prove.js";
6
+ import { withTableAdmission } from "../core/table-admission.js";
3
7
  const originals = new WeakMap(), ids = new WeakMap();
4
8
  const nodes = new Map();
5
9
  let serial = 0, keyChars = 0;
@@ -97,6 +101,13 @@ export class ProverRowsCache {
97
101
  }
98
102
  const rows = new ProverRowsCache(env.GDP_ROWS_UNWEIGHTED === '1' ? Infinity : 250000);
99
103
  export const rowReuseStorage = () => ({ nodes: nodes.size, keyChars, goals: goalPool.size, rowEntries: rows.size, constraints: rows.weight });
104
+ // One-pass reindex keeps interned hypotheses and per-hypothesis facts without
105
+ // retaining complete tables. Preserve the existing full-work row admission.
106
+ export function proverRowsReusingFacts(goal, path) {
107
+ rowReuseStats.rowsBuilt++;
108
+ const build = () => { const shared = env.GDP_ROWS_SHARED === '0' ? goal : sharedGoal(goal); return completeWorkProfile.enabled && inBudget() ? budgetedLeafRows(shared, path) : leafConstraintsReusing(shared, path); };
109
+ return completeWorkProfile.enabled && inBudget() ? withTableAdmission(build) : build();
110
+ }
100
111
  export function proverRows(goal, path) {
101
112
  const shared = sharedGoal(goal);
102
113
  // Path ordering matters for input-row indices. Include the actual atom as
@@ -108,7 +119,7 @@ export function proverRows(goal, path) {
108
119
  return out;
109
120
  }
110
121
  rowReuseStats.rowsBuilt++;
111
- out = leafConstraintsReusing(shared, path);
122
+ out = completeWorkProfile.enabled && inBudget() ? budgetedLeafRows(shared, path) : leafConstraintsReusing(shared, path);
112
123
  rowReuseStats.rowsEvicted += rows.set(key, out);
113
124
  return out;
114
125
  }
@@ -111,7 +111,7 @@ export declare class Reader {
111
111
  private trailRows;
112
112
  private trailStamps;
113
113
  private pairs;
114
- leafRows(src?: (number | [string, string])[]): Row[];
114
+ leafRows(src?: (number | [string, string])[], beforeRow?: (count: number) => void): Row[];
115
115
  live: Row[];
116
116
  entered: number[];
117
117
  left: number[];
@@ -1,5 +1,10 @@
1
+ import { completeWorkProfile } from "../core/work-profile.js";
2
+ import { checkWorkEndpoint } from "./prove.js";
3
+ import { startWork } from "../core/work-admission.js";
1
4
  import { shareTerms } from "./share.js";
2
- import { add, costs, env, k, scale, sub, v } from "../core/solver.js";
5
+ import { costs, env } from "../core/solver.js";
6
+ import { fundedAdd as add, fundedConstant as k, fundedScale as scale, fundedSub as sub, fundedVariable as v, admittedLinearProduct, everyLinearCell } from "../core/linear-admission.js";
7
+ import { workConcat, workStrings, workJoin } from "../core/work-collections.js";
3
8
  import { atomOf, canon, canonFlip, cellParts, plainMap, columnTerm, factorsOf, isCell, termColumn, tupleAnd } from "./kernel.js";
4
9
  export const none = new Set();
5
10
  export const join = (a, b) => {
@@ -27,6 +32,13 @@ const unfin = (r) => (r.fin ? { w: r.w, pos: r.pos, fin: false } : r);
27
32
  const both = (a, b) => ({ w: join(a.w, b.w), pos: Math.max(a.pos, b.pos), fin: a.fin && b.fin });
28
33
  // The kernel's product of two linear forms (kernel.ts's `times`): each monomial its factors sorted, joined by '*'.
29
34
  export function times(a, b) {
35
+ if (completeWorkProfile.enabled)
36
+ return admittedLinearProduct(a, b, (p, q) => {
37
+ if (p.includes('⟦') || q.includes('⟦'))
38
+ return undefined;
39
+ const fs = workStrings(workConcat(p === '1' ? [] : factorsOf(p), q === '1' ? [] : factorsOf(q), 'reader product:factors'), 'reader product:sort');
40
+ return fs.length ? workJoin(fs, '*', 'reader product:join') : '1';
41
+ }, 'reader product', false);
30
42
  const out = [];
31
43
  for (const [p, cp] of Object.entries(a))
32
44
  for (const [q, cq] of Object.entries(b)) {
@@ -39,7 +51,7 @@ export function times(a, b) {
39
51
  }
40
52
  const one = k(1);
41
53
  const namePair = new WeakMap();
42
- const constantLin = (l) => Object.entries(l).every(([key, c]) => key === '1' || c === 0);
54
+ const constantLin = (l) => everyLinearCell(l, (key, c) => key === '1' || c === 0, 'reader constant branch');
43
55
  const lasts = Array.from({ length: 8 }, () => new WeakMap());
44
56
  function same(site, owner, a, b, c, make) {
45
57
  const m = lasts[site], had = m.get(owner);
@@ -113,8 +125,11 @@ export class Reader {
113
125
  s.set(f.key, f);
114
126
  }
115
127
  within(key, f) {
128
+ if (completeWorkProfile.enabled)
129
+ startWork('values', 1, 'reader value');
116
130
  const was = this.finding, now = { key };
117
- costs.values++;
131
+ if (!completeWorkProfile.enabled)
132
+ costs.values++;
118
133
  this.found.set(key, now);
119
134
  this.finding = now;
120
135
  try {
@@ -130,8 +145,11 @@ export class Reader {
130
145
  const todo = [], seen = new Set(), found = this.found;
131
146
  const walk = (edges) => {
132
147
  if (edges) {
133
- costs.edges += edges.size;
148
+ if (!completeWorkProfile.enabled)
149
+ costs.edges += edges.size;
134
150
  for (const [k, f] of edges) {
151
+ if (completeWorkProfile.enabled)
152
+ startWork('edges', 1, 'reader dependency');
135
153
  if (found.get(k) === f)
136
154
  todo.push(k);
137
155
  else
@@ -165,6 +183,8 @@ export class Reader {
165
183
  this.units.set(name, (w = new Set([name]))); return w; }
166
184
  // Whether lin <= 0 is decided, and by what.
167
185
  dec(lin) {
186
+ if (completeWorkProfile.enabled)
187
+ checkWorkEndpoint('reader decision');
168
188
  let constant = true;
169
189
  for (const key in lin)
170
190
  if (key !== '1') {
@@ -188,6 +208,8 @@ export class Reader {
188
208
  return { t: undefined, w: none, pos: -1, fin: false };
189
209
  }
190
210
  linear(e) {
211
+ if (completeWorkProfile.enabled)
212
+ checkWorkEndpoint('reader expression');
191
213
  e = this.share(e);
192
214
  this.read(e);
193
215
  const had = this.ls.get(e);
@@ -334,6 +356,8 @@ export class Reader {
334
356
  return { when: atoms.when, unless: atoms.unless, r };
335
357
  }
336
358
  truth(c) {
359
+ if (completeWorkProfile.enabled)
360
+ checkWorkEndpoint('reader condition');
337
361
  c = this.share(c);
338
362
  this.read(c);
339
363
  const had = this.ts.get(c);
@@ -423,6 +447,8 @@ export class Reader {
423
447
  }
424
448
  // kernel.ts's facts, each row with its reason; final when nothing it read is open.
425
449
  factsOf(c, positive, out) {
450
+ if (completeWorkProfile.enabled)
451
+ checkWorkEndpoint('reader fact');
426
452
  switch (c.op) {
427
453
  case 'flag': throw new Error('flags are inlined before the kernel sees them');
428
454
  case 'all': return R0;
@@ -637,6 +663,8 @@ export class Reader {
637
663
  termSeen = [];
638
664
  gen = 0;
639
665
  form(lin) {
666
+ if (completeWorkProfile.enabled)
667
+ checkWorkEndpoint('reader form');
640
668
  let f = this.forms.get(lin);
641
669
  if (f)
642
670
  return f;
@@ -673,11 +701,12 @@ export class Reader {
673
701
  pairs = new Map();
674
702
  // The rows in kernel.ts's order, copies kept (a leaf's derivation indexes these).
675
703
  // With `src`, each row's source beside it: the hypothesis whose facts it is, the pair of cells it equates, else -1.
676
- leafRows(src) {
704
+ leafRows(src, beforeRow) {
677
705
  const rows = [];
678
706
  for (let i = 0; i < this.trail.size(); i++) {
679
707
  if (this.trail.quiet?.(i))
680
708
  continue;
709
+ beforeRow?.(1);
681
710
  const s = this.trail.stamp(i);
682
711
  let r = this.trailStamps[i] === s ? this.trailRows[i] : undefined;
683
712
  if (!r) {
@@ -693,6 +722,7 @@ export class Reader {
693
722
  }
694
723
  for (let i = 0; i < this.goal.hyps.length; i++)
695
724
  for (const r of this.facts(i).rows) {
725
+ beforeRow?.(1);
696
726
  rows.push(r);
697
727
  src?.push(i);
698
728
  }
@@ -711,8 +741,12 @@ export class Reader {
711
741
  continue;
712
742
  const f = this.pair(p, q), w = this.equal(f);
713
743
  if (w) {
714
- rows.push({ lin: f.pq, w, label: '' }, { lin: f.qp, w, label: '' });
715
- src?.push([p.name, q.name], [p.name, q.name]);
744
+ beforeRow?.(1);
745
+ rows.push({ lin: f.pq, w, label: '' });
746
+ src?.push([p.name, q.name]);
747
+ beforeRow?.(1);
748
+ rows.push({ lin: f.qp, w, label: '' });
749
+ src?.push([p.name, q.name]);
716
750
  }
717
751
  }
718
752
  const done = this.termSeen, todo = names.filter(j => kind[j] === 1);
@@ -722,6 +756,7 @@ export class Reader {
722
756
  continue;
723
757
  done[j] = g;
724
758
  for (const r of this.termRows(this.nameText[j])) {
759
+ beforeRow?.(1);
725
760
  rows.push(r);
726
761
  src?.push(-1);
727
762
  for (const n of this.form(r.lin).names) {
@@ -735,10 +770,11 @@ export class Reader {
735
770
  }
736
771
  }
737
772
  for (const j of names) {
773
+ beforeRow?.(1);
738
774
  const name = this.nameText[j];
739
775
  let r = this.natRows.get(name);
740
776
  if (!r)
741
- this.natRows.set(name, (r = { lin: { [name]: -1 }, w: none, label: '' }));
777
+ this.natRows.set(name, (r = { lin: completeWorkProfile.enabled ? scale(v(name), -1) : { [name]: -1 }, w: none, label: '' }));
742
778
  rows.push(r);
743
779
  src?.push(-1);
744
780
  }
@@ -792,6 +828,8 @@ export class Reader {
792
828
  cellsChanged = 0;
793
829
  // (`from`: the trail's first position that may have changed since the last sync, where the caller knows it)
794
830
  sync(from = 0) {
831
+ if (completeWorkProfile.enabled)
832
+ checkWorkEndpoint('reader sync');
795
833
  this.syncing = true;
796
834
  this.syncN++;
797
835
  this.changed = [];
@@ -914,8 +952,12 @@ export class Reader {
914
952
  // A copy of a row in (kind 1: from the trail or the facts, 2: a column's term rows, its own name not counted; 0: a
915
953
  // natural's or a pair of cells', whose names it doesn't count).
916
954
  addCopy(r, kind, self = -1) {
917
- const f = this.form(r.lin), id = f.id, cs = (this.copies[id] ??= []);
918
- costs.copies++;
955
+ const f = this.form(r.lin), id = f.id;
956
+ if (completeWorkProfile.enabled)
957
+ startWork('copies', 1, 'reader add copy');
958
+ const cs = (this.copies[id] ??= []);
959
+ if (!completeWorkProfile.enabled)
960
+ costs.copies++;
919
961
  if (!cs.length) {
920
962
  this.mark(id, false);
921
963
  this.slot[id] = this.live.length;
@@ -934,7 +976,10 @@ export class Reader {
934
976
  }
935
977
  removeCopy(r, kind, self = -1) {
936
978
  const f = this.form(r.lin), id = f.id, cs = this.copies[id];
937
- costs.copies++;
979
+ if (completeWorkProfile.enabled)
980
+ startWork('copies', 1, 'reader remove copy');
981
+ else
982
+ costs.copies++;
938
983
  cs.splice(cs.indexOf(r), 1);
939
984
  const at = this.slot[id];
940
985
  if (!cs.length) {
@@ -983,7 +1028,7 @@ export class Reader {
983
1028
  const name = this.nameText[j];
984
1029
  let r = this.natRows.get(name);
985
1030
  if (!r)
986
- this.natRows.set(name, (r = { lin: { [name]: -1 }, w: none, label: '' }));
1031
+ this.natRows.set(name, (r = { lin: completeWorkProfile.enabled ? scale(v(name), -1) : { [name]: -1 }, w: none, label: '' }));
987
1032
  this.inNat[j] = r;
988
1033
  this.addCopy(r, 0);
989
1034
  if (this.nameKind[j] === 2) {
@@ -11,6 +11,8 @@
11
11
  // false) nothing is rounded, and a strict row's bound is moved in by a hair (1e-7, relative): the floats only pick a
12
12
  // conflict's rows, which the exact elimination then refutes, strictness and all, or doesn't.
13
13
  import { costs, gcd } from "../core/solver.js";
14
+ import { completeWorkProfile } from "../core/work-profile.js";
15
+ import { startWork } from "../core/work-admission.js";
14
16
  const eps = 1e-9;
15
17
  // A bound's tolerance: relative past 1 (values drift by a few ulps a pivot).
16
18
  const tol = (b) => 1e-7 * Math.max(1, Math.abs(b));
@@ -407,8 +409,13 @@ export class Simplex {
407
409
  for (const j of ecoef.keys())
408
410
  this.colOf[j].add(r);
409
411
  // Every other row reading x_e: substitute.
410
- costs.pivotRows += this.colOf[e].size;
411
- for (const q of [...this.colOf[e]]) {
412
+ if (!completeWorkProfile.enabled)
413
+ costs.pivotRows += this.colOf[e].size;
414
+ // ecoef excludes e: this traversal only deletes its current member from
415
+ // colOf[e], never inserts a new one. OFF retains its original snapshot.
416
+ for (const q of completeWorkProfile.enabled ? this.colOf[e] : [...this.colOf[e]]) {
417
+ if (completeWorkProfile.enabled)
418
+ startWork('pivotRows', 1, 'simplex pivot substitution');
412
419
  if (q === r)
413
420
  continue;
414
421
  const other = this.rows[q], c = other.coef.get(e), before = other.coef.size;
@@ -1,6 +1,6 @@
1
1
  import type { C, E, Law, Machine, Recurrence } from '../core/machine.js';
2
2
  import { type Lin, type Step } from '../core/solver.js';
3
- import { type CountCert, type CountedGoal, type CountInst, type LemmaCut, type Ghosted, type Fold, type Goal, type Instances, type KInduction, type Liveness, type Loop, type Path, type Recur, type RecurCases, type StepLaw, type Tree } from '../kernel/kernel.js';
3
+ import { type CountCert, type CountDecl, type CountedGoal, type CountInst, type FrameCut, type MonoCut, type LinCut, type LemmaCut, type Ghosted, type Fold, type Goal, type Instances, type KInduction, type Liveness, type Loop, type Path, type Recur, type RecurCases, type StepLaw, type Tree } from '../kernel/kernel.js';
4
4
  import { proveStepLaws } from '../kernel/prove.js';
5
5
  import { type Cyclic } from '../kernel/cyclic.js';
6
6
  import { leanLibrary } from './library.js';
@@ -20,6 +20,9 @@ export declare function leaves(t: Tree, path: Path, visit: (t: Tree & {
20
20
  export declare function encode(ex: Exported, tamper?: boolean, dropStep?: boolean, globalVars?: string[], globalMaps?: string[], slim?: boolean, reach?: boolean, context?: {
21
21
  path?: Path;
22
22
  lemmas?: LemmaCut[];
23
+ frames?: FrameCut[];
24
+ monos?: MonoCut[];
25
+ lins?: LinCut[];
23
26
  cols?: string[];
24
27
  }): {
25
28
  tab: string;
@@ -35,6 +38,9 @@ export declare function goalToLean(ex: Exported, i: number, tamper?: boolean, dr
35
38
  export declare function encodeCounted(id: string, goal: Goal, cert: {
36
39
  tree: Tree;
37
40
  lemmas?: LemmaCut[];
41
+ frames?: FrameCut[];
42
+ monos?: MonoCut[];
43
+ lins?: LinCut[];
38
44
  }, vars: string[], maps: string[]): {
39
45
  lemmas: string;
40
46
  lemmaList: (entries: LemmaCut[]) => string;
@@ -47,6 +53,7 @@ export declare function encodeCounted(id: string, goal: Goal, cert: {
47
53
  e: (t: E) => string;
48
54
  row: (lin: Lin) => string;
49
55
  };
56
+ export declare function mcToLean(id: string, hyps: C[], decls: CountDecl[], cert: CountCert): string;
50
57
  export declare function countedToLean(id: string, g: CountedGoal, cert: {
51
58
  insts: CountInst[];
52
59
  tree: Tree;
@@ -95,6 +102,7 @@ export declare function readable(id: string, laws: Law[], vars: string[], maps:
95
102
  have?: (j: number) => string;
96
103
  lit?: (c: C) => string;
97
104
  eLit?: (e: E) => string;
105
+ ghosts?: boolean;
98
106
  }): string;
99
107
  export type ProgressCase = {
100
108
  id: string;
@@ -1,14 +1,16 @@
1
1
  import { atMost, n, not, pointWrite } from "../core/machine.js";
2
2
  import { add, k, scale, sub } from "../core/solver.js";
3
- import { lemmaPath, checkCounted, checkCountedLaws, countedGoal, countedObligations, countHyps, mcGoal, postName, boundOf, caseGoals, cellParts, check, checkRecur, checkRecurCases, coverGoal, recurGoal, canon, decided, factorsOf, isCell, isMonomial, columnTerm, stateName, termColumn, truth, historyMachine, sumMachine, sumCovers, sumParts, foldObligations, kInductionStart, kInductionSteps, leafConstraints, loopLiveness, loopMachine, linear, livenessHelpful, livenessParts, livenessLevels, livenessRanks, strongly, loopObligations, trueC, obligations, progressObligations, stepLawObligations, substC, witnessesOf, withProducts } from "../kernel/kernel.js";
3
+ import { framePath, lemmaPath, checkMC, checkCounted, checkCountedLaws, countedGoal, countedObligations, countHyps, mcGoal, postName, boundOf, caseGoals, cellParts, check, checkRecur, checkRecurCases, coverGoal, recurGoal, canon, decided, factorsOf, isCell, isMonomial, columnTerm, stateName, termColumn, truth, historyMachine, sumMachine, sumCovers, sumParts, foldObligations, kInductionStart, kInductionSteps, leafConstraints, loopLiveness, loopMachine, linear, livenessHelpful, livenessParts, livenessLevels, livenessRanks, strongly, loopObligations, trueC, obligations, progressObligations, stepLawObligations, substC, witnessesOf, withProducts } from "../kernel/kernel.js";
4
4
  import { chooseLevels, clock, grow, minimal, proveBuilt, proveLaws, proveSetFast, proveStepLaws, withDeadline } from "../kernel/prove.js";
5
5
  import { refinement, refinementSides } from "../core/compose.js";
6
6
  import { exactNat, leanConnective, leanSurface, leanTerms } from "./lean-terms.js";
7
7
  import { descentGoal, mainGoal, premiseGoal } from "../kernel/cyclic.js";
8
8
  import { allowNode, certMs, closingInsts, reqTS, withWitness, foldNodes, certMode, quietly, uncoveredWhy, hasQuantified, kWhens, machineNodes, proveCyclic, routeOf, searchedStepNodes, skMachine, stepLawNodes, tBack, tSub } from "../core/cyclic.js";
9
9
  import { leanLibrary } from "./library.js";
10
+ import { legacyFamilyLibrary } from "./legacy-family-library.js";
10
11
  import { proveKInduction } from "../core/kind.js";
11
12
  import { quantifiedRenames } from "./qalpha.js";
13
+ import { countsForReads } from "../core/count-facts.js";
12
14
  export { leanLibrary };
13
15
  // --- to Lean ------------------------------------------------------------------------------------------------------------
14
16
  const varsOf = (c) => [...JSON.stringify(c).matchAll(/"op":"var","name":"([^"]+)"/g)].map(m => m[1]);
@@ -120,7 +122,7 @@ export function encode(ex, tamper = false, dropStep = true, globalVars, globalMa
120
122
  // Each leaf with its path and rows, found once (the passes below and the tree's text read them in the same order).
121
123
  const leafList = [];
122
124
  leaves(tree, context.path ?? new Map(), (leaf, path) => {
123
- const visible = lemmaPath(context.lemmas ?? [], path);
125
+ const visible = context.frames?.length || context.monos?.length || context.lins?.length ? framePath(context.frames ?? [], context.lemmas ?? [], path, context.monos, context.lins) : lemmaPath(context.lemmas ?? [], path);
124
126
  leafList.push({ leaf, path: visible, base: leafConstraints(goal, visible) });
125
127
  });
126
128
  const reads = new Set(), hintTerms = new Set();
@@ -138,11 +140,11 @@ export function encode(ex, tamper = false, dropStep = true, globalVars, globalMa
138
140
  hintTerms.add(src.term);
139
141
  }
140
142
  }
141
- const readHyps = whole ? goal.hyps : goal.hyps.filter((_, i) => reads.has(i));
143
+ const readHyps = [...(whole ? goal.hyps : goal.hyps.filter((_, i) => reads.has(i))), ...(context.monos ?? []).flatMap(m => m.when), ...(context.lins ?? []).flatMap(l => l.when)];
142
144
  const readTerms = whole ? [] : [...hintTerms].map(name => columnTerm(name));
143
145
  // Columns: every variable of the hypotheses, then every cell any leaf uses (and the cells inside their keys),
144
146
  // shallower cells first so a key reads only earlier columns.
145
- const vars = globalVars ?? [...new Set(goal.hyps.flatMap(varsOf))];
147
+ const vars = globalVars ?? [...new Set([...goal.hyps.flatMap(varsOf), ...lemmaNames([], context.frames, context.monos, context.lins).vars])];
146
148
  const cells = new Set(), terms = new Set();
147
149
  // Monomials: every one a leaf's rows or products use, or that a product term has under the leaf's path, with the
148
150
  // cells among their factors.
@@ -228,6 +230,17 @@ export function encode(ex, tamper = false, dropStep = true, globalVars, globalMa
228
230
  addCell(key);
229
231
  }
230
232
  }
233
+ // Conditions can name columns a certificate never uses at a leaf; they still need encoding.
234
+ for (const f of context.frames ?? [])
235
+ for (const r of f.when)
236
+ for (const key of Object.keys(r)) {
237
+ if (isMonomial(key))
238
+ addMono(key);
239
+ else if (isCell(key))
240
+ addCell(key);
241
+ else if (key.startsWith('⟦'))
242
+ terms.add(key);
243
+ }
231
244
  const depth = (name) => name.split('[').length;
232
245
  // Term columns (open choices, each standing for its term's value) before the cells, whose keys may read them; a
233
246
  // monomial with a cell among its factors after the cells.
@@ -330,7 +343,7 @@ export function encode(ex, tamper = false, dropStep = true, globalVars, globalMa
330
343
  if (!src)
331
344
  return '.any';
332
345
  if ('atom' in src)
333
- return context.path || context.lemmas?.length ? '.any' : `.atom ${path.size - 1 - src.atom}`; // Lean's path has the latest decision first
346
+ return context.path || context.lemmas?.length || context.frames?.length || context.monos?.length || context.lins?.length ? '.any' : `.atom ${path.size - 1 - src.atom}`; // Lean's path has the latest decision first
334
347
  if ('fact' in src)
335
348
  return `.fact ${src.fact}`;
336
349
  const j = 'pair' in src ? pairs.indexOf([...src.pair].sort().join('\n')) : col.get('nat' in src ? src.nat : src.term) ?? -1;
@@ -368,7 +381,7 @@ theorem ${name} : ∀ env maps, ¬ ∀ c ∈ ${name}_goal.hyps, evalC env maps c
368
381
  const varsOfE = (t) => [...JSON.stringify(t).matchAll(/"op":"var","name":"([^"]+)"/g)].map(m => m[1]);
369
382
  const mapsOf = (t) => [...JSON.stringify(t).matchAll(/"op":"get","map":"([^"]+)"/g)].map(m => m[1]);
370
383
  // Extra row names may appear only in a lemma. Resolve their column dependencies with the same rules as encode.
371
- function lemmaNames(lemmas) {
384
+ function lemmaNames(lemmas, frames = [], monos = [], lins = []) {
372
385
  const vars = new Set(), maps = new Set(), seen = new Set();
373
386
  const name = (s) => {
374
387
  if (s === '1' || seen.has(s))
@@ -406,6 +419,24 @@ function lemmaNames(lemmas) {
406
419
  row(l.cut);
407
420
  tree(l.tree);
408
421
  }
422
+ for (const f of frames) {
423
+ f.when.forEach(row);
424
+ name(f.post);
425
+ name(f.pre);
426
+ }
427
+ for (const m of monos) {
428
+ m.when.flatMap(varsOf).forEach(name);
429
+ m.when.flatMap(mapsOf).forEach(v => maps.add(v));
430
+ name(m.post);
431
+ name(m.pre);
432
+ tree(m.tree);
433
+ }
434
+ for (const l of lins) {
435
+ l.when.flatMap(varsOf).forEach(name);
436
+ l.when.flatMap(mapsOf).forEach(v => maps.add(v));
437
+ [...l.pos, ...l.neg].forEach(([, v]) => name(v));
438
+ tree(l.tree);
439
+ }
409
440
  return { vars: [...vars], maps: [...maps] };
410
441
  }
411
442
  // Every independent proof uses one common table, but its own exact slice and initial path. Two passes establish
@@ -427,7 +458,7 @@ export function encodeCounted(id, goal, cert, vars, maps) {
427
458
  return { ex: { name: `${id}: lemma ${i}`, goal: { ...goal, hyps: selected }, tree: l.tree }, path };
428
459
  });
429
460
  const main = { name: id, goal, tree: cert.tree };
430
- const first = encode(main, false, true, vars, maps, false, false, { lemmas: ls });
461
+ const first = encode(main, false, true, vars, maps, false, false, { lemmas: ls, frames: cert.frames, monos: cert.monos, lins: cert.lins });
431
462
  if (!ls.length)
432
463
  return { ...first, lemmas: '[]', lemmaList: (entries) => {
433
464
  if (entries.length)
@@ -436,7 +467,7 @@ export function encodeCounted(id, goal, cert, vars, maps) {
436
467
  } };
437
468
  const initial = sources.map(s => encode(s.ex, false, true, vars, maps, false, false, { path: s.path }));
438
469
  const cols = [...new Set([first, ...initial].flatMap(e => e.cols))];
439
- const base = encode(main, false, true, vars, maps, false, false, { lemmas: ls, cols });
470
+ const base = encode(main, false, true, vars, maps, false, false, { lemmas: ls, frames: cert.frames, monos: cert.monos, lins: cert.lins, cols });
440
471
  const proofs = sources.map(s => encode(s.ex, false, true, vars, maps, false, false, { path: s.path, cols }));
441
472
  const lemmaList = (entries) => list(entries.map((l, i) => {
442
473
  const source = sources[i];
@@ -448,6 +479,71 @@ export function encodeCounted(id, goal, cert, vars, maps) {
448
479
  }));
449
480
  return { ...base, lemmas: lemmaList(ls), lemmaList };
450
481
  }
482
+ // The three cut lists of one counted certificate as Lean literals: frames over the certificate's own row encoder, per-key
483
+ // monotone and linear cuts each with the table and tree of its own auxiliary goal. One code path for the single-goal
484
+ // export (mcToLean) and the family export (cmachineToLean).
485
+ function cutLits(id, cert, decls, enc, vars, maps, c, ix) {
486
+ const frames = list((cert.frames ?? []).map(f => `⟨${list(f.when.map(enc.row))}, ${ix(f.post)}, ${ix(f.pre)}⟩`));
487
+ const counts = countsForReads(decls, cert.reads);
488
+ if (!counts)
489
+ throw new Error(`${id}: invalid count reads`);
490
+ const monos = list((cert.monos ?? []).map((m, i) => {
491
+ const post = counts.find(c => c.v === m.post), pre = counts.find(c => c.v === m.pre);
492
+ const auxiliary = { name: `${id}: per-key cut ${i}`, hyps: [...m.when,
493
+ { op: '<', a: { op: 'var', name: post.key }, b: post.below }, { op: '<', a: pre.body, b: post.body }] };
494
+ const proof = encode({ name: auxiliary.name, goal: auxiliary, tree: m.tree }, false, true, vars, maps);
495
+ return `⟨${list(m.when.map(c))}, ${ix(m.post)}, ${ix(m.pre)}, ${proof.tab}, ${proof.tree}⟩`;
496
+ }));
497
+ const lins = list((cert.lins ?? []).map((l, i) => {
498
+ const first = counts.find(c => c.v === [...l.pos, ...l.neg][0][1]);
499
+ const term = (side) => side.reduceRight((rest, [k, v]) => ({ op: 'add', a: { op: 'mul', k, a: counts.find(c => c.v === v).body }, b: rest }), { op: 'const', value: 0 });
500
+ const auxiliary = { name: `${id}: linear cut ${i}`, hyps: [...l.when,
501
+ { op: '<', a: { op: 'var', name: first.key }, b: first.below }, { op: '<', a: term(l.neg), b: term(l.pos) }] };
502
+ const proof = encode({ name: auxiliary.name, goal: auxiliary, tree: l.tree }, false, true, vars, maps);
503
+ const side = (xs) => list(xs.map(([k, v]) => `(${k}, ${ix(v)})`));
504
+ return `⟨${list(l.when.map(c))}, ${side(l.pos)}, ${side(l.neg)}, ${proof.tab}, ${proof.tree}⟩`;
505
+ }));
506
+ return { frames, monos, lins };
507
+ }
508
+ // A single counted obligation, including conditional frames. This is a conditional
509
+ // goal theorem through mcF_sound, not a claim that the source machine's INIT or
510
+ // its other operation goals have been proved.
511
+ export function mcToLean(id, hyps, decls, cert) {
512
+ if (!checkMC(hyps, decls, cert))
513
+ throw new Error(`${id}: counted certificate does not check`);
514
+ const goal = mcGoal(hyps, decls, cert);
515
+ const extra = lemmaNames(cert.lemmas ?? [], cert.frames, cert.monos, cert.lins);
516
+ const vars = [...new Set([...extra.vars, ...goal.hyps.flatMap(varsOf),
517
+ ...decls.flatMap(d => [d.j, d.lo ?? d.j, d.key, ...varsOfE(d.below), ...varsOfE(d.body)]),
518
+ ...cert.reads.flatMap(r => [r[0], ...varsOfE(r[2])]),
519
+ ...cert.insts.flatMap(i => [i.wit, ...varsOfE(i.below)]),
520
+ ...(cert.picks ?? []).flatMap(([v, ks]) => [v, ...ks.flatMap(varsOfE)])])];
521
+ const maps = [...new Set([...extra.maps, ...goal.hyps.flatMap(mapsOf), ...decls.flatMap(d => [d.map, ...mapsOf(d.below), ...mapsOf(d.body)])])];
522
+ const enc = encodeCounted(id, goal, cert, vars, maps), { e, c } = enc;
523
+ const ix = (name) => { const i = vars.indexOf(name); if (i < 0)
524
+ throw new Error(`${id}: unknown variable ${name}`); return i; };
525
+ const mx = (name) => maps.indexOf(name);
526
+ const { frames, monos, lins } = cutLits(id, cert, decls, enc, vars, maps, c, ix);
527
+ const linRef = cert.lins?.length ? `${id}_lins` : '[]';
528
+ const linDefinition = cert.lins?.length ? `def ${id}_lins : List LinCut := ${lins}\n` : '';
529
+ const monoRef = cert.monos?.length ? `${id}_monos` : '[]';
530
+ const monoDefinition = cert.monos?.length ? `def ${id}_monos : List MonoCut := ${monos}\n` : '';
531
+ return `-- Goal-local counted certificate; no whole-machine reachability claim.
532
+ def ${id}_hyps : List C := ${list(hyps.map(c))}
533
+ -- CDecl.post is unused by checkMCF/GHolds; this packet already contains PRE/POST declarations.
534
+ def ${id}_decls : List CDecl := ${list(decls.map(d => `⟨${mx(d.map)}, ${mx(d.map)}, ${ix(d.j)}, ${ix(d.key)}, ${e(d.below)}, ${e(d.body)}, ${ix(d.lo ?? d.j)}, ${d.base ?? 0}⟩`))}
535
+ def ${id}_cert : CCert := ⟨${id}_hyps,
536
+ ${list(cert.reads.map(r => `(${ix(r[0])}, ${mx(r[1])}, ${e(r[2])})`))},
537
+ ${list(cert.insts.map(i => `⟨${ix(i.wit)}, ${e(i.below)}, ${list(i.terms.map(([z, v]) => `(${int(z)}, ${ix(v)})`))}, ${int(i.unit)}⟩`))},
538
+ ${enc.tab}, ${enc.tree},
539
+ ${list((cert.picks ?? []).map(([v, ks]) => `(${ix(v)}, ${list(ks.map(e))})`))}, ${enc.lemmas}⟩
540
+ def ${id}_frames : List FrameCut := ${frames}
541
+ ${monoDefinition}${linDefinition}theorem ${id}_check : checkMCF ${id}_hyps ${id}_decls ${id}_cert ${id}_frames ${monoRef}${cert.lins?.length ? ` ${linRef}` : ''} = true := by ${checkBy}
542
+ theorem ${id} (ρ : Nat → Nat) (M : Nat → Nat → Nat) (hd : GHolds ${id}_decls ρ M)
543
+ (hH : ∀ ρw : Nat → Nat, (∀ j, (∀ i ∈ ${id}_cert.insts, i.wit ≠ j) → ρw j = ρ j) →
544
+ ∀ h ∈ ${id}_hyps, evalC ρw M h = true) : False :=
545
+ mcF_sound ${id}_hyps ${id}_decls ${id}_cert ${id}_frames ${monoRef} ${linRef} ${id}_check ρ M hd hH`;
546
+ }
451
547
  export function countedToLean(id, g, cert, tampered = []) {
452
548
  const goal = countedGoal(g, cert.insts);
453
549
  if (!goal)
@@ -484,7 +580,7 @@ export function cmachineToLean(id, m, laws, proof, tampers = []) {
484
580
  const sm = { ...m, counts: undefined, inputMaps: [...(m.inputMaps ?? []), ...counts.map(([cn]) => cn)] };
485
581
  const named = machineNames(sm, laws, [], [], {});
486
582
  const allCerts = [proof.certs, ...tampers.map(t => t.certs)];
487
- const extra = allCerts.flatMap(cs => Object.values(cs).map(k => lemmaNames(k.lemmas ?? [])));
583
+ const extra = allCerts.flatMap(cs => Object.values(cs).map(k => lemmaNames(k.lemmas ?? [], k.frames, k.monos, k.lins)));
488
584
  const goals = obl.map(o => { const g = mcGoal(o.goal.hyps, o.decls, proof.certs[o.goal.name]); if (!g)
489
585
  throw new Error(`${id}: ${o.goal.name}: a read of no count`); return g; });
490
586
  const certVars = allCerts.flatMap(cs => Object.values(cs).flatMap(k => [...k.reads.flatMap(r => [r[0], ...varsOfE(r[2])]), ...k.insts.flatMap(i => [i.wit, ...varsOfE(i.below)]), ...(k.picks ?? []).flatMap(([v2, ks]) => [v2, ...ks.flatMap(varsOfE)])]));
@@ -531,12 +627,29 @@ export function cmachineToLean(id, m, laws, proof, tampers = []) {
531
627
  ${list((k.picks ?? []).map(([v2, ks]) => `(${ix(v2)}, ${list(ks.map(e))})`))},
532
628
  ${tt.lemmaList(k.lemmas ?? [])}⟩`;
533
629
  };
630
+ // A certificate's cuts, encoded against the same table as its tree (a tampered certificate keeps the cuts of the one
631
+ // it tampers with, as it keeps its table and tree). Emitted only when some certificate of this export has a cut: an
632
+ // export without cuts is the text it was before.
633
+ const hasCuts = (k) => !!(k.frames?.length || k.monos?.length || k.lins?.length);
634
+ const withAux = allCerts.some(cs => Object.values(cs).some(hasCuts));
635
+ const auxLit = (name, certs) => {
636
+ const o = obl.find(o2 => o2.goal.name === name), k = certs[name], k0 = proof.certs[name];
637
+ if (!hasCuts(k) && !hasCuts(k0))
638
+ return '⟨[], [], []⟩';
639
+ // The table is the original certificate's (as for its tree); the cuts are this certificate's own, so a tamper
640
+ // that drops or alters a cut is exported as altered and Lean computes the check without it.
641
+ const tt = encodeCounted(`${id}: ${name}`, mcGoal(o.goal.hyps, o.decls, k0), k0, vars, maps);
642
+ const cuts = cutLits(`${id}: ${name}`, { ...k0, frames: k.frames, monos: k.monos, lins: k.lins }, o.decls, tt, vars, maps, c, ix);
643
+ return `⟨${cuts.frames}, ${cuts.monos}, ${cuts.lins}⟩`;
644
+ };
534
645
  const entries = (certs) => laws.map(law => {
535
646
  const inst = proof.instances[law.name] ?? {};
536
647
  return `⟨⟨⟨${c(law.holds)}, ${law.forall ? `some ${ix(law.forall)}` : 'none'}⟩, ${ix(law.forall ? `${law.forall}#` : '#')}, ${list((law.keys ?? []).map(key => String(ix(key))))}, ${list(insts(inst))}, ${list(qinsts(inst))}, ${list(finsts(inst))}, ${list(pinsts(inst))}, ${list(pfinsts(inst))},
537
648
  ([], [], .leaf [] [] [] []), ([], [], .leaf [] [] [] [])⟩,
538
649
  ${certLit(`${law.name} @start`, certs)},
539
- ${certLit(`${law.name} @step`, certs)}⟩`;
650
+ ${certLit(`${law.name} @step`, certs)}${withAux ? `,
651
+ ${auxLit(`${law.name} @start`, certs)},
652
+ ${auxLit(`${law.name} @step`, certs)}` : ''}⟩`;
540
653
  });
541
654
  return `-- ${m.name}: ${laws.map(l => l.name).join('; ')}, with counts ${counts.map(([cn]) => cn).join(', ')}
542
655
  -- (variables ${vars.map((v2, j) => `${j} ${v2}`).join(', ')}; maps ${maps.map((v2, j) => `${j} ${v2}`).join(', ')})
@@ -545,13 +658,13 @@ def ${id}_machine : SMachine := ${machineLit(sm, { e, c }, ix, mx)}${renames.len
545
658
  def ${id}_renames : List QAlpha.Rename := ${list(renames.map(r => `⟨${ix(`?${r.flag}`)}, ${ix(r.old)}, ${ix(r.fresh)}⟩`))}
546
659
  def ${id}_checkedMachine : SMachine := QAlpha.renameAll ${id}_machine ${id}_renames` : ''}
547
660
  def ${id}_decls : List CDecl := ${list(counts.map(([cn, d]) => `⟨${mx(cn)}, ${mx(postName(cn))}, ${ix(d.j)}, ${ix(d.key)}, ${e(d.below)}, ${e(d.body)}, ${ix(d.lo ?? d.j)}, ${d.base ?? 0}⟩`))}
548
- def ${id}_proof : List CEntry := ${list(entries(proof.certs))}
549
- theorem ${id}_check : checkCMachine ${checked} ${id}_decls ${id}_proof = true := by ${checkBy}
661
+ ${withAux ? 'noncomputable ' : ''}def ${id}_proof : List ${withAux ? 'CEntryF' : 'CEntry'} := ${list(entries(proof.certs))}
662
+ theorem ${id}_check : ${withAux ? 'checkCMachineF' : 'checkCMachine'} ${checked} ${id}_decls ${id}_proof = true := by ${checkBy}
550
663
  /-- ${laws.map(l => l.name).join('; ')}: each holds in every reachable state, each count map read as the state's count. -/
551
664
  theorem ${id}_laws : ∀ ρ M, CReach ${id}_machine ${id}_decls ρ M → ∀ ce ∈ ${id}_proof, ce.e.Holds ρ (withCnt ${id}_decls ρ M) :=
552
- ${renames.length ? `QAlpha.cmachine_sound ${id}_machine ${id}_renames ${id}_decls ${id}_proof (by ${checkBy}) ${id}_check` : `cmachine_sound ${id}_machine ${id}_decls ${id}_proof ${id}_check`}${tampers.map(t => `
665
+ ${renames.length ? `QAlpha.${withAux ? 'cmachineF_sound' : 'cmachine_sound'} ${id}_machine ${id}_renames ${id}_decls ${id}_proof (by ${checkBy}) ${id}_check` : `${withAux ? 'cmachineF_sound' : 'cmachine_sound'} ${id}_machine ${id}_decls ${id}_proof ${id}_check`}${tampers.map(t => `
553
666
  -- TAMPERED: ${t.what}. Lean computes the check to false, as kernel.ts refuses it.
554
- example : checkCMachine ${checked} ${id}_decls ${list(entries(t.certs))} = false := by ${checkBy}`).join('')}`;
667
+ example : ${withAux ? 'checkCMachineF' : 'checkCMachine'} ${checked} ${id}_decls ${list(entries(t.certs))} = false := by ${checkBy}`).join('')}`;
555
668
  }
556
669
  // Whole machines through Kern.machine_sound: Lean builds the goals from the machine; the trees are the kernel's.
557
670
  export function machineToLean(id, m, laws, corollary) {
@@ -947,10 +1060,15 @@ export function readable(id, laws, vars, maps, reach) {
947
1060
  throw new Error(`${id}: no variable for ${name}`); return i; };
948
1061
  const ws = ex.vars.map((_, i) => `w${i + 1}`), at = (env, vals) => `updAll ${env} [${ex.vars.map((n, i) => `(${ix(n)}, ${vals[i]})`).join(', ')}]`;
949
1062
  const P = `(${lit(ex.body)})`, key = law.forall ? ix(law.forall) : undefined;
950
- const sigma = ex.sub ? `[${ex.vars.map(n => `(${ix(n)}, ${eLit(ex.sub[n])})`).join(', ')}]` : '';
951
- const machine = ex.ghost ? `${id}_ghosted.orig` : `${id}_machine`;
1063
+ // A retained family may carry ex.ghost metadata without exporting the
1064
+ // original/ghosted pair. In that case its theorem is about this machine:
1065
+ // choose its current witness values, not a nonexistent _ghosted.orig.
1066
+ const throughGhosts = ex.ghost && reach.ghosts;
1067
+ const sub = ex.sub ?? (ex.ghost && !throughGhosts ? Object.fromEntries(ex.vars.map(n => [n, { op: 'var', name: n }])) : undefined);
1068
+ const sigma = sub ? `[${ex.vars.map(n => `(${ix(n)}, ${eLit(sub[n])})`).join(', ')}]` : '';
1069
+ const machine = throughGhosts ? `${id}_ghosted.orig` : `${id}_machine`;
952
1070
  const head = `theorem some${j} : ∀ ρ μ, SReach ${machine} ρ μ → ${key !== undefined ? '∀ k : Nat, ' : ''}∃ ${ws.join(' ')} : Nat, evalC (${at(key !== undefined ? `(upd ρ ${key} k)` : 'ρ', ws)}) μ ${P} = true`;
953
- const proof = ex.ghost
1071
+ const proof = throughGhosts
954
1072
  ? ` intro ρ μ h
955
1073
  obtain ⟨ρg, hg⟩ := some_of_ghost ${id}_ghosted ${id}_ghostOk [${ex.vars.map(ix).join(', ')}] ${P} (by ${checkBy}) (fun ρ μ h => by
956
1074
  ${haveOf(j)}
@@ -965,7 +1083,7 @@ export function readable(id, laws, vars, maps, reach) {
965
1083
  theorem law${j} ${reach.binders} (h : SReach ${machine} ρ μ) : ${statement(law)} := by
966
1084
  ${key !== undefined ? 'intro k\n ' : ''}obtain ⟨${ws.join(', ')}, hg⟩ := some${j} ρ μ h${key !== undefined ? ' k' : ''}
967
1085
  exact ⟨${ws.join(', ')}, (evalC_iff (${at(key !== undefined ? `(upd ρ ${key} k)` : 'ρ', ws)}) μ ${P}).mp hg⟩`;
968
- return `-- ${law.name}: there exists, proven ${ex.ghost ? 'through ghosts the machine carries' : 'with its witness terms in place'}
1086
+ return `-- ${law.name}: there exists, proven ${throughGhosts ? 'through ghosts the machine carries' : ex.ghost ? 'with current-machine witness values' : 'with its witness terms in place'}
969
1087
  ${head} := by
970
1088
  ${proof}
971
1089
  ${plain}`;
@@ -1709,7 +1827,7 @@ def ${id}_proof : List SEntry := ${list(laws.map((_, j) => `${id}_e${j}`))}
1709
1827
  theorem ${id}_check : checkSMachine ${id}_machine ${id}_proof = true := by ${checkBy}
1710
1828
  theorem ${id}_laws : ∀ ρ M, SReach ${id}_machine ρ M → ∀ e ∈ ${id}_proof, e.Holds ρ M :=
1711
1829
  smachine_sound ${id}_machine ${id}_proof ${id}_check
1712
- ${hm ? histBlock() : readable(id, laws, vars, mapNames, { binders: '(ρ : Nat → Nat) (μ : Nat → Nat → Nat)', hyp: `SReach ${id}_machine ρ μ`, call: `${id}_laws ρ μ h`, lit: c, eLit: e })}${sm ? sumsBlock() : ''}${opts.noFacts ? '' : factsProof(id, m, mapNames, vars, opts.simp)}${opts.tamper ? `
1830
+ ${hm ? histBlock() : readable(id, laws, vars, mapNames, { binders: '(ρ : Nat → Nat) (μ : Nat → Nat → Nat)', hyp: `SReach ${id}_machine ρ μ`, call: `${id}_laws ρ μ h`, lit: c, eLit: e, ghosts: !rf && !gm && gv.length > 0 })}${sm ? sumsBlock() : ''}${opts.noFacts ? '' : factsProof(id, m, mapNames, vars, opts.simp)}${opts.tamper ? `
1713
1831
  -- TAMPERED: ${opts.tamper.what}. Lean computes the check to false.
1714
1832
  def ${id}_tampered : SMachine := ${lit(opts.tamper.machine)}
1715
1833
  example : checkSMachine ${id}_tampered ${id}_proof = false := by ${checkBy}` : ''}${records.length ? `\n\n${records.join('\n\n')}` : ''}${opts.after ? `\n\n${opts.after(ix, mx, lit)}` : ''}`;
@@ -2029,7 +2147,7 @@ ${cycProofText(id, p, [], vars, maps)}
2029
2147
  ${okLemmas}
2030
2148
  ${lawBlocks}
2031
2149
  ${lawsThm}
2032
- ${hm ? histBlock() : readable(id, laws, vars, maps, { binders: '(ρ : Nat → Nat) (μ : Nat → Nat → Nat)', hyp: `SReach ${id}_machine ρ μ`, call: '', lit: c, eLit: e,
2150
+ ${hm ? histBlock() : readable(id, laws, vars, maps, { binders: '(ρ : Nat → Nat) (μ : Nat → Nat → Nat)', hyp: `SReach ${id}_machine ρ μ`, call: '', lit: c, eLit: e, ghosts: !rf && gv.length > 0,
2033
2151
  have: j => `have hl : holdsOver ${id}_l${j} μ ${keys2(laws[j])} ρ := cyc_machine_holds (${id}_law${j}_holds ρ μ h)` })}${opts.noFacts ? '' : factsProof(id, m, maps, vars, opts.simp)}${records.length ? `\n\n${records.join('\n\n')}` : ''}${opts.after ? `\n\n${opts.after(ix)}` : ''}` };
2034
2152
  }
2035
2153
  // A fold from its cyclic proof (Bridge.lean's cyc_fold_sound): the fold numbered as foldToLean numbers it, each law's
@@ -2507,9 +2625,13 @@ export { rationalsToLean } from "./qlean.js";
2507
2625
  // A Lake project that builds the twin and the file: `lake build` in its folder checks every proof.
2508
2626
  export function leanProject(file, opts = {}) {
2509
2627
  const name = opts.name ?? 'Proofs';
2510
- const modules = [...Object.keys(leanLibrary).map(f => f.replace(/\.lean$/, '')), name];
2628
+ // Only generated cut-family declarations need the new family library. Merely
2629
+ // mentioning CEntryF in a comment or identifier must not change a cut-free project.
2630
+ const cutFamily = /^(?:noncomputable )?def [^\s:]+ : List CEntryF :=/m.test(file);
2631
+ const library = cutFamily ? leanLibrary : { ...leanLibrary, ...legacyFamilyLibrary };
2632
+ const modules = [...Object.keys(library).map(f => f.replace(/\.lean$/, '')), name];
2511
2633
  return {
2512
- ...leanLibrary,
2634
+ ...library,
2513
2635
  [`${name}.lean`]: file,
2514
2636
  'lean-toolchain': 'leanprover/lean4:v4.34.0\n',
2515
2637
  'lakefile.lean': `import Lake
@@ -0,0 +1 @@
1
+ export declare const legacyFamilyLibrary: Readonly<Record<string, string>>;