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
@@ -0,0 +1,331 @@
1
+ // Optional structural quorum/leader strategy. Every auxiliary is regenerated
2
+ // and checked on this machine; no saved fact or domain assertion is trusted.
3
+ import { n, x, get, same, walkOnce } from "./machine.js";
4
+ import { discoverCountThresholdWrite } from "./count-write-shape.js";
5
+ import { countFrameConditions, fixedCountFrameCase, ownCountLawInstance } from "./count-frames.js";
6
+ import { finishCountStrategy, strategyLeafUntil } from "./count-strategy.js";
7
+ import { proveLeaderCountFacts } from "./count-leader-facts.js";
8
+ import { countPrimitiveUnits } from "./count-primitive-budget.js";
9
+ import { guardLinearFact } from "./count-guard-facts.js";
10
+ import { boundedQuotient } from "./count-bounded-quotient.js";
11
+ import { countGuardTree } from "./count-guard-tree.js";
12
+ import { countsForReads } from "./count-facts.js";
13
+ import { add, k, scale, sub, solve } from "./solver.js";
14
+ import { assumed, canon, check, countedObligations, frameOk, framePath, linear, linOk, mcGoal } from "../kernel/kernel.js";
15
+ import { clock, fullRate, fullWork, grow, pastWall, rowsAt, withDeadline } from "../kernel/prove.js";
16
+ import { growCdcl } from "../kernel/cdcl.js";
17
+ import { countQueryConjuncts, countSearchView, proveCountQuery } from "./count-query.js";
18
+ import { rebasePath } from "./count-recovery/rebase-path.js";
19
+ import { reframeCountTree } from "./count-recovery/reframe-tree.js";
20
+ import { replayLinearSkeleton } from "./count-recovery/replay-linear-skeleton.js";
21
+ // The exact structural citation selected by the leader emitter, also exposed to
22
+ // prerequisite scheduling. Discovery does not prove the cited law.
23
+ export function countLeaderPremise(m, shape, family) {
24
+ const mapReads = (t) => { const names = []; walkOnce(t, (node) => { if (node.op === 'get' && m.counts?.[node.map] && !names.includes(node.map))
25
+ names.push(node.map); }); return names; };
26
+ const pairMapsFor = (law) => mapReads(law.holds).filter(name => !!m.counts[name].base);
27
+ const pairLaws = family.filter(law => law.forall && law.keys?.length === 3 && pairMapsFor(law).length === 2 && pairMapsFor(law).every(name => { const fields = new Set(); walkOnce(m.counts[name].body, (node) => { if (node.op === 'get')
28
+ fields.add(node.map); }); return fields.size === 1 && fields.has(shape.membershipMap); }));
29
+ const eligibilityFor = (law) => mapReads(law.holds).find(name => { const d = m.counts[name], fields = new Set(); walkOnce(d.body, (node) => { if (node.op === 'get')
30
+ fields.add(node.map); }); return !d.base && name !== shape.rowMap && fields.has(shape.membershipMap) && !fields.has(shape.memberField); });
31
+ const law = pairLaws.find(law => eligibilityFor(law)) ?? pairLaws[0];
32
+ return law ? { law, maps: pairMapsFor(law), eligibilityMap: eligibilityFor(law) } : undefined;
33
+ }
34
+ export function proveCountLeader(context, family, law, seed, until, requestFor, observe, options = {}) {
35
+ return withDeadline(until, () => {
36
+ const leaderStart = fullWork();
37
+ const m = context.machine, shape = context.shape, choice = fixedCountFrameCase(m), index = family.indexOf(law);
38
+ if (!choice || index < 0 || clock() >= until || pastWall())
39
+ return;
40
+ const write = discoverCountThresholdWrite(context.original, shape, choice);
41
+ if (!write || write.increment !== 1)
42
+ return;
43
+ const saved = proveLeaderCountFacts(context, family, law, until, requestFor, options.leafUnits);
44
+ if (!saved)
45
+ return;
46
+ const upperFact = saved.facts.find(f => f.proposal.kind === 'guard-complement-upper');
47
+ if (!upperFact || upperFact.proposal.when.length < 4)
48
+ return;
49
+ const { rowMap, voteMap } = shape, guardMap = write.input, i = x(write.source), a = x(law.forall + '#'), b = x(law.keys[0]);
50
+ const selectedPair = countLeaderPremise(m, shape, family), pairLaw = selectedPair?.law, eligibilityMap = selectedPair?.eligibilityMap;
51
+ options.trace?.({ query: 'leader-pair-premise', outcome: pairLaw ? 'selected' : 'missing', premises: pairLaw ? [pairLaw.name] : [], eligibilityMap });
52
+ if (!pairLaw || !selectedPair)
53
+ return;
54
+ const pairMaps = selectedPair.maps, onlyMap = pairMaps.find(name => { let neg = false; walkOnce(m.counts[name].body, (node) => { if (node.op === 'not')
55
+ neg = true; }); return neg; }), bothMap = pairMaps.find(name => name !== onlyMap);
56
+ if (!onlyMap || !bothMap)
57
+ return;
58
+ const key = (map, args) => { const d = m.counts[map.replace(/#$/, '')]; return d.base ? { op: 'add', a: { op: 'mul', k: d.base, a: args[0] }, b: args[1] } : args[0]; };
59
+ const read = (map, args) => get(map, key(map, args)), sum = (a, b) => ({ op: 'add', a, b });
60
+ const na = sum(read(onlyMap, [a, i]), read(bothMap, [a, i])), ni = sum(read(onlyMap, [i, a]), read(bothMap, [a, i]));
61
+ let upper = 0;
62
+ walkOnce(m.pre ?? [], (node) => { if (node.op === '<=' && node.b.op === 'const')
63
+ upper = Math.max(upper, node.b.value); });
64
+ if (!Number.isSafeInteger(upper) || upper < 1 || upper > 4096)
65
+ return;
66
+ const sourceVoteMap = voteMap, sMap = context.inputCounts[guardMap], outsideMap = context.restrictions.find(e => e.base === rowMap && e.input === guardMap)?.negative;
67
+ const inputRowMap = Object.keys(m.counts).find(name => { const d = m.counts[name]; let source = false; const fields = new Set(); walkOnce(d.body, (node) => { if (node.op === 'get')
68
+ fields.add(node.map); if (node.op === 'var' && node.name === write.source)
69
+ source = true; }); return !d.base && source && fields.size === 1 && fields.has(shape.membershipMap); });
70
+ if (!sMap || !outsideMap || !inputRowMap)
71
+ return;
72
+ const scope = JSON.stringify([m, family, seed]);
73
+ let prefix = 'ordinary$';
74
+ while (scope.includes('"' + prefix))
75
+ prefix = '$' + prefix;
76
+ const labels = ['subset', 'union', 'bound-a', 'bound-i', 'row-source', 'source-row', 'term', ...(eligibilityMap ? ['eligible-source', 'eligible-target'] : [])].map(name => prefix + name);
77
+ const halves = [boundedQuotient(na, 2, upper), boundedQuotient(ni, 2, upper)];
78
+ const pairTerms = [a, i, ...halves], pairInstance = assumed([pairLaw], { [pairLaw.name]: pairTerms })[0];
79
+ const instances = { ...ownCountLawInstance(law, seed), [pairLaw.name]: [...(seed[pairLaw.name] ?? []), ...pairTerms] };
80
+ // The source row uses this same restricted invariant, not a weaker law
81
+ // that may already have been refuted by candidate admission.
82
+ instances[law.name] = [...(instances[law.name] ?? []), i, b];
83
+ for (const [name, q] of Object.entries(m.step.flags ?? {}))
84
+ if (q.op === 'all' && !q.keys?.length) {
85
+ let relevant = false;
86
+ walkOnce(q.c, (node) => { if (node.op === 'get' && node.map === guardMap)
87
+ relevant = true; });
88
+ if (relevant)
89
+ instances['?' + name] = [...(seed['?' + name] ?? []), ...labels.map(x)];
90
+ }
91
+ const step = countedObligations(m, family, { [law.name]: instances }, index).at(-1);
92
+ const base = requestFor(step.goal, step.decls), reads = [...base.reads];
93
+ const bind = (map, args) => { const term = key(map, args), old = reads.find(r => r[1] === map && JSON.stringify(r[2]) === JSON.stringify(term)); if (old)
94
+ return old[0]; const name = prefix + 'read' + reads.length; reads.push([name, map, term]); return name; };
95
+ const names = { S: bind(sMap, [n(0)]), X: bind(inputRowMap, [n(0)]), A: bind(rowMap, [a]), B: bind(rowMap, [i]), O: bind(outsideMap, [a]), L: bind(onlyMap, [a, i]), R: bind(onlyMap, [i, a]), I: bind(bothMap, [a, i]), V: bind(sourceVoteMap, [i, b]) };
96
+ const eligible = eligibilityMap ? { source: bind(eligibilityMap, [i]), target: bind(eligibilityMap, [a]), postVotes: bind(voteMap + '#', [a, b]) } : undefined;
97
+ for (const f of saved.facts)
98
+ for (const [, name] of [...f.cut.pos, ...f.cut.neg]) {
99
+ const r = saved.reads.find(r => r[0] === name);
100
+ if (!reads.some(t => t[1] === r[1] && JSON.stringify(t[2]) === JSON.stringify(r[2])))
101
+ reads.push([prefix + 'read' + reads.length, r[1], r[2]]);
102
+ }
103
+ const counts = countsForReads(step.decls, reads);
104
+ if (!counts?.length)
105
+ return;
106
+ const bound = counts[0].below, insts = [
107
+ { wit: labels[0], below: bound, terms: [[1, names.S], [-1, names.B]], unit: 0 },
108
+ { wit: labels[1], below: bound, terms: [[1, names.S], [1, names.O], [-1, names.A], [-1, names.R]], unit: 0 },
109
+ { wit: labels[2], below: bound, terms: [[1, names.A]], unit: -1 },
110
+ { wit: labels[3], below: bound, terms: [[1, names.B]], unit: -1 },
111
+ { wit: labels[4], below: bound, terms: [[1, names.X], [-1, names.B]], unit: 0 },
112
+ { wit: labels[5], below: bound, terms: [[1, names.B], [-1, names.X]], unit: 0 },
113
+ { wit: labels[6], below: bound, terms: [[1, names.S], [-1, names.V]], unit: 0 },
114
+ ...(eligible ? [
115
+ { wit: labels[7], below: bound, terms: [[1, names.S], [-1, eligible.source]], unit: 0 },
116
+ { wit: labels[8], below: bound, terms: [[1, eligible.postVotes], [-1, eligible.target]], unit: 0 }
117
+ ] : [])
118
+ ];
119
+ const cert = { reads, insts, picks: [], tree: { leaf: [] }, lins: [], frames: [] }, goal = mcGoal(step.goal.hyps, step.decls, cert);
120
+ if (!goal)
121
+ return;
122
+ const remap = (side) => side.map(([coefficient, name]) => { const r = saved.reads.find(r => r[0] === name); return [coefficient, reads.find(t => t[1] === r[1] && JSON.stringify(t[2]) === JSON.stringify(r[2]))[0]]; });
123
+ for (const fact of saved.facts) {
124
+ const cut = { ...fact.cut, pos: remap(fact.cut.pos), neg: remap(fact.cut.neg) };
125
+ if (!linOk(counts, cut))
126
+ return;
127
+ cert.lins.push(cut);
128
+ }
129
+ options.trace?.({ query: 'leader-setup', units: (fullWork() - leaderStart) / fullRate });
130
+ const partition = (terms, name) => {
131
+ const started = fullWork(), leafEnd = strategyLeafUntil(until, options);
132
+ let searchEnd;
133
+ const fact = guardLinearFact(step.decls, reads, { name, kind: 'partition', when: [], terms }, Math.min(leafEnd, clock() + countPrimitiveUnits(600, options.leafUnits)), event => { searchEnd = event.searchEnd; });
134
+ const capped = leafEnd < until && (searchEnd ?? clock()) >= leafEnd;
135
+ if (fact && !capped)
136
+ cert.lins.push(fact.cut);
137
+ options.trace?.({ query: 'partition', name, outcome: capped ? 'leaf-cap' : fact ? 'proposed' : 'declined', units: (fullWork() - started) / fullRate });
138
+ return !!fact && !capped;
139
+ };
140
+ for (const [terms, name] of [
141
+ [[[1, names.A], [-1, names.L], [-1, names.I]], 'first row partition <='],
142
+ [[[-1, names.A], [1, names.L], [1, names.I]], 'first row partition >='],
143
+ [[[1, names.B], [-1, names.R], [-1, names.I]], 'source row partition <='],
144
+ [[[-1, names.B], [1, names.R], [1, names.I]], 'source row partition >='],
145
+ [[[1, names.O], [-1, names.A]], 'guard complement subset']
146
+ ])
147
+ if (!partition(terms, name))
148
+ return;
149
+ const split = countGuardTree(until);
150
+ const askInner = (path, stage) => {
151
+ if (clock() >= until || pastWall())
152
+ return;
153
+ const p = framePath(cert.frames ?? [], [], path, [], cert.lins), queryEnd = strategyLeafUntil(until, options);
154
+ if (options.minimalView && stage === 'count-fact') {
155
+ const selected = insts.find(inst => { const row = add(...inst.terms.map(([c, v]) => ({ [v]: c })), scale(linear(inst.below, p), inst.unit)); return p.get(canon(row))?.holds === false; });
156
+ const minimal = selected && countSearchView(step.goal, step.decls, cert, selected);
157
+ if (minimal) {
158
+ const tree = proveCountQuery(goal, p, until, { query: stage, minimal, direct: true, minimalUnits: countPrimitiveUnits(600, options.leafUnits), fullUnits: countPrimitiveUnits(250, options.leafUnits), leafUnits: Math.max(0, queryEnd - clock()), trace: options.trace });
159
+ observe?.(stage, !!tree);
160
+ return tree;
161
+ }
162
+ }
163
+ if (stage === 'quorum-transport') {
164
+ const started = fullWork(), end = until;
165
+ const required = new Set([names.S, names.O, names.A, names.B, names.L, names.R, names.I, ...(eligible ? [eligible.source, eligible.target] : [])]);
166
+ const domains = step.goal.hyps.flatMap(h => countQueryConjuncts(h)).filter(h => h.op === '<' && JSON.stringify(h.b) === JSON.stringify(bound) && [a, i].some(key => JSON.stringify(key) === JSON.stringify(h.a)));
167
+ const minimal = mcGoal([...countQueryConjuncts(m.pre ?? { op: 'and', xs: [] }), ...domains, pairInstance], step.decls, { reads: reads.filter(([id]) => required.has(id)), insts: [], picks: [] });
168
+ const clipped = [];
169
+ walkOnce(pairInstance, (node) => { if (node.op === 'sub' && !clipped.some(e => JSON.stringify(e) === JSON.stringify(node)))
170
+ clipped.push(node); });
171
+ if (!minimal || clipped.length !== 2)
172
+ return;
173
+ // Match natural subtraction's own decision: right <= left.
174
+ const cuts = [sub({ [names.O]: 1 }, linear(halves[0], p)), sub({ [names.S]: 1 }, linear(halves[1], p)), ...clipped.map(e => e.op === 'sub' ? sub(linear(e.b, p), linear(e.a, p)) : {})];
175
+ const local = countGuardTree(end);
176
+ const close = (at) => {
177
+ const before = fullWork(), leafEnd = strategyLeafUntil(until, options);
178
+ if (clock() >= leafEnd)
179
+ return;
180
+ const rows = rowsAt(minimal, at), result = withDeadline(leafEnd, () => solve(rows, 2000, true, () => clock() < leafEnd && !pastWall())), capped = leafEnd < until && clock() >= leafEnd;
181
+ const tree = result.kind === 'refuted' ? { leaf: result.steps } : undefined;
182
+ const accepted = !capped && tree && check(minimal, tree, at) ? tree : undefined;
183
+ options.trace?.({ query: 'quorum-linear-leaf', outcome: accepted ? 'proposed' : capped ? 'leaf-cap' : result.kind, units: (fullWork() - before) / fullRate, hyps: minimal.hyps.length, rows: rows.length, ...(!accepted ? { goal: minimal, path: [...at.values()], result } : {}) });
184
+ return accepted;
185
+ };
186
+ const choose = (j, at) => j === cuts.length ? close(at) : local.rows([cuts[j]], at, j < 2 ? close : q => choose(j + 1, q), q => choose(j + 1, q));
187
+ if (pairInstance.op !== 'or' || pairInstance.xs[0]?.op !== 'not')
188
+ return;
189
+ const guard = pairInstance.xs[0].x, disabled = pairInstance.xs.slice(2), base = m.counts[onlyMap].base;
190
+ const enter = (j, at) => j < disabled.length
191
+ ? local.condition(disabled[j], at, close, next => enter(j + 1, next))
192
+ : local.condition({ op: '<', a, b: n(base) }, at, next => local.condition({ op: '<', a: i, b: n(base) }, next, ready => choose(0, ready), close), close);
193
+ // Make the law's raw atoms explicit too: aliases imply them linearly,
194
+ // but truth() does not infer an equivalent decision through a binding.
195
+ const tree = local.condition(guard, p, at => enter(0, at), close), lifted = tree && rebasePath(minimal, tree, p, p, end, goal), checked = lifted && check(goal, lifted, p);
196
+ options.trace?.({ query: stage, mode: 'linear', outcome: checked ? 'proposed' : tree ? 'transport-rejected' : 'declined', units: (fullWork() - started) / fullRate, hyps: minimal.hyps.length, fullHyps: goal.hyps.length });
197
+ observe?.(stage, !!checked);
198
+ return checked ? lifted : undefined;
199
+ }
200
+ if (stage === 'count-fact') {
201
+ const selected = insts.find(inst => { const row = add(...inst.terms.map(([c, v]) => ({ [v]: c })), scale(linear(inst.below, p), inst.unit)); return p.get(canon(row))?.holds === false; });
202
+ if (selected) {
203
+ const hyps = step.goal.hyps.filter(h => { let choice = false; walkOnce(h, (node) => { if (node.op === 'if')
204
+ choice = true; }); return !choice; });
205
+ const view = mcGoal(hyps, step.decls, { reads, insts: [selected], picks: [] });
206
+ const result = growCdcl(view, p, { nodes: 0, until: Math.min(queryEnd, clock() + countPrimitiveUnits(600, options.leafUnits)) }), tree = 'tree' in result && clock() < queryEnd ? rebasePath(view, result.tree, p, p, until, goal) ?? replayLinearSkeleton(goal, result.tree, p, until) : undefined;
207
+ if (tree && check(goal, tree, p))
208
+ return tree;
209
+ }
210
+ }
211
+ if (stage === 'bounded-floor')
212
+ for (const value of [na, ni]) {
213
+ const half = boundedQuotient(value, 2, upper), twice = { op: 'mul', k: 2, a: half };
214
+ for (const fact of [{ op: '<=', a: twice, b: value }, { op: '<=', a: value, b: sum(twice, n(1)) }]) {
215
+ if (fact.op !== '<=')
216
+ continue;
217
+ const row = sub(linear(fact.a, p), linear(fact.b, p));
218
+ if (p.get(canon(row))?.holds !== false)
219
+ continue;
220
+ const auxiliary = { name: 'ordinary bounded floor', hyps: [{ op: '<=', a: value, b: n(upper) }, { op: 'not', x: fact }] };
221
+ const result = grow(auxiliary, new Map(), { nodes: 0, until: Math.min(queryEnd, clock() + countPrimitiveUnits(600, options.leafUnits)) }), tree = 'tree' in result && clock() < queryEnd && check(auxiliary, result.tree) ? rebasePath(auxiliary, result.tree, new Map(), p, until, goal) ?? replayLinearSkeleton(goal, result.tree, p, until) : undefined;
222
+ if (tree && check(goal, tree, p))
223
+ return tree;
224
+ }
225
+ }
226
+ if (stage === 'row-sum-bound') {
227
+ const domains = step.goal.hyps.flatMap(h => countQueryConjuncts(h)).filter(h => h.op === '<' && JSON.stringify(h.b) === JSON.stringify(bound) && [a, i].some(key => JSON.stringify(key) === JSON.stringify(h.a)));
228
+ const minimal = mcGoal([...countQueryConjuncts(m.pre ?? { op: 'and', xs: [] }), ...domains], step.decls, { reads, insts: [], picks: [] });
229
+ if (minimal)
230
+ return proveCountQuery(goal, p, until, { query: stage, minimal, direct: true, leafUnits: Math.max(0, queryEnd - clock()), trace: options.trace });
231
+ }
232
+ // Stage-specific auxiliary views above have the first chance. The full
233
+ // goal's direct solve is the last inexpensive fallback, not the first.
234
+ if (clock() >= queryEnd) {
235
+ options.trace?.({ query: stage, outcome: 'leaf-cap', units: 0 });
236
+ return;
237
+ }
238
+ const direct = solve(rowsAt(goal, p), 2000, true, () => clock() < queryEnd && !pastWall());
239
+ if (clock() >= queryEnd) {
240
+ options.trace?.({ query: stage, outcome: 'leaf-cap', units: 0 });
241
+ return;
242
+ }
243
+ if (direct.kind === 'refuted') {
244
+ const tree = { leaf: direct.steps };
245
+ if (check(goal, tree, p))
246
+ return tree;
247
+ }
248
+ const queryStart = fullWork();
249
+ const result = growCdcl(goal, p, { nodes: 0, until: Math.min(queryEnd, clock() + countPrimitiveUnits(250, options.leafUnits)) }), capped = queryEnd < until && clock() >= queryEnd, checked = !capped && 'tree' in result && check(goal, result.tree, p);
250
+ observe?.(stage, checked);
251
+ options.trace?.({ query: stage, outcome: capped ? 'leaf-cap' : checked ? 'proposed' : 'stuck' in result ? result.stuck : 'rejected', units: (fullWork() - queryStart) / fullRate, ...(!checked ? { goal, path: [...p.values()], ...('witness' in result ? { witness: result.witness } : {}), ...('why' in result ? { why: result.why } : {}) } : {}) });
252
+ return checked && 'tree' in result ? result.tree : undefined;
253
+ };
254
+ const memo = new Map();
255
+ const ask = (path, stage) => {
256
+ const started = fullWork(), p = framePath(cert.frames ?? [], [], path, [], cert.lins);
257
+ const minimal = countSearchView(step.goal, step.decls, cert) ?? goal;
258
+ const key = stage + '\n' + JSON.stringify(rowsAt(minimal, p).filter(row => row.src && 'fact' in row.src).map(row => canon(row.lin)).sort());
259
+ for (const entry of memo.get(key) ?? []) {
260
+ const tree = rebasePath(goal, entry.tree, entry.path, p, until, goal);
261
+ if (tree && check(goal, tree, p)) {
262
+ const framed = reframeCountTree(goal, tree, p, path, at => framePath(cert.frames ?? [], [], at, [], cert.lins), until);
263
+ if (framed) {
264
+ options.trace?.({ query: 'leader-ask', stage, kind: 'ask-total', mode: 'memo', outcome: 'proposed', units: (fullWork() - started) / fullRate, remaining: until - clock() });
265
+ return framed;
266
+ }
267
+ }
268
+ }
269
+ const tree = askInner(path, stage);
270
+ if (tree && check(goal, tree, p)) {
271
+ const entries = memo.get(key) ?? [];
272
+ if (entries.length < 8) {
273
+ entries.push({ path: new Map(p), tree });
274
+ memo.set(key, entries);
275
+ }
276
+ }
277
+ const framed = tree && reframeCountTree(goal, tree, p, path, at => framePath(cert.frames ?? [], [], at, [], cert.lins), until);
278
+ options.trace?.({ query: 'leader-ask', stage, kind: 'ask-total', mode: 'search', outcome: framed ? 'proposed' : clock() >= until ? 'pool-exhausted' : 'declined', units: (fullWork() - started) / fullRate, remaining: until - clock() });
279
+ return framed;
280
+ };
281
+ const frame = (p) => { for (const r of reads.filter(r => r[1] === voteMap + '#')) {
282
+ const pre = reads.find(t => t[1] === voteMap && JSON.stringify(t[2]) === JSON.stringify(r[2]));
283
+ if (!pre)
284
+ continue;
285
+ const cut = { post: r[0], pre: pre[0], when: [...p.values()].map(t => t.holds ? t.lin : add(scale(t.lin, -1), k(1))) };
286
+ if (frameOk(counts, cut))
287
+ cert.frames.push(cut);
288
+ } ; return ask(p, 'no-op'); };
289
+ const active = upperFact.proposal.when[1], postBound = upperFact.proposal.when[3];
290
+ // These facts do not depend on the target-column/source equality. Prove
291
+ // them once before that exhaustive split, rather than once in every arm.
292
+ const factRows = (p) => [add({ [names.X]: 1, [names.S]: -2 }, k(1)), ...[...insts.slice(0, 6), ...(eligible ? [insts[7]] : [])].map(inst => add(...inst.terms.map(([c, v]) => ({ [v]: c })), scale(linear(inst.below, p), inst.unit)))];
293
+ const transportRows = (at) => ({
294
+ floors: [na, ni].flatMap(value => { const half = boundedQuotient(value, 2, upper), twice = { op: 'mul', k: 2, a: half }; return [sub(linear(twice, at), linear(value, at)), add(sub(linear(value, at), linear(twice, at)), k(-1))]; }),
295
+ domains: [na, ni].map(value => add(linear(value, at), k(-upper)))
296
+ });
297
+ const finish = (p) => {
298
+ return split.condition(postBound, p, r => {
299
+ const transport = (at) => {
300
+ const { floors, domains } = transportRows(at);
301
+ return split.rows(domains, at, s => split.rows(floors, s, t => split.rows([{ [names.O]: 2, [names.A]: -1 }], t, u => ask(u, 'main-with-transport'), u => ask(u, 'quorum-transport')), t => ask(t, 'bounded-floor')), s => ask(s, 'row-sum-bound'));
302
+ };
303
+ if (!eligible)
304
+ return transport(r);
305
+ // A source quorum is eligible by the retained per-member guards. For a
306
+ // different target row, its post-votes are a subset of pre-eligibility.
307
+ // Both are proposed ordinary count witnesses, never assumed aliases.
308
+ return split.condition(same(a, i), r, transport, s => split.rows([{ [eligible.postVotes]: 1, [eligible.target]: -1 }], s, t => split.rows([{ [eligible.target]: 2, [names.A]: -1 }], t, u => ask(u, 'disabled-target'), transport), t => ask(t, 'count-fact')));
309
+ }, r => ask(r, 'term-bound'));
310
+ };
311
+ const domain = { op: 'and', xs: [a, b, i].flatMap(t => [{ op: '<', a: t, b: bound }, { op: '<', a: t, b: n(shape.width) }]) };
312
+ const cases = (p) => split.condition(same(b, i), p, finish, finish);
313
+ const beforeCases = (p) => {
314
+ const { domains, floors } = transportRows(p);
315
+ const queries = [...domains.map(row => ({ row, name: 'row-sum-bound', reject: (q) => ask(q, 'row-sum-bound') })), ...floors.map(row => ({ row, name: 'bounded-floor', reject: (q) => ask(q, 'bounded-floor') }))];
316
+ const afterCommon = (q) => !eligible ? cases(q) : split.condition(same(a, i), q, cases, r => split.hoist([{ row: { [eligible.postVotes]: 1, [eligible.target]: -1 }, name: 'eligibility', reject: (s) => ask(s, 'count-fact') }], [same(b, i)], r, cases, options.trace));
317
+ return split.hoist(queries, [same(a, i), same(b, i)], p, afterCommon, options.trace);
318
+ };
319
+ const tree = split.rows(countFrameConditions(choice), new Map(), p => split.condition(domain, p, q => split.condition(active, q, r => split.rows(factRows(r), r, beforeCases, q => ask(q, 'count-fact')), frame), q => ask(q, 'outside-domain')), p => ask(p, 'outside-operation'));
320
+ if (!tree)
321
+ return;
322
+ let last = fullWork();
323
+ const proof = finishCountStrategy(m, family, law, instances, voteMap, { ...cert, tree }, until, requestFor, (stage, checked) => {
324
+ const now = fullWork();
325
+ options.trace?.({ query: 'leader-final', stage, outcome: checked ? 'checked' : 'rejected', units: (now - last) / fullRate });
326
+ last = now;
327
+ }, options);
328
+ options.trace?.({ query: 'leader-total', outcome: proof ? options.deferToComposition ? 'proposed' : 'checked' : 'declined', units: (fullWork() - leaderStart) / fullRate });
329
+ return proof;
330
+ });
331
+ }
@@ -0,0 +1,8 @@
1
+ import { type C } from './machine.js';
2
+ import { type Lin } from './solver.js';
3
+ import { type Goal, type LemmaCut } from '../kernel/kernel.js';
4
+ export declare function transportCountLemmas(source: Goal, target: Goal, lemmas: LemmaCut[], scope: {
5
+ assumed: C;
6
+ retained?: C;
7
+ when: Lin[];
8
+ }, until: number): LemmaCut[] | undefined;
@@ -0,0 +1,47 @@
1
+ import { canon } from "../kernel/kernel.js";
2
+ import { late } from "../kernel/prove.js";
3
+ import { rebasePath } from "./count-rebase-path.js";
4
+ export function transportCountLemmas(source, target, lemmas, scope, until) {
5
+ const key = (v) => JSON.stringify(v), at = new Map();
6
+ target.hyps.forEach((hyp, i) => { const k = key(hyp); at.set(k, [...(at.get(k) ?? []), i]); });
7
+ const root = (cut, when) => { const out = new Map(); let n = 0; for (const atom of [{ lin: cut, holds: false }, ...when.map(lin => ({ lin, holds: true }))]) {
8
+ const id = canon(atom.lin);
9
+ out.set(out.has(id) ? '@' + n++ : id, atom);
10
+ } return out; };
11
+ const out = [];
12
+ for (const lemma of lemmas) {
13
+ if (late(until))
14
+ return;
15
+ const original = lemma.slice ?? source.hyps.map((_, i) => i), slice = [], used = new Set();
16
+ for (const i of original) {
17
+ if (!Number.isSafeInteger(i) || i < 0 || i >= source.hyps.length)
18
+ return;
19
+ const hyp = source.hyps[i], found = at.get(key(hyp));
20
+ if (found?.length === 1) {
21
+ if (used.has(found[0]))
22
+ return;
23
+ used.add(found[0]);
24
+ slice.push(found[0]);
25
+ continue;
26
+ }
27
+ if (found?.length || key(hyp) !== key(scope.assumed)) {
28
+ console.log('LEMMA_TRANSPORT_DECLINE ' + JSON.stringify({ stage: 'hyp-map', index: i, matches: found?.length ?? 0, hyp: key(hyp).slice(0, 4000), assumed: key(scope.assumed).slice(0, 4000) }));
29
+ return;
30
+ }
31
+ if (scope.retained) {
32
+ const retained = at.get(key(scope.retained));
33
+ if (retained?.length !== 1 || used.has(retained[0]))
34
+ return;
35
+ used.add(retained[0]);
36
+ slice.push(retained[0]);
37
+ }
38
+ }
39
+ const when = [...scope.when, ...lemma.when], tree = rebasePath({ ...source, hyps: original.map(i => source.hyps[i]) }, lemma.tree, root(lemma.cut, lemma.when), root(lemma.cut, when), until, { ...target, hyps: slice.map(i => target.hyps[i]) });
40
+ if (!tree) {
41
+ console.log('LEMMA_TRANSPORT_DECLINE ' + JSON.stringify({ stage: 'tree-reindex', original, slice, when: when.length }));
42
+ return;
43
+ }
44
+ out.push({ ...lemma, when, slice, tree });
45
+ }
46
+ return out;
47
+ }
@@ -0,0 +1,54 @@
1
+ import { type CountStrategyOptions } from './count-strategy.js';
2
+ import { type WorkAmount } from './work-amount.js';
3
+ import { type CountFundingOwners } from './count-disjoint-funding.js';
4
+ export type LiftedWorkSlice = Readonly<{
5
+ kind: 'case' | 'leaf';
6
+ key: string;
7
+ caseKey?: string;
8
+ allocation: WorkAmount;
9
+ scopeId: number;
10
+ rootEpoch: number;
11
+ }>;
12
+ export type LiftedWorkSliceObserver = (slice: LiftedWorkSlice) => void;
13
+ export type LiftedWorkTraceEvent = Readonly<{
14
+ stage: 'start';
15
+ slice: LiftedWorkSlice;
16
+ }> | Readonly<{
17
+ stage: 'end';
18
+ slice: LiftedWorkSlice;
19
+ used: WorkAmount;
20
+ completed: boolean;
21
+ error?: unknown;
22
+ }>;
23
+ export type LiftedWorkTrace = (event: LiftedWorkTraceEvent) => void;
24
+ export declare function withLiftedWorkSliceObservation<T>(observe: LiftedWorkSliceObserver, run: () => T): T;
25
+ export type LiftedLeasePlan = Readonly<{
26
+ original: WorkAmount;
27
+ leaf: WorkAmount;
28
+ operation: WorkAmount;
29
+ cases: Readonly<Record<string, WorkAmount>>;
30
+ observe?: LiftedWorkSliceObserver;
31
+ trace?: LiftedWorkTrace;
32
+ owners?: CountFundingOwners;
33
+ }>;
34
+ export type LiftedWorkBudget = Readonly<{
35
+ workAllowance: number;
36
+ leafUnits: number;
37
+ caseUnits: number;
38
+ full: boolean;
39
+ lease?: LiftedLeasePlan;
40
+ }>;
41
+ export declare function liftedWorkBudget(workAllowance: number, full?: boolean): LiftedWorkBudget;
42
+ export declare const liftedDeadline: (now: number, parent: number, units: number) => number;
43
+ export declare function liftedLeafUntil(until: number, options: CountStrategyOptions, legacy?: number): number;
44
+ export declare function liftedCaseUntil(until: number, budget: LiftedWorkBudget, frame?: boolean): number;
45
+ export declare function liftedWorkLeaseBudget(original: WorkAmount, overrides?: {
46
+ leaf?: WorkAmount;
47
+ cases?: Readonly<Record<string, WorkAmount>>;
48
+ observe?: LiftedWorkSliceObserver;
49
+ trace?: LiftedWorkTrace;
50
+ owners?: CountFundingOwners;
51
+ }): LiftedWorkBudget;
52
+ export declare function withLiftedLeaf<T>(until: number, options: CountStrategyOptions, legacy: number, key: string, run: (until: number) => T): T;
53
+ export declare function withLiftedCase<T>(until: number, budget: LiftedWorkBudget, frame: boolean, key: string, run: (until: number) => T): T;
54
+ export declare function liftedLeaseOptions(budget: LiftedWorkBudget, caseKey: string): Pick<CountStrategyOptions, 'leafUnits' | 'leafWork' | 'caseKey' | 'workSliceObserver' | 'workSliceTrace' | 'workOwners'>;
@@ -0,0 +1,97 @@
1
+ // W is the original enclosing CLOCK-unit allowance, not a remaining case share.
2
+ // Divide once: every local leaf uses W/120, every operation uses W/30, and
3
+ // both are clipped to the caller's absolute endpoint. Legacy search is exact.
4
+ import { completeWorkProfile } from "./work-profile.js";
5
+ import { strategyLeafUnits } from "./count-strategy.js";
6
+ import { clock } from "../kernel/prove.js";
7
+ import { countPrimitiveUnits } from "./count-primitive-budget.js";
8
+ import { workShare, workSub } from "./work-amount.js";
9
+ import { remainingAdmittedWork, workAdmissionSnapshot, workLedger } from "./work-admission.js";
10
+ let sliceObserver;
11
+ export function withLiftedWorkSliceObservation(observe, run) { const prior = sliceObserver; sliceObserver = observe; try {
12
+ return run();
13
+ }
14
+ finally {
15
+ sliceObserver = prior;
16
+ } }
17
+ export function liftedWorkBudget(workAllowance, full = completeWorkProfile.enabled) {
18
+ if (full && (!Number.isFinite(workAllowance) || workAllowance < 0))
19
+ throw new RangeError('invalid lifted work allowance');
20
+ return Object.freeze({ workAllowance, leafUnits: full ? strategyLeafUnits(workAllowance) : 500, caseUnits: full ? workAllowance / 30 : 2000, full });
21
+ }
22
+ export const liftedDeadline = (now, parent, units) => Math.min(parent, now + Math.max(0, units));
23
+ export function liftedLeafUntil(until, options, legacy = 500) {
24
+ return liftedDeadline(clock(), until, countPrimitiveUnits(legacy, options.leafUnits));
25
+ }
26
+ export function liftedCaseUntil(until, budget, frame = false) {
27
+ return liftedDeadline(clock(), until, countPrimitiveUnits(frame ? 500 : 2000, budget.caseUnits));
28
+ }
29
+ // Explicit opt-in. These amounts are RAW work from the original grant, never
30
+ // decoded from clock(), remaining capacity or a telemetry display. Infinity is
31
+ // only the legacy-until sentinel inside a live exact child scope.
32
+ export function liftedWorkLeaseBudget(original, overrides = {}) {
33
+ if (!completeWorkProfile.enabled)
34
+ throw new Error('lifted work leases require FULL accounting');
35
+ const valid = (amount) => { if (amount.den <= 0n || amount.num < 0n)
36
+ throw new RangeError('invalid lifted work grant'); };
37
+ valid(original);
38
+ const leaf = overrides.leaf ?? workShare(original, 1n, 120n), operation = workShare(original, 1n, 30n), cases = Object.freeze({ ...overrides.cases });
39
+ valid(leaf);
40
+ for (const amount of Object.values(cases))
41
+ valid(amount);
42
+ return Object.freeze({ workAllowance: Infinity, leafUnits: Infinity, caseUnits: Infinity, full: true, lease: Object.freeze({ original, leaf, operation, cases, observe: overrides.observe, trace: overrides.trace, owners: overrides.owners }) });
43
+ }
44
+ function withLiftedSlice(kind, key, allocation, observe, run, caseKey, trace) {
45
+ if (!key)
46
+ throw new Error('lifted work slice requires a stable key');
47
+ if (!completeWorkProfile.enabled || remainingAdmittedWork() === null)
48
+ throw new Error('lifted work slice requires an inherited FULL endpoint');
49
+ const state = {};
50
+ try {
51
+ return workLedger.withBudget(allocation, () => {
52
+ const snapshot = workAdmissionSnapshot(), scope = snapshot.activeEndpoints.at(-1);
53
+ const slice = { kind, key, caseKey, allocation, scopeId: scope.id, rootEpoch: snapshot.rootEpoch };
54
+ if (!trace) {
55
+ observe?.(slice);
56
+ sliceObserver?.(slice);
57
+ return run(Infinity);
58
+ }
59
+ state.receipt = { slice, before: workLedger.actual(), completed: false };
60
+ trace({ stage: 'start', slice });
61
+ observe?.(slice);
62
+ sliceObserver?.(slice);
63
+ const result = run(Infinity);
64
+ state.receipt.completed = true;
65
+ return result;
66
+ });
67
+ }
68
+ catch (error) {
69
+ if (state.receipt) {
70
+ state.receipt.error = error;
71
+ state.receipt.completed = false;
72
+ }
73
+ throw error;
74
+ }
75
+ finally {
76
+ const receipt = state.receipt;
77
+ // Finish bookkeeping after the expired local slice has unwound, but inside
78
+ // its real parent/round. If that parent cannot pay, its hard stop wins.
79
+ // `used` is exact work inside the physical slice, not its exit metadata.
80
+ if (receipt)
81
+ trace({ stage: 'end', slice: receipt.slice, used: workSub(workLedger.actual(), receipt.before), completed: receipt.completed, ...(!receipt.completed ? { error: receipt.error } : {}) });
82
+ }
83
+ }
84
+ export function withLiftedLeaf(until, options, legacy, key, run) {
85
+ if (options.workOwners)
86
+ return options.workOwners.leaf(key, () => run(Infinity), options.caseKey);
87
+ return options.leafWork === undefined ? run(liftedLeafUntil(until, options, legacy)) : withLiftedSlice('leaf', key, options.leafWork, options.workSliceObserver, run, options.caseKey, options.workSliceTrace);
88
+ }
89
+ export function withLiftedCase(until, budget, frame, key, run) {
90
+ const plan = budget.lease;
91
+ if (plan?.owners)
92
+ return plan.owners.case(key, () => run(Infinity));
93
+ return plan === undefined ? run(liftedCaseUntil(until, budget, frame)) : withLiftedSlice('case', key, plan.cases[key] ?? plan.operation, plan.observe, run, undefined, plan.trace);
94
+ }
95
+ export function liftedLeaseOptions(budget, caseKey) {
96
+ return { leafUnits: budget.leafUnits, ...(budget.lease ? { leafWork: budget.lease.leaf, caseKey, workSliceObserver: budget.lease.observe, workSliceTrace: budget.lease.trace, workOwners: budget.lease.owners } : {}) };
97
+ }
@@ -0,0 +1,3 @@
1
+ import { type Law, type Machine } from './machine.js';
2
+ import { type CountRequestBuilder, type CountStrategyOptions, type CountStrategyProof } from './count-strategy.js';
3
+ export declare function proveLiftedCountCopy(m: Machine, family: Law[], law: Law, until: number, requestFor: CountRequestBuilder, observe?: (event: Record<string, unknown>) => void, options?: CountStrategyOptions): CountStrategyProof | undefined;