@typeonce/effect-machine 0.47.1 → 0.48.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 (334) hide show
  1. package/AGENTS.md +374 -22
  2. package/CLAUDE.md +374 -22
  3. package/README.md +56 -7
  4. package/ai-docs/src/10_modeling/01_create-a-machine.ts +3 -3
  5. package/ai-docs/src/10_modeling/index.md +64 -17
  6. package/ai-docs/src/20_root-api/index.md +2 -2
  7. package/ai-docs/src/35_cluster/index.md +213 -0
  8. package/ai-docs/src/37_new-host/index.md +90 -0
  9. package/dist/LocalMachine.d.ts +417 -0
  10. package/dist/LocalMachine.d.ts.map +1 -0
  11. package/dist/LocalMachine.js +193 -0
  12. package/dist/LocalMachine.js.map +1 -0
  13. package/dist/Machine.d.ts +1120 -812
  14. package/dist/Machine.d.ts.map +1 -1
  15. package/dist/Machine.js +195 -186
  16. package/dist/Machine.js.map +1 -1
  17. package/dist/index.d.ts +1 -0
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +1 -0
  20. package/dist/index.js.map +1 -1
  21. package/dist/internal/machine/atom.d.ts +8 -10
  22. package/dist/internal/machine/atom.d.ts.map +1 -1
  23. package/dist/internal/machine/atom.js +7 -6
  24. package/dist/internal/machine/atom.js.map +1 -1
  25. package/dist/internal/machine/capability.d.ts +101 -0
  26. package/dist/internal/machine/capability.d.ts.map +1 -0
  27. package/dist/internal/machine/capability.js +70 -0
  28. package/dist/internal/machine/capability.js.map +1 -0
  29. package/dist/internal/machine/{invocationDefinition.d.ts → capturedInvocation.d.ts} +11 -11
  30. package/dist/internal/machine/capturedInvocation.d.ts.map +1 -0
  31. package/dist/internal/machine/{invocationDefinition.js → capturedInvocation.js} +2 -2
  32. package/dist/internal/machine/capturedInvocation.js.map +1 -0
  33. package/dist/internal/machine/child.d.ts +14 -0
  34. package/dist/internal/machine/child.d.ts.map +1 -0
  35. package/dist/internal/machine/child.js +19 -0
  36. package/dist/internal/machine/child.js.map +1 -0
  37. package/dist/internal/machine/childRegistry.d.ts +0 -2
  38. package/dist/internal/machine/childRegistry.d.ts.map +1 -1
  39. package/dist/internal/machine/childRegistry.js +2 -2
  40. package/dist/internal/machine/childRegistry.js.map +1 -1
  41. package/dist/internal/machine/cluster.d.ts +19 -4
  42. package/dist/internal/machine/cluster.d.ts.map +1 -1
  43. package/dist/internal/machine/cluster.js +263 -110
  44. package/dist/internal/machine/cluster.js.map +1 -1
  45. package/dist/internal/machine/clusterChild.d.ts +66 -0
  46. package/dist/internal/machine/clusterChild.d.ts.map +1 -0
  47. package/dist/internal/machine/clusterChild.js +105 -0
  48. package/dist/internal/machine/clusterChild.js.map +1 -0
  49. package/dist/internal/machine/clusterFailure.d.ts +14 -0
  50. package/dist/internal/machine/clusterFailure.d.ts.map +1 -0
  51. package/dist/internal/machine/clusterFailure.js +44 -0
  52. package/dist/internal/machine/clusterFailure.js.map +1 -0
  53. package/dist/internal/machine/clusterInstance.d.ts +194 -0
  54. package/dist/internal/machine/clusterInstance.d.ts.map +1 -0
  55. package/dist/internal/machine/clusterInstance.js +1076 -0
  56. package/dist/internal/machine/clusterInstance.js.map +1 -0
  57. package/dist/internal/machine/clusterKeepAlive.d.ts +47 -0
  58. package/dist/internal/machine/clusterKeepAlive.d.ts.map +1 -0
  59. package/dist/internal/machine/clusterKeepAlive.js +72 -0
  60. package/dist/internal/machine/clusterKeepAlive.js.map +1 -0
  61. package/dist/internal/machine/clusterProgress.d.ts +73 -0
  62. package/dist/internal/machine/clusterProgress.d.ts.map +1 -0
  63. package/dist/internal/machine/clusterProgress.js +116 -0
  64. package/dist/internal/machine/clusterProgress.js.map +1 -0
  65. package/dist/internal/machine/clusterProtocol.d.ts +37 -4
  66. package/dist/internal/machine/clusterProtocol.d.ts.map +1 -1
  67. package/dist/internal/machine/clusterProtocol.js +18 -4
  68. package/dist/internal/machine/clusterProtocol.js.map +1 -1
  69. package/dist/internal/machine/clusterProxy.d.ts +46 -0
  70. package/dist/internal/machine/clusterProxy.d.ts.map +1 -0
  71. package/dist/internal/machine/clusterProxy.js +150 -0
  72. package/dist/internal/machine/clusterProxy.js.map +1 -0
  73. package/dist/internal/machine/clusterRead.d.ts +61 -0
  74. package/dist/internal/machine/clusterRead.d.ts.map +1 -0
  75. package/dist/internal/machine/clusterRead.js +108 -0
  76. package/dist/internal/machine/clusterRead.js.map +1 -0
  77. package/dist/internal/machine/clusterSqlStorage.d.ts +16 -0
  78. package/dist/internal/machine/clusterSqlStorage.d.ts.map +1 -0
  79. package/dist/internal/machine/clusterSqlStorage.js +138 -0
  80. package/dist/internal/machine/clusterSqlStorage.js.map +1 -0
  81. package/dist/internal/machine/clusterStorageCheck.d.ts +19 -0
  82. package/dist/internal/machine/clusterStorageCheck.d.ts.map +1 -0
  83. package/dist/internal/machine/clusterStorageCheck.js +186 -0
  84. package/dist/internal/machine/clusterStorageCheck.js.map +1 -0
  85. package/dist/internal/machine/clusterTarget.d.ts +74 -0
  86. package/dist/internal/machine/clusterTarget.d.ts.map +1 -0
  87. package/dist/internal/machine/clusterTarget.js +81 -0
  88. package/dist/internal/machine/clusterTarget.js.map +1 -0
  89. package/dist/internal/machine/clusterTimer.d.ts +21 -0
  90. package/dist/internal/machine/clusterTimer.d.ts.map +1 -0
  91. package/dist/internal/machine/clusterTimer.js +50 -0
  92. package/dist/internal/machine/clusterTimer.js.map +1 -0
  93. package/dist/internal/machine/clusterWake.d.ts +61 -0
  94. package/dist/internal/machine/clusterWake.d.ts.map +1 -0
  95. package/dist/internal/machine/clusterWake.js +81 -0
  96. package/dist/internal/machine/clusterWake.js.map +1 -0
  97. package/dist/internal/machine/clusterWork.d.ts +130 -0
  98. package/dist/internal/machine/clusterWork.d.ts.map +1 -0
  99. package/dist/internal/machine/clusterWork.js +191 -0
  100. package/dist/internal/machine/clusterWork.js.map +1 -0
  101. package/dist/internal/machine/command.d.ts +4 -4
  102. package/dist/internal/machine/command.d.ts.map +1 -1
  103. package/dist/internal/machine/commandRuntime.d.ts +8 -6
  104. package/dist/internal/machine/commandRuntime.d.ts.map +1 -1
  105. package/dist/internal/machine/commandRuntime.js +1 -5
  106. package/dist/internal/machine/commandRuntime.js.map +1 -1
  107. package/dist/internal/machine/configuration.d.ts +0 -13
  108. package/dist/internal/machine/configuration.d.ts.map +1 -1
  109. package/dist/internal/machine/configuration.js +0 -151
  110. package/dist/internal/machine/configuration.js.map +1 -1
  111. package/dist/internal/machine/errors.d.ts +11 -2
  112. package/dist/internal/machine/errors.d.ts.map +1 -1
  113. package/dist/internal/machine/errors.js +11 -2
  114. package/dist/internal/machine/errors.js.map +1 -1
  115. package/dist/internal/machine/executionPlan.d.ts +45 -3
  116. package/dist/internal/machine/executionPlan.d.ts.map +1 -1
  117. package/dist/internal/machine/executionPlan.js +328 -191
  118. package/dist/internal/machine/executionPlan.js.map +1 -1
  119. package/dist/internal/machine/implementation.d.ts +6 -6
  120. package/dist/internal/machine/implementation.d.ts.map +1 -1
  121. package/dist/internal/machine/inspectionRuntime.d.ts +1 -1
  122. package/dist/internal/machine/inspectionRuntime.d.ts.map +1 -1
  123. package/dist/internal/machine/invocationChanges.d.ts +60 -0
  124. package/dist/internal/machine/invocationChanges.d.ts.map +1 -0
  125. package/dist/internal/machine/invocationChanges.js +54 -0
  126. package/dist/internal/machine/invocationChanges.js.map +1 -0
  127. package/dist/internal/machine/{activities.d.ts → invocationDefinitions.d.ts} +8 -8
  128. package/dist/internal/machine/invocationDefinitions.d.ts.map +1 -0
  129. package/dist/internal/machine/{activities.js → invocationDefinitions.js} +5 -5
  130. package/dist/internal/machine/invocationDefinitions.js.map +1 -0
  131. package/dist/internal/machine/invocationEvent.d.ts +16 -7
  132. package/dist/internal/machine/invocationEvent.d.ts.map +1 -1
  133. package/dist/internal/machine/invocationEvent.js +26 -12
  134. package/dist/internal/machine/invocationEvent.js.map +1 -1
  135. package/dist/internal/machine/invocationOutcome.d.ts +89 -0
  136. package/dist/internal/machine/invocationOutcome.d.ts.map +1 -0
  137. package/dist/internal/machine/invocationOutcome.js +76 -0
  138. package/dist/internal/machine/invocationOutcome.js.map +1 -0
  139. package/dist/internal/machine/invocationResolution.d.ts +137 -0
  140. package/dist/internal/machine/invocationResolution.d.ts.map +1 -0
  141. package/dist/internal/machine/invocationResolution.js +150 -0
  142. package/dist/internal/machine/invocationResolution.js.map +1 -0
  143. package/dist/internal/machine/logicScope.d.ts +24 -0
  144. package/dist/internal/machine/logicScope.d.ts.map +1 -0
  145. package/dist/internal/machine/logicScope.js +33 -0
  146. package/dist/internal/machine/logicScope.js.map +1 -0
  147. package/dist/internal/machine/machine.d.ts +17 -23
  148. package/dist/internal/machine/machine.d.ts.map +1 -1
  149. package/dist/internal/machine/machine.js +24 -40
  150. package/dist/internal/machine/machine.js.map +1 -1
  151. package/dist/internal/machine/observation.d.ts +3 -0
  152. package/dist/internal/machine/observation.d.ts.map +1 -1
  153. package/dist/internal/machine/observation.js +56 -2
  154. package/dist/internal/machine/observation.js.map +1 -1
  155. package/dist/internal/machine/plannedSnapshot.d.ts.map +1 -1
  156. package/dist/internal/machine/plannedSnapshot.js +11 -20
  157. package/dist/internal/machine/plannedSnapshot.js.map +1 -1
  158. package/dist/internal/machine/planner.d.ts +36 -23
  159. package/dist/internal/machine/planner.d.ts.map +1 -1
  160. package/dist/internal/machine/planner.js +15 -8
  161. package/dist/internal/machine/planner.js.map +1 -1
  162. package/dist/internal/machine/process.d.ts +17 -9
  163. package/dist/internal/machine/process.d.ts.map +1 -1
  164. package/dist/internal/machine/process.js +43 -503
  165. package/dist/internal/machine/process.js.map +1 -1
  166. package/dist/internal/machine/protocol.d.ts +1 -1
  167. package/dist/internal/machine/protocol.d.ts.map +1 -1
  168. package/dist/internal/machine/protocol.js +48 -10
  169. package/dist/internal/machine/protocol.js.map +1 -1
  170. package/dist/internal/machine/runtime.d.ts +20 -16
  171. package/dist/internal/machine/runtime.d.ts.map +1 -1
  172. package/dist/internal/machine/runtime.js +93 -88
  173. package/dist/internal/machine/runtime.js.map +1 -1
  174. package/dist/internal/machine/runtimeCompiled.d.ts.map +1 -1
  175. package/dist/internal/machine/runtimeCompiled.js +359 -120
  176. package/dist/internal/machine/runtimeCompiled.js.map +1 -1
  177. package/dist/internal/machine/runtimeProtocol.d.ts +151 -82
  178. package/dist/internal/machine/runtimeProtocol.d.ts.map +1 -1
  179. package/dist/internal/machine/runtimeProtocol.js +236 -219
  180. package/dist/internal/machine/runtimeProtocol.js.map +1 -1
  181. package/dist/internal/machine/stateDefinition.d.ts +0 -1
  182. package/dist/internal/machine/stateDefinition.d.ts.map +1 -1
  183. package/dist/internal/machine/stateDefinition.js +0 -1
  184. package/dist/internal/machine/stateDefinition.js.map +1 -1
  185. package/dist/internal/machine/step.d.ts +486 -0
  186. package/dist/internal/machine/step.d.ts.map +1 -0
  187. package/dist/internal/machine/step.js +957 -0
  188. package/dist/internal/machine/step.js.map +1 -0
  189. package/dist/internal/machine/stepHost.d.ts +33 -0
  190. package/dist/internal/machine/stepHost.d.ts.map +1 -0
  191. package/dist/internal/machine/stepHost.js +501 -0
  192. package/dist/internal/machine/stepHost.js.map +1 -0
  193. package/dist/internal/machine/symbols.d.ts +2 -11
  194. package/dist/internal/machine/symbols.d.ts.map +1 -1
  195. package/dist/internal/machine/symbols.js +2 -2
  196. package/dist/internal/machine/symbols.js.map +1 -1
  197. package/dist/internal/machine/transition.d.ts +7 -7
  198. package/dist/internal/machine/transition.d.ts.map +1 -1
  199. package/dist/internal/testing/machine/check.d.ts.map +1 -1
  200. package/dist/internal/testing/machine/check.js +217 -25
  201. package/dist/internal/testing/machine/check.js.map +1 -1
  202. package/dist/internal/testing/machine/exploration.d.ts +19 -2
  203. package/dist/internal/testing/machine/exploration.d.ts.map +1 -1
  204. package/dist/internal/testing/machine/exploration.js +14 -3
  205. package/dist/internal/testing/machine/exploration.js.map +1 -1
  206. package/dist/internal/testing/machine/format.js.map +1 -1
  207. package/dist/internal/testing/machine/probe.d.ts.map +1 -1
  208. package/dist/internal/testing/machine/probe.js +1 -1
  209. package/dist/internal/testing/machine/probe.js.map +1 -1
  210. package/dist/internal/testing/machine/runtime.d.ts +2 -2
  211. package/dist/internal/testing/machine/runtime.d.ts.map +1 -1
  212. package/dist/internal/testing/machine/runtime.js +10 -3
  213. package/dist/internal/testing/machine/runtime.js.map +1 -1
  214. package/dist/internal/testing/machine/trace.d.ts +38 -3
  215. package/dist/internal/testing/machine/trace.d.ts.map +1 -1
  216. package/dist/internal/testing/machine/trace.js +180 -33
  217. package/dist/internal/testing/machine/trace.js.map +1 -1
  218. package/dist/internal/testing/machine/transitionCoverage.d.ts +1 -1
  219. package/dist/internal/testing/machine/transitionCoverage.d.ts.map +1 -1
  220. package/dist/internal/testing/machine/verification.d.ts.map +1 -1
  221. package/dist/internal/testing/machine/verification.js +9 -1
  222. package/dist/internal/testing/machine/verification.js.map +1 -1
  223. package/dist/internal/testing/machine/work.d.ts +47 -0
  224. package/dist/internal/testing/machine/work.d.ts.map +1 -0
  225. package/dist/internal/testing/machine/work.js +74 -0
  226. package/dist/internal/testing/machine/work.js.map +1 -0
  227. package/dist/testing/MachineTest.d.ts +253 -37
  228. package/dist/testing/MachineTest.d.ts.map +1 -1
  229. package/dist/testing/MachineTest.js +81 -9
  230. package/dist/testing/MachineTest.js.map +1 -1
  231. package/dist/unstable/cluster/ClusterMachine.d.ts +1071 -41
  232. package/dist/unstable/cluster/ClusterMachine.d.ts.map +1 -1
  233. package/dist/unstable/cluster/ClusterMachine.js +441 -12
  234. package/dist/unstable/cluster/ClusterMachine.js.map +1 -1
  235. package/dist/unstable/cluster/ClusterMachineProxy.d.ts +257 -0
  236. package/dist/unstable/cluster/ClusterMachineProxy.d.ts.map +1 -0
  237. package/dist/unstable/cluster/ClusterMachineProxy.js +73 -0
  238. package/dist/unstable/cluster/ClusterMachineProxy.js.map +1 -0
  239. package/dist/unstable/cluster/SqlMachineStorage.d.ts +125 -0
  240. package/dist/unstable/cluster/SqlMachineStorage.d.ts.map +1 -0
  241. package/dist/unstable/cluster/SqlMachineStorage.js +62 -0
  242. package/dist/unstable/cluster/SqlMachineStorage.js.map +1 -0
  243. package/dist/unstable/cluster/index.d.ts +13 -0
  244. package/dist/unstable/cluster/index.d.ts.map +1 -1
  245. package/dist/unstable/cluster/index.js +13 -0
  246. package/dist/unstable/cluster/index.js.map +1 -1
  247. package/dist/unstable/reactivity/AtomMachine.d.ts +21 -26
  248. package/dist/unstable/reactivity/AtomMachine.d.ts.map +1 -1
  249. package/dist/unstable/reactivity/AtomMachine.js.map +1 -1
  250. package/package.json +5 -3
  251. package/src/LocalMachine.ts +611 -0
  252. package/src/Machine.ts +1379 -1334
  253. package/src/index.ts +1 -0
  254. package/src/internal/machine/atom.ts +20 -49
  255. package/src/internal/machine/capability.ts +123 -0
  256. package/src/internal/machine/{invocationDefinition.ts → capturedInvocation.ts} +13 -13
  257. package/src/internal/machine/child.ts +25 -0
  258. package/src/internal/machine/childRegistry.ts +1 -4
  259. package/src/internal/machine/cluster.ts +420 -205
  260. package/src/internal/machine/clusterChild.ts +117 -0
  261. package/src/internal/machine/clusterFailure.ts +53 -0
  262. package/src/internal/machine/clusterInstance.ts +1779 -0
  263. package/src/internal/machine/clusterKeepAlive.ts +93 -0
  264. package/src/internal/machine/clusterProgress.ts +159 -0
  265. package/src/internal/machine/clusterProtocol.ts +46 -4
  266. package/src/internal/machine/clusterProxy.ts +233 -0
  267. package/src/internal/machine/clusterRead.ts +207 -0
  268. package/src/internal/machine/clusterSqlStorage.ts +181 -0
  269. package/src/internal/machine/clusterStorageCheck.ts +274 -0
  270. package/src/internal/machine/clusterTarget.ts +154 -0
  271. package/src/internal/machine/clusterTimer.ts +58 -0
  272. package/src/internal/machine/clusterWake.ts +100 -0
  273. package/src/internal/machine/clusterWork.ts +269 -0
  274. package/src/internal/machine/command.ts +4 -4
  275. package/src/internal/machine/commandRuntime.ts +12 -24
  276. package/src/internal/machine/configuration.ts +0 -181
  277. package/src/internal/machine/errors.ts +11 -2
  278. package/src/internal/machine/executionPlan.ts +493 -263
  279. package/src/internal/machine/implementation.ts +6 -6
  280. package/src/internal/machine/inspectionRuntime.ts +1 -1
  281. package/src/internal/machine/invocationChanges.ts +89 -0
  282. package/src/internal/machine/{activities.ts → invocationDefinitions.ts} +10 -10
  283. package/src/internal/machine/invocationEvent.ts +35 -12
  284. package/src/internal/machine/invocationOutcome.ts +145 -0
  285. package/src/internal/machine/invocationResolution.ts +307 -0
  286. package/src/internal/machine/logicScope.ts +47 -0
  287. package/src/internal/machine/machine.ts +35 -100
  288. package/src/internal/machine/observation.ts +67 -2
  289. package/src/internal/machine/plannedSnapshot.ts +17 -20
  290. package/src/internal/machine/planner.ts +75 -99
  291. package/src/internal/machine/process.ts +78 -722
  292. package/src/internal/machine/protocol.ts +70 -26
  293. package/src/internal/machine/runtime.ts +198 -195
  294. package/src/internal/machine/runtimeCompiled.ts +496 -171
  295. package/src/internal/machine/runtimeProtocol.ts +416 -305
  296. package/src/internal/machine/stateDefinition.ts +0 -5
  297. package/src/internal/machine/step.ts +1518 -0
  298. package/src/internal/machine/stepHost.ts +634 -0
  299. package/src/internal/machine/symbols.ts +3 -14
  300. package/src/internal/machine/transition.ts +11 -11
  301. package/src/internal/testing/machine/check.ts +240 -36
  302. package/src/internal/testing/machine/exploration.ts +42 -3
  303. package/src/internal/testing/machine/format.ts +1 -1
  304. package/src/internal/testing/machine/probe.ts +2 -1
  305. package/src/internal/testing/machine/runtime.ts +15 -5
  306. package/src/internal/testing/machine/trace.ts +261 -41
  307. package/src/internal/testing/machine/transitionCoverage.ts +1 -1
  308. package/src/internal/testing/machine/verification.ts +11 -5
  309. package/src/internal/testing/machine/work.ts +101 -0
  310. package/src/testing/MachineTest.ts +268 -44
  311. package/src/unstable/cluster/ClusterMachine.ts +1183 -59
  312. package/src/unstable/cluster/ClusterMachineProxy.ts +372 -0
  313. package/src/unstable/cluster/SqlMachineStorage.ts +136 -0
  314. package/src/unstable/cluster/index.ts +15 -0
  315. package/src/unstable/reactivity/AtomMachine.ts +27 -88
  316. package/dist/internal/machine/activities.d.ts.map +0 -1
  317. package/dist/internal/machine/activities.js.map +0 -1
  318. package/dist/internal/machine/invocation.d.ts +0 -33
  319. package/dist/internal/machine/invocation.d.ts.map +0 -1
  320. package/dist/internal/machine/invocation.js +0 -220
  321. package/dist/internal/machine/invocation.js.map +0 -1
  322. package/dist/internal/machine/invocationDefinition.d.ts.map +0 -1
  323. package/dist/internal/machine/invocationDefinition.js.map +0 -1
  324. package/dist/internal/machine/requirements.d.ts +0 -4
  325. package/dist/internal/machine/requirements.d.ts.map +0 -1
  326. package/dist/internal/machine/requirements.js +0 -2
  327. package/dist/internal/machine/requirements.js.map +0 -1
  328. package/dist/internal/machine/runtimeGeneric.d.ts +0 -3
  329. package/dist/internal/machine/runtimeGeneric.d.ts.map +0 -1
  330. package/dist/internal/machine/runtimeGeneric.js +0 -465
  331. package/dist/internal/machine/runtimeGeneric.js.map +0 -1
  332. package/src/internal/machine/invocation.ts +0 -376
  333. package/src/internal/machine/requirements.ts +0 -11
  334. package/src/internal/machine/runtimeGeneric.ts +0 -797
@@ -38,6 +38,7 @@ import {
38
38
  type MicrostepTransition,
39
39
  normalizeTransition,
40
40
  planConfiguration,
41
+ planDecodedConfiguration,
41
42
  removeConflictingTransitions,
42
43
  resolveInitialConfiguration,
43
44
  resolveInitialTarget,
@@ -76,7 +77,7 @@ interface IndexedExecutionDescriptor {
76
77
  number,
77
78
  ReadonlyMap<PropertyKey, {
78
79
  readonly sourceIndex: number
79
- readonly transition: MicrostepTransition<any, any, any, any>
80
+ readonly transition: MicrostepTransition<any, any>
80
81
  }>
81
82
  >
82
83
  }
@@ -137,7 +138,7 @@ const compileIndexedExecutionDescriptor = (
137
138
  const finalPaths: Array<string> = []
138
139
  const transitionsByPath = new Map<
139
140
  PropertyKey,
140
- ReadonlyMap<PropertyKey, MicrostepTransition<any, any, any, any>>
141
+ ReadonlyMap<PropertyKey, MicrostepTransition<any, any>>
141
142
  >()
142
143
 
143
144
  for (const node of machine.stateNodes.byPath.values() as Iterable<Machine.StateNode>) {
@@ -159,7 +160,7 @@ const compileIndexedExecutionDescriptor = (
159
160
  if (config?.on === undefined) {
160
161
  continue
161
162
  }
162
- const byEvent = new Map<PropertyKey, MicrostepTransition<any, any, any, any>>()
163
+ const byEvent = new Map<PropertyKey, MicrostepTransition<any, any>>()
163
164
  for (const tag of Reflect.ownKeys(config.on)) {
164
165
  const transition = normalizeTransition(config.on[tag] as Parameters<typeof normalizeTransition>[0])
165
166
  if (transition !== undefined) {
@@ -192,13 +193,13 @@ const compileIndexedExecutionDescriptor = (
192
193
  number,
193
194
  ReadonlyMap<PropertyKey, {
194
195
  readonly sourceIndex: number
195
- readonly transition: MicrostepTransition<any, any, any, any>
196
+ readonly transition: MicrostepTransition<any, any>
196
197
  }>
197
198
  >()
198
199
  for (const leafIndex of leafIndices) {
199
200
  const dispatch = new Map<PropertyKey, {
200
201
  readonly sourceIndex: number
201
- readonly transition: MicrostepTransition<any, any, any, any>
202
+ readonly transition: MicrostepTransition<any, any>
202
203
  }>()
203
204
  const candidates = [leafIndex, ...ancestorIndices[leafIndex]!.slice().reverse()]
204
205
  for (const sourceIndex of candidates) {
@@ -237,15 +238,17 @@ const compileIndexedExecutionDescriptor = (
237
238
  }
238
239
 
239
240
  /**
240
- * The compact execution state owned by a single compiled process drain.
241
+ * The compact execution state of the indexed kernels.
241
242
  *
242
- * This representation never crosses the public snapshot boundary. The flat
243
- * kernel may update `values` in place only after constructing the handler
244
- * context, whose snapshot is detached from this storage. Hierarchical plans
245
- * copy the table whenever simultaneous transitions need their common source
246
- * state to remain stable.
243
+ * This representation never crosses the public snapshot boundary. Only
244
+ * `values` is ever written in place, and only by the flat kernel, after it has
245
+ * built the handler context, whose snapshot is detached from this storage. Who
246
+ * may let it write a state is the {@link ExecutionOwnership} of the plan. The
247
+ * hierarchical kernel never writes a state in place: it copies the table
248
+ * whenever it changes it, so simultaneous transitions read one stable source
249
+ * state, and its microsteps can share states with what it returns.
247
250
  */
248
- interface OwnedIndexedState {
251
+ interface IndexedExecutionState {
249
252
  readonly active: Uint8Array
250
253
  readonly activeLeaves: ReadonlyArray<number>
251
254
  readonly values: Array<unknown>
@@ -254,7 +257,28 @@ interface OwnedIndexedState {
254
257
  readonly completedOrder: ReadonlyArray<number>
255
258
  }
256
259
 
257
- const copyOwnedIndexedState = (state: OwnedIndexedState): OwnedIndexedState => ({
260
+ /**
261
+ * Who may write the execution state that a plan receives.
262
+ *
263
+ * - `"Persistent"`: the state is a persistent value. The caller may keep it and
264
+ * plan from it again, and may keep what the plan returns. The plan writes no
265
+ * state that it did not create in that same call, and returns no state that a
266
+ * later `"Persistent"` plan writes.
267
+ * - `"Owned"`: the caller hands the state over to the plan, and reads it again
268
+ * only through what the plan returns. The plan may update it in place. What a
269
+ * plan returns, its next state and its microsteps, stays valid until that
270
+ * next state is planned again. A plan that throws leaves the state it received
271
+ * as it was.
272
+ *
273
+ * Every plan of one chain of states takes the same ownership, since an
274
+ * `"Owned"` plan may write a state that a `"Persistent"` plan returned to a
275
+ * caller that keeps it.
276
+ *
277
+ * @internal
278
+ */
279
+ export type ExecutionOwnership = "Owned" | "Persistent"
280
+
281
+ const copyIndexedState = (state: IndexedExecutionState): IndexedExecutionState => ({
258
282
  active: state.active.slice(),
259
283
  activeLeaves: state.activeLeaves.slice(),
260
284
  values: state.values.slice(),
@@ -263,23 +287,16 @@ const copyOwnedIndexedState = (state: OwnedIndexedState): OwnedIndexedState => (
263
287
  completedOrder: state.completedOrder.slice()
264
288
  })
265
289
 
266
- const retainIndexedMicrostep = (
267
- step: ExecutionMicrostep<OwnedIndexedState>,
268
- retain: boolean
269
- ): ExecutionMicrostep<OwnedIndexedState> => retain ? { ...step, next: copyOwnedIndexedState(step.next) } : step
270
-
271
- const updateOwnedIndexedValue = (
272
- state: OwnedIndexedState,
273
- index: number,
274
- value: unknown
275
- ): void => {
276
- state.values[index] = value
277
- }
290
+ /** A state equal to `state` whose values the kernel may write, as only `values` is ever written. */
291
+ const withWritableIndexedValues = (state: IndexedExecutionState): IndexedExecutionState => ({
292
+ ...state,
293
+ values: state.values.slice()
294
+ })
278
295
 
279
- const ownedIndexedStateFromActive = (
296
+ const indexedStateFromActive = (
280
297
  descriptor: IndexedExecutionDescriptor,
281
298
  configuration: ActiveConfiguration
282
- ): OwnedIndexedState => {
299
+ ): IndexedExecutionState => {
283
300
  const active = new Uint8Array(descriptor.nodes.length)
284
301
  const values: Array<unknown> = new Array(descriptor.nodes.length)
285
302
  const completed = new Uint8Array(descriptor.nodes.length)
@@ -310,7 +327,7 @@ const ownedIndexedStateFromActive = (
310
327
 
311
328
  const activeConfigurationFromIndexedState = (
312
329
  descriptor: IndexedExecutionDescriptor,
313
- configuration: OwnedIndexedState
330
+ configuration: IndexedExecutionState
314
331
  ): ActiveConfiguration => {
315
332
  const active = new Set<string>()
316
333
  const values = new Map<string, unknown>()
@@ -340,7 +357,7 @@ interface IndexedSnapshotNode {
340
357
 
341
358
  const snapshotFromIndexedStateStatePath = (
342
359
  descriptor: IndexedExecutionDescriptor,
343
- configuration: OwnedIndexedState,
360
+ configuration: IndexedExecutionState,
344
361
  index: number
345
362
  ): IndexedSnapshotNode => {
346
363
  const node = descriptor.nodes[index]!
@@ -377,7 +394,7 @@ const snapshotFromIndexedStateStatePath = (
377
394
 
378
395
  const snapshotFromIndexedState = (
379
396
  descriptor: IndexedExecutionDescriptor,
380
- configuration: OwnedIndexedState
397
+ configuration: IndexedExecutionState
381
398
  ): Machine.Snapshot<any> => {
382
399
  const rootIndex = descriptor.rootIndices.find((index) => configuration.active[index] === 1)
383
400
  if (rootIndex === undefined) throw new Error("Machine expected an active indexed root state")
@@ -410,7 +427,7 @@ interface IndexedTransitionContext {
410
427
  const makeIndexedTransitionContext = (
411
428
  machine: Machine.Any,
412
429
  descriptor: IndexedExecutionDescriptor,
413
- configuration: OwnedIndexedState,
430
+ configuration: IndexedExecutionState,
414
431
  sourceIndex: number,
415
432
  event: IndexedEvent,
416
433
  machineReferences?: PlanningMachineReferences
@@ -432,23 +449,26 @@ const makeIndexedTransitionContext = (
432
449
  }
433
450
  }
434
451
 
435
- type IndexedSelectedTransition = SelectedTransition<any, any, any, IndexedTransitionContext> & {
452
+ type IndexedSelectedTransition = SelectedTransition<any, IndexedTransitionContext> & {
436
453
  readonly sourceIndex: number
437
454
  readonly leafIndex: number
438
455
  }
439
456
 
440
457
  type IndexedEvaluatedTransition =
441
458
  & Omit<
442
- EvaluatedTransition<any, IndexedEvent, any, any, IndexedTransitionContext>,
459
+ EvaluatedTransition<any, IndexedEvent, IndexedTransitionContext>,
443
460
  "selection"
444
461
  >
445
462
  & {
446
463
  readonly selection: IndexedSelectedTransition
447
- readonly next: OwnedIndexedState
464
+ readonly next: IndexedExecutionState
448
465
  }
449
466
 
450
467
  const emptyExecutionValues: ReadonlyArray<never> = Object.freeze([])
451
468
 
469
+ /** Marks that a flat microstep writes no value. A decoded value may be `undefined`. */
470
+ const noIndexedValue: unique symbol = Symbol("effect/Machine/ExecutionPlan/NoValue")
471
+
452
472
  export interface ExecutionMicrostep<State = unknown> {
453
473
  readonly next: State
454
474
  readonly event: unknown
@@ -473,9 +493,9 @@ export interface ExecutionMacrostep<State = unknown> {
473
493
 
474
494
  const collectIndexedTransition = <Context>(
475
495
  machine: Machine.Any,
476
- transition: TransitionHandler<any, any, any, Context>,
496
+ transition: TransitionHandler<any, Context>,
477
497
  context: Context,
478
- evaluate?: NonNullable<MicrostepTransition<any, any, any, Context>["evaluate"]>
498
+ evaluate?: NonNullable<MicrostepTransition<any, Context>["evaluate"]>
479
499
  ) => {
480
500
  let commands: Array<RuntimeCommand> | undefined
481
501
  let raisedEvents: Array<IndexedEvent> | undefined
@@ -510,7 +530,7 @@ const collectIndexedTransition = <Context>(
510
530
  const selectIndexedEventTransitions = (
511
531
  machine: Machine.Any,
512
532
  descriptor: IndexedExecutionDescriptor,
513
- configuration: OwnedIndexedState,
533
+ configuration: IndexedExecutionState,
514
534
  event: IndexedEvent,
515
535
  machineReferences?: PlanningMachineReferences
516
536
  ): ReadonlyArray<IndexedSelectedTransition> => {
@@ -543,7 +563,7 @@ const selectIndexedEventTransitions = (
543
563
  return selected
544
564
  }
545
565
 
546
- const hasSameIndexedActive = (left: OwnedIndexedState, right: OwnedIndexedState): boolean => {
566
+ const hasSameIndexedActive = (left: IndexedExecutionState, right: IndexedExecutionState): boolean => {
547
567
  if (left.active === right.active) return true
548
568
  for (let index = 0; index < left.active.length; index++) {
549
569
  if (left.active[index] !== right.active[index]) return false
@@ -554,10 +574,10 @@ const hasSameIndexedActive = (left: OwnedIndexedState, right: OwnedIndexedState)
554
574
  const normalizeIndexedTargetStateSync = (
555
575
  machine: Machine.Any,
556
576
  descriptor: IndexedExecutionDescriptor,
557
- current: OwnedIndexedState,
577
+ current: IndexedExecutionState,
558
578
  target: Machine.Target<any, any> | Machine.Snapshot<any>,
559
579
  activeLeafIndex: number
560
- ): OwnedIndexedState => {
580
+ ): IndexedExecutionState => {
561
581
  const targetIndex = isTarget(target) ? descriptor.indexByPath.get(String(target.path)) : undefined
562
582
  if (
563
583
  targetIndex === activeLeafIndex && current.active[activeLeafIndex] === 1 && isTarget(target) &&
@@ -573,7 +593,7 @@ const normalizeIndexedTargetStateSync = (
573
593
  )
574
594
  return { ...current, values }
575
595
  }
576
- return ownedIndexedStateFromActive(
596
+ return indexedStateFromActive(
577
597
  descriptor,
578
598
  normalizeTargetConfigurationSync(
579
599
  machine,
@@ -586,7 +606,7 @@ const normalizeIndexedTargetStateSync = (
586
606
  const collectIndexedEvaluatedTransition = (
587
607
  machine: Machine.Any,
588
608
  descriptor: IndexedExecutionDescriptor,
589
- state: OwnedIndexedState,
609
+ state: IndexedExecutionState,
590
610
  selection: IndexedSelectedTransition
591
611
  ): IndexedEvaluatedTransition => {
592
612
  const transitionResult = collectIndexedTransition(
@@ -648,7 +668,7 @@ const collectIndexedEvaluatedTransition = (
648
668
  const initialRaisedEvents = (initialResolution?.raisedEvents ?? emptyExecutionValues) as ReadonlyArray<IndexedEvent>
649
669
  let next = target === undefined
650
670
  ? update === undefined ? state : (() => {
651
- const next = copyOwnedIndexedState(state)
671
+ const next = copyIndexedState(state)
652
672
  next.values[descriptor.indexByPath.get(update.path)!] = update.value
653
673
  return next
654
674
  })()
@@ -712,41 +732,140 @@ const collectIndexedEvaluatedTransition = (
712
732
  }
713
733
 
714
734
  /** Indexed microsteps keep decoded raised events typed for the next dispatch. */
715
- type IndexedMicrostep = ExecutionMicrostep<OwnedIndexedState> & {
735
+ type IndexedMicrostep = ExecutionMicrostep<IndexedExecutionState> & {
716
736
  readonly raisedEvents: ReadonlyArray<IndexedEvent>
717
737
  }
718
738
 
739
+ const retainIndexedTransition = (transition: IndexedEvaluatedTransition): Machine.RetainedTransition => ({
740
+ source: transition.selection.sourcePath,
741
+ trigger: transition.selection.trigger,
742
+ reenter: transition.selection.transition.reenter,
743
+ branchIndex: transition.branchIndex,
744
+ branchKey: transition.branchKey,
745
+ target: transition.unresolvedTarget === undefined ? undefined : getTargetNodePath(transition.unresolvedTarget),
746
+ resolvedTarget: transition.target === undefined ? undefined : getTargetNodePath(transition.target),
747
+ updates: transition.update === undefined ? [] : [transition.update.path]
748
+ })
749
+
750
+ /**
751
+ * A retained microstep of the hierarchical kernel. It builds its retained
752
+ * transitions on first read, from evaluated transitions that hold only values
753
+ * no later plan writes.
754
+ */
755
+ class RetainedHierarchicalMicrostep implements IndexedMicrostep {
756
+ #evaluated: ReadonlyArray<IndexedEvaluatedTransition> | undefined
757
+ #transitions: ReadonlyArray<Machine.RetainedTransition> | undefined
758
+
759
+ constructor(
760
+ readonly next: IndexedExecutionState,
761
+ readonly event: IndexedEvent,
762
+ evaluated: ReadonlyArray<IndexedEvaluatedTransition>,
763
+ readonly commands: ReadonlyArray<RuntimeCommand>,
764
+ readonly raisedEvents: ReadonlyArray<IndexedEvent>,
765
+ readonly emittedEvents: ReadonlyArray<unknown>,
766
+ readonly exitPaths: ReadonlyArray<string>,
767
+ readonly entryPaths: ReadonlyArray<string>,
768
+ readonly changed: boolean
769
+ ) {
770
+ this.#evaluated = evaluated
771
+ }
772
+
773
+ get transitions(): ReadonlyArray<Machine.RetainedTransition> {
774
+ if (this.#transitions === undefined) {
775
+ this.#transitions = this.#evaluated!.map(retainIndexedTransition)
776
+ this.#evaluated = undefined
777
+ }
778
+ return this.#transitions
779
+ }
780
+ }
781
+
782
+ /**
783
+ * A retained microstep of the flat kernel, which builds its one retained
784
+ * transition on first read.
785
+ */
786
+ class RetainedFlatMicrostep implements IndexedMicrostep {
787
+ readonly #source: string
788
+ readonly #reenter: boolean
789
+ readonly #branchIndex: number
790
+ readonly #branchKey: string | undefined
791
+ readonly #target: Machine.Target<any, any> | Machine.Snapshot<any> | undefined
792
+ readonly #update: { readonly path: string } | undefined
793
+ #transitions: ReadonlyArray<Machine.RetainedTransition> | undefined
794
+
795
+ constructor(
796
+ readonly next: IndexedExecutionState,
797
+ readonly event: IndexedEvent,
798
+ readonly commands: ReadonlyArray<RuntimeCommand>,
799
+ readonly raisedEvents: ReadonlyArray<IndexedEvent>,
800
+ readonly emittedEvents: ReadonlyArray<unknown>,
801
+ readonly exitPaths: ReadonlyArray<string>,
802
+ readonly entryPaths: ReadonlyArray<string>,
803
+ readonly changed: boolean,
804
+ source: string,
805
+ reenter: boolean,
806
+ branchIndex: number,
807
+ branchKey: string | undefined,
808
+ target: Machine.Target<any, any> | Machine.Snapshot<any> | undefined,
809
+ update: { readonly path: string } | undefined
810
+ ) {
811
+ this.#source = source
812
+ this.#reenter = reenter
813
+ this.#branchIndex = branchIndex
814
+ this.#branchKey = branchKey
815
+ this.#target = target
816
+ this.#update = update
817
+ }
818
+
819
+ get transitions(): ReadonlyArray<Machine.RetainedTransition> {
820
+ if (this.#transitions === undefined) {
821
+ const target = this.#target === undefined ? undefined : getTargetNodePath(this.#target)
822
+ this.#transitions = [{
823
+ source: this.#source,
824
+ trigger: { type: "event", event: this.event._tag },
825
+ reenter: this.#reenter,
826
+ branchIndex: this.#branchIndex,
827
+ branchKey: this.#branchKey,
828
+ target,
829
+ resolvedTarget: target,
830
+ updates: this.#update === undefined ? [] : [this.#update.path]
831
+ }]
832
+ }
833
+ return this.#transitions
834
+ }
835
+ }
836
+
719
837
  const indexedMicrostep = (
720
838
  machine: Machine.Any,
721
839
  descriptor: IndexedExecutionDescriptor,
722
- state: OwnedIndexedState,
840
+ state: IndexedExecutionState,
723
841
  event: IndexedEvent,
724
842
  selections: ReadonlyArray<IndexedSelectedTransition>,
725
843
  retainTransitions: boolean
726
844
  ): IndexedMicrostep => {
727
- const retain = (transition: IndexedEvaluatedTransition): Machine.RetainedTransition => ({
728
- source: transition.selection.sourcePath,
729
- trigger: transition.selection.trigger,
730
- reenter: transition.selection.transition.reenter,
731
- branchIndex: transition.branchIndex,
732
- branchKey: transition.branchKey,
733
- target: transition.unresolvedTarget === undefined ? undefined : getTargetNodePath(transition.unresolvedTarget),
734
- resolvedTarget: transition.target === undefined ? undefined : getTargetNodePath(transition.target),
735
- updates: transition.update === undefined ? [] : [transition.update.path]
736
- })
737
845
  if (selections.length === 1) {
738
846
  const transition = collectIndexedEvaluatedTransition(machine, descriptor, state, selections[0]!)
739
- return {
740
- next: transition.next,
741
- event,
742
- ...(retainTransitions ? { transitions: [retain(transition)] } : undefined),
743
- commands: transition.commands,
744
- raisedEvents: transition.raisedEvents,
745
- emittedEvents: transition.emittedEvents,
746
- exitPaths: transition.exitPaths,
747
- entryPaths: transition.entryPaths,
748
- changed: transition.changed
749
- }
847
+ return retainTransitions
848
+ ? new RetainedHierarchicalMicrostep(
849
+ transition.next,
850
+ event,
851
+ [transition],
852
+ transition.commands,
853
+ transition.raisedEvents,
854
+ transition.emittedEvents,
855
+ transition.exitPaths,
856
+ transition.entryPaths,
857
+ transition.changed
858
+ )
859
+ : {
860
+ next: transition.next,
861
+ event,
862
+ commands: transition.commands,
863
+ raisedEvents: transition.raisedEvents,
864
+ emittedEvents: transition.emittedEvents,
865
+ exitPaths: transition.exitPaths,
866
+ entryPaths: transition.entryPaths,
867
+ changed: transition.changed
868
+ }
750
869
  }
751
870
  const activeSelections = selections.filter((selection) =>
752
871
  !selections.some((other) =>
@@ -791,199 +910,235 @@ const indexedMicrostep = (
791
910
  const raisedEvents = transitions.flatMap((transition) => transition.raisedEvents)
792
911
  const emittedEvents = transitions.flatMap((transition) => transition.emittedEvents)
793
912
  const changed = transitions.some((transition) => transition.changed)
794
- return {
795
- next,
796
- event,
797
- ...(retainTransitions ? { transitions: transitions.map(retain) } : undefined),
798
- commands,
799
- raisedEvents,
800
- emittedEvents,
801
- exitPaths: changed ? sortExitPaths(machine, transitions.flatMap((transition) => transition.exitPaths)) : [],
802
- entryPaths: changed ? sortEntryPaths(machine, transitions.flatMap((transition) => transition.entryPaths)) : [],
803
- changed
804
- }
913
+ const exitPaths = changed ? sortExitPaths(machine, transitions.flatMap((transition) => transition.exitPaths)) : []
914
+ const entryPaths = changed ? sortEntryPaths(machine, transitions.flatMap((transition) => transition.entryPaths)) : []
915
+ return retainTransitions
916
+ ? new RetainedHierarchicalMicrostep(
917
+ next,
918
+ event,
919
+ transitions,
920
+ commands,
921
+ raisedEvents,
922
+ emittedEvents,
923
+ exitPaths,
924
+ entryPaths,
925
+ changed
926
+ )
927
+ : { next, event, commands, raisedEvents, emittedEvents, exitPaths, entryPaths, changed }
805
928
  }
806
929
 
807
930
  const planIndexedFlatState = (
808
931
  machine: Machine.Any,
809
932
  descriptor: IndexedExecutionDescriptor,
810
- configuration: OwnedIndexedState,
933
+ configuration: IndexedExecutionState,
811
934
  decoded: IndexedEvent,
812
935
  retainMicrosteps: boolean,
936
+ ownership: ExecutionOwnership,
813
937
  machineReferences?: PlanningMachineReferences
814
- ): ExecutionMacrostep<OwnedIndexedState> => {
938
+ ): ExecutionMacrostep<IndexedExecutionState> => {
815
939
  let current = configuration
816
940
  let event: IndexedEvent = decoded
817
941
  let commands: Array<RuntimeCommand> | undefined
818
942
  let raisedEvents: Array<IndexedEvent> | undefined
819
943
  let emittedEvents: Array<unknown> | undefined
820
- let microsteps: Array<ExecutionMicrostep<OwnedIndexedState>> | undefined
944
+ let microsteps: Array<ExecutionMicrostep<IndexedExecutionState>> | undefined
821
945
  let raisedIndex = 0
822
946
  let iterations = 0
947
+ // Whether `current` may be written in place, because nothing but this plan
948
+ // references it. A persistent caller's state, and the state of a retained
949
+ // microstep, are copied before they would be written.
950
+ let writable = ownership === "Owned"
951
+ // The value that this plan overwrote in an owned caller's state, so that a
952
+ // plan that throws leaves that state as it was. Only the active leaf is
953
+ // written, and the leaf of the caller's state stays active while `current`
954
+ // is that state, so one value is all a plan overwrites in it.
955
+ let restoreIndex = -1
956
+ let restoreValue: unknown
823
957
 
824
- while (true) {
825
- iterations += 1
826
- if (iterations > MaxMacrostepIterations) {
827
- throw new InfiniteTransitionError({
828
- machineId: machine.id,
829
- state: descriptor.nodes[current.activeLeaves[0]!]!.path,
830
- maxIterations: MaxMacrostepIterations
831
- })
832
- }
958
+ try {
959
+ while (true) {
960
+ iterations += 1
961
+ if (iterations > MaxMacrostepIterations) {
962
+ throw new InfiniteTransitionError({
963
+ machineId: machine.id,
964
+ state: descriptor.nodes[current.activeLeaves[0]!]!.path,
965
+ maxIterations: MaxMacrostepIterations
966
+ })
967
+ }
833
968
 
834
- const sourceIndex = current.activeLeaves[0]
835
- if (sourceIndex === undefined) {
836
- throw new Error("Machine expected an active indexed root state")
837
- }
838
- if (descriptor.nodes[sourceIndex]!.type === "final") {
839
- const completed = completeConfigurationSync(
840
- machine,
841
- activeConfigurationFromIndexedState(descriptor, current),
842
- event
843
- ).configuration
844
- const root = getRootPath(machine, completed)
845
- if (!completed.outputs.has(root)) {
846
- throw new Error("Machine reached a terminal indexed configuration without a completed root output")
969
+ const sourceIndex = current.activeLeaves[0]
970
+ if (sourceIndex === undefined) {
971
+ throw new Error("Machine expected an active indexed root state")
847
972
  }
848
- return {
849
- event: decoded,
850
- next: ownedIndexedStateFromActive(descriptor, completed),
851
- commands: commands ?? emptyExecutionValues,
852
- emittedEvents: emittedEvents ?? emptyExecutionValues,
853
- microsteps: microsteps ?? emptyExecutionValues,
854
- done: true,
855
- output: completed.outputs.get(root)
973
+ if (descriptor.nodes[sourceIndex]!.type === "final") {
974
+ const completed = completeConfigurationSync(
975
+ machine,
976
+ activeConfigurationFromIndexedState(descriptor, current),
977
+ event
978
+ ).configuration
979
+ const root = getRootPath(machine, completed)
980
+ if (!completed.outputs.has(root)) {
981
+ throw new Error("Machine reached a terminal indexed configuration without a completed root output")
982
+ }
983
+ return {
984
+ event: decoded,
985
+ next: indexedStateFromActive(descriptor, completed),
986
+ commands: commands ?? emptyExecutionValues,
987
+ emittedEvents: emittedEvents ?? emptyExecutionValues,
988
+ microsteps: microsteps ?? emptyExecutionValues,
989
+ done: true,
990
+ output: completed.outputs.get(root)
991
+ }
856
992
  }
857
- }
858
993
 
859
- const sourcePath = descriptor.nodes[sourceIndex]!.path
860
- const transition = normalizeTransition(toImpl(machine).handlers[sourcePath]?.on?.[event._tag])
861
- if (transition !== undefined) {
862
- const transitionResult = collectIndexedTransition(
863
- machine,
864
- transition.transition,
865
- {
866
- ...resolveMachineReferences(machine, machineReferences),
867
- state: current.values[sourceIndex],
868
- containingState: undefined,
869
- ancestors: {},
870
- event,
871
- snapshot: snapshotFromIndexedState(descriptor, current)
872
- },
873
- transition.evaluate
874
- )
875
- const update = isStateUpdate(transitionResult.state) ? transitionResult.state : undefined
876
- const target = update === undefined ? transitionResult.state : undefined
877
- if (update !== undefined) {
878
- const node = descriptor.nodes[sourceIndex]!
879
- if (update.path !== sourcePath || node.schema === undefined) {
880
- throw new Error(`Machine state update owner "${update.path}" must be the active valued state`)
994
+ const sourcePath = descriptor.nodes[sourceIndex]!.path
995
+ const transition = normalizeTransition(toImpl(machine).handlers[sourcePath]?.on?.[event._tag])
996
+ if (transition !== undefined) {
997
+ const transitionResult = collectIndexedTransition(
998
+ machine,
999
+ transition.transition,
1000
+ {
1001
+ ...resolveMachineReferences(machine, machineReferences),
1002
+ state: current.values[sourceIndex],
1003
+ containingState: undefined,
1004
+ ancestors: {},
1005
+ event,
1006
+ snapshot: snapshotFromIndexedState(descriptor, current)
1007
+ },
1008
+ transition.evaluate
1009
+ )
1010
+ const update = isStateUpdate(transitionResult.state) ? transitionResult.state : undefined
1011
+ const target = update === undefined ? transitionResult.state : undefined
1012
+ // The new value of the source state, when this microstep keeps it active.
1013
+ let value: unknown = noIndexedValue
1014
+ if (update !== undefined) {
1015
+ const node = descriptor.nodes[sourceIndex]!
1016
+ if (update.path !== sourcePath || node.schema === undefined) {
1017
+ throw new Error(`Machine state update owner "${update.path}" must be the active valued state`)
1018
+ }
1019
+ value = decodeStateValueSync(machine, node, update.value)
1020
+ }
1021
+ validateDeclaredTransitionTarget(
1022
+ sourcePath,
1023
+ { type: "event", event: event._tag },
1024
+ transition.targets,
1025
+ target
1026
+ )
1027
+ if (target !== undefined && !isTarget(target) && !isSnapshot(target)) {
1028
+ throw new Error("Machine expected indexed transition target to be a snapshot or target builder result")
881
1029
  }
882
- updateOwnedIndexedValue(current, sourceIndex, decodeStateValueSync(machine, node, update.value))
883
- }
884
- validateDeclaredTransitionTarget(
885
- sourcePath,
886
- { type: "event", event: event._tag },
887
- transition.targets,
888
- target
889
- )
890
- if (target !== undefined && !isTarget(target) && !isSnapshot(target)) {
891
- throw new Error("Machine expected indexed transition target to be a snapshot or target builder result")
892
- }
893
1030
 
894
- let next = current
895
- if (target !== undefined) {
896
- const targetIndex = descriptor.indexByPath.get(String(target.path))
897
- const isSimpleTarget = isTarget(target)
898
- ? (target as TargetSnapshotSlot)[TargetSnapshotTypeId] === undefined && target.values === undefined
899
- : !("state" in target) && !("states" in target) && !("completed" in target) && !("history" in target)
900
- if (
901
- targetIndex === sourceIndex && isSimpleTarget && current.completedOrder.length === 0 &&
902
- descriptor.valued[sourceIndex]
903
- ) {
904
- updateOwnedIndexedValue(
905
- current,
906
- sourceIndex,
907
- decodeStateValueSync(
908
- machine,
909
- descriptor.nodes[sourceIndex]!,
910
- target.value
911
- )
912
- )
913
- } else {
914
- next = normalizeIndexedTargetStateSync(machine, descriptor, current, target, sourceIndex)
1031
+ let next = current
1032
+ if (target !== undefined) {
1033
+ const targetIndex = descriptor.indexByPath.get(String(target.path))
1034
+ const isSimpleTarget = isTarget(target)
1035
+ ? (target as TargetSnapshotSlot)[TargetSnapshotTypeId] === undefined && target.values === undefined
1036
+ : !("state" in target) && !("states" in target) && !("completed" in target) && !("history" in target)
1037
+ if (
1038
+ targetIndex === sourceIndex && isSimpleTarget && current.completedOrder.length === 0 &&
1039
+ descriptor.valued[sourceIndex]
1040
+ ) {
1041
+ value = decodeStateValueSync(machine, descriptor.nodes[sourceIndex]!, target.value)
1042
+ } else {
1043
+ next = normalizeIndexedTargetStateSync(machine, descriptor, current, target, sourceIndex)
1044
+ }
915
1045
  }
916
- }
917
- const changed = transition.reenter || !hasSameIndexedActive(current, next)
918
- const nextIndex = next.activeLeaves[0]
919
- if (nextIndex === undefined) {
920
- throw new Error("Machine expected an active indexed transition target")
921
- }
922
- const step: ExecutionMicrostep<OwnedIndexedState> = {
923
- next,
924
- event,
925
- ...(retainMicrosteps
926
- ? {
927
- transitions: [{
928
- source: sourcePath,
929
- trigger: { type: "event", event: event._tag },
930
- reenter: transition.reenter,
931
- branchIndex: transitionResult.branchIndex,
932
- branchKey: transitionResult.branchKey,
933
- target: target === undefined ? undefined : getTargetNodePath(target),
934
- resolvedTarget: target === undefined ? undefined : getTargetNodePath(target),
935
- updates: update === undefined ? [] : [update.path]
936
- }]
1046
+ if (value !== noIndexedValue) {
1047
+ if (!writable) {
1048
+ current = withWritableIndexedValues(current)
1049
+ writable = true
1050
+ } else if (current === configuration && restoreIndex === -1) {
1051
+ restoreIndex = sourceIndex
1052
+ restoreValue = configuration.values[sourceIndex]
937
1053
  }
938
- : undefined),
939
- commands: transitionResult.commands,
940
- raisedEvents: transitionResult.raisedEvents,
941
- emittedEvents: transitionResult.emittedEvents,
942
- exitPaths: changed ? [sourcePath] : emptyExecutionValues,
943
- entryPaths: changed ? [descriptor.nodes[nextIndex]!.path] : emptyExecutionValues,
944
- changed
945
- }
946
- current = next
947
- ;(microsteps ??= []).push(retainIndexedMicrostep(step, retainMicrosteps))
948
- if (transitionResult.commands.length > 0) {
949
- ;(commands ??= []).push(...transitionResult.commands)
950
- }
951
- if (transitionResult.raisedEvents.length > 0) {
952
- ;(raisedEvents ??= []).push(...transitionResult.raisedEvents)
953
- }
954
- if (transitionResult.emittedEvents.length > 0) {
955
- ;(emittedEvents ??= []).push(...transitionResult.emittedEvents)
1054
+ current.values[sourceIndex] = value
1055
+ next = current
1056
+ }
1057
+ const changed = transition.reenter || !hasSameIndexedActive(current, next)
1058
+ const nextIndex = next.activeLeaves[0]
1059
+ if (nextIndex === undefined) {
1060
+ throw new Error("Machine expected an active indexed transition target")
1061
+ }
1062
+ const exitPaths = changed ? [sourcePath] : emptyExecutionValues
1063
+ const entryPaths = changed ? [descriptor.nodes[nextIndex]!.path] : emptyExecutionValues
1064
+ const step: ExecutionMicrostep<IndexedExecutionState> = retainMicrosteps
1065
+ ? new RetainedFlatMicrostep(
1066
+ next,
1067
+ event,
1068
+ transitionResult.commands,
1069
+ transitionResult.raisedEvents,
1070
+ transitionResult.emittedEvents,
1071
+ exitPaths,
1072
+ entryPaths,
1073
+ changed,
1074
+ sourcePath,
1075
+ transition.reenter,
1076
+ transitionResult.branchIndex,
1077
+ transitionResult.branchKey,
1078
+ target,
1079
+ update
1080
+ )
1081
+ : {
1082
+ next,
1083
+ event,
1084
+ commands: transitionResult.commands,
1085
+ raisedEvents: transitionResult.raisedEvents,
1086
+ emittedEvents: transitionResult.emittedEvents,
1087
+ exitPaths,
1088
+ entryPaths,
1089
+ changed
1090
+ }
1091
+ // A state that this microstep created is referenced by nothing else,
1092
+ // unless the microstep is retained.
1093
+ if (next !== current) writable = true
1094
+ current = next
1095
+ if (retainMicrosteps) writable = false
1096
+ ;(microsteps ??= []).push(step)
1097
+ if (transitionResult.commands.length > 0) {
1098
+ ;(commands ??= []).push(...transitionResult.commands)
1099
+ }
1100
+ if (transitionResult.raisedEvents.length > 0) {
1101
+ ;(raisedEvents ??= []).push(...transitionResult.raisedEvents)
1102
+ }
1103
+ if (transitionResult.emittedEvents.length > 0) {
1104
+ ;(emittedEvents ??= []).push(...transitionResult.emittedEvents)
1105
+ }
956
1106
  }
957
- }
958
1107
 
959
- if (descriptor.nodes[current.activeLeaves[0]!]!.type === "final") {
960
- continue
961
- }
962
- const raised = raisedEvents?.[raisedIndex]
963
- if (raised === undefined) {
964
- return {
965
- event: decoded,
966
- next: current,
967
- commands: commands ?? emptyExecutionValues,
968
- emittedEvents: emittedEvents ?? emptyExecutionValues,
969
- microsteps: microsteps ?? emptyExecutionValues,
970
- done: false,
971
- output: undefined
1108
+ if (descriptor.nodes[current.activeLeaves[0]!]!.type === "final") {
1109
+ continue
1110
+ }
1111
+ const raised = raisedEvents?.[raisedIndex]
1112
+ if (raised === undefined) {
1113
+ return {
1114
+ event: decoded,
1115
+ next: current,
1116
+ commands: commands ?? emptyExecutionValues,
1117
+ emittedEvents: emittedEvents ?? emptyExecutionValues,
1118
+ microsteps: microsteps ?? emptyExecutionValues,
1119
+ done: false,
1120
+ output: undefined
1121
+ }
972
1122
  }
1123
+ raisedIndex += 1
1124
+ event = raised
973
1125
  }
974
- raisedIndex += 1
975
- event = raised
1126
+ } catch (error) {
1127
+ if (restoreIndex !== -1) configuration.values[restoreIndex] = restoreValue
1128
+ throw error
976
1129
  }
977
1130
  }
978
1131
 
979
1132
  const planIndexedState = (
980
1133
  machine: Machine.Any,
981
1134
  descriptor: IndexedExecutionDescriptor,
982
- configuration: OwnedIndexedState,
1135
+ configuration: IndexedExecutionState,
983
1136
  input: unknown,
1137
+ decode: boolean,
984
1138
  retainMicrosteps: boolean,
1139
+ ownership: ExecutionOwnership,
985
1140
  machineReferences?: PlanningMachineReferences
986
- ): ExecutionMacrostep<OwnedIndexedState> => {
1141
+ ): ExecutionMacrostep<IndexedExecutionState> => {
987
1142
  if (InvocationEvent.isInvocationEvent(input)) {
988
1143
  // Invocation lifecycle transitions retain the generic planner as their
989
1144
  // semantic reference. Ordinary machine events and initialization stay on
@@ -998,11 +1153,11 @@ const planIndexedState = (
998
1153
  )
999
1154
  return {
1000
1155
  event: planned.event,
1001
- next: ownedIndexedStateFromActive(descriptor, planned.next),
1156
+ next: indexedStateFromActive(descriptor, planned.next),
1002
1157
  commands: planned.commands,
1003
1158
  emittedEvents: planned.emittedEvents,
1004
1159
  microsteps: planned.microsteps.map((step) => ({
1005
- next: ownedIndexedStateFromActive(descriptor, step.next),
1160
+ next: indexedStateFromActive(descriptor, step.next),
1006
1161
  event: step.event,
1007
1162
  transitions: step.transitions,
1008
1163
  commands: step.commands,
@@ -1016,10 +1171,20 @@ const planIndexedState = (
1016
1171
  output: planned.output
1017
1172
  }
1018
1173
  }
1019
- const decoded = decodeEventSync(machine, input)
1174
+ const decoded: IndexedEvent = decode ? decodeEventSync(machine, input) : input as IndexedEvent
1020
1175
  if (descriptor.flat) {
1021
- return planIndexedFlatState(machine, descriptor, configuration, decoded, retainMicrosteps, machineReferences)
1176
+ return planIndexedFlatState(
1177
+ machine,
1178
+ descriptor,
1179
+ configuration,
1180
+ decoded,
1181
+ retainMicrosteps,
1182
+ ownership,
1183
+ machineReferences
1184
+ )
1022
1185
  }
1186
+ // The hierarchical kernel never writes a state in place, so it plans every
1187
+ // ownership alike.
1023
1188
  if (descriptor.finalIndices.some((index) => configuration.active[index] === 1)) {
1024
1189
  const active = activeConfigurationFromIndexedState(descriptor, configuration)
1025
1190
  if (isActiveFinalConfiguration(machine, active)) {
@@ -1030,7 +1195,7 @@ const planIndexedState = (
1030
1195
  }
1031
1196
  return {
1032
1197
  event: decoded,
1033
- next: ownedIndexedStateFromActive(descriptor, completed),
1198
+ next: indexedStateFromActive(descriptor, completed),
1034
1199
  commands: [],
1035
1200
  emittedEvents: [],
1036
1201
  microsteps: [],
@@ -1059,7 +1224,7 @@ const planIndexedState = (
1059
1224
  const commands = [...first.commands]
1060
1225
  const raisedEvents = [...first.raisedEvents]
1061
1226
  const emittedEvents = [...first.emittedEvents]
1062
- const microsteps = [retainIndexedMicrostep(first, retainMicrosteps)]
1227
+ const microsteps = [first]
1063
1228
  let raisedIndex = 0
1064
1229
  let iterations = 0
1065
1230
 
@@ -1079,7 +1244,7 @@ const planIndexedState = (
1079
1244
  activeConfigurationFromIndexedState(descriptor, current),
1080
1245
  currentEvent
1081
1246
  ).configuration
1082
- current = ownedIndexedStateFromActive(descriptor, completed)
1247
+ current = indexedStateFromActive(descriptor, completed)
1083
1248
  if (isActiveFinalConfiguration(machine, completed)) {
1084
1249
  const root = getRootPath(machine, completed)
1085
1250
  if (!completed.outputs.has(root)) {
@@ -1118,10 +1283,19 @@ const planIndexedState = (
1118
1283
  commands.push(...step.commands)
1119
1284
  raisedEvents.push(...step.raisedEvents)
1120
1285
  emittedEvents.push(...step.emittedEvents)
1121
- microsteps.push(retainIndexedMicrostep(step, retainMicrosteps))
1286
+ microsteps.push(step)
1122
1287
  }
1123
1288
  }
1124
1289
 
1290
+ /**
1291
+ * A machine compiled for planning, with an execution state of its own.
1292
+ *
1293
+ * `plan` takes the {@link ExecutionOwnership} of the state it receives. With
1294
+ * `retainMicrosteps`, each microstep keeps its retained transitions, and its
1295
+ * `next` stays readable for as long as that ownership keeps what a plan returns
1296
+ * valid. Without it, a microstep's `next` may have been written by a later
1297
+ * microstep of the same plan, and only its paths and `changed` are meaningful.
1298
+ */
1125
1299
  export interface CompiledExecutionPlan {
1126
1300
  readonly fromConfiguration: (configuration: ActiveConfiguration) => unknown
1127
1301
  readonly toConfiguration: (state: unknown) => ActiveConfiguration
@@ -1129,7 +1303,19 @@ export interface CompiledExecutionPlan {
1129
1303
  readonly plan: (
1130
1304
  state: unknown,
1131
1305
  event: unknown,
1132
- retainMicrosteps?: boolean,
1306
+ ownership: ExecutionOwnership,
1307
+ retainMicrosteps: boolean,
1308
+ machineReferences?: PlanningMachineReferences
1309
+ ) => ExecutionMacrostep
1310
+ /**
1311
+ * Plans an event that needs no decoding: a public event that
1312
+ * `decodeEventSync` returned, or an invocation event. Otherwise as `plan`.
1313
+ */
1314
+ readonly planDecoded: (
1315
+ state: unknown,
1316
+ event: Machine.EventOf<any> | InvocationEvent.InvocationEvent,
1317
+ ownership: ExecutionOwnership,
1318
+ retainMicrosteps: boolean,
1133
1319
  machineReferences?: PlanningMachineReferences
1134
1320
  ) => ExecutionMacrostep
1135
1321
  readonly initial?: (
@@ -1146,13 +1332,23 @@ export interface CompiledExecutionPlan {
1146
1332
  }
1147
1333
 
1148
1334
  const executionPlanCache = new WeakMap<Machine.Any, CompiledExecutionPlan>()
1335
+ const referenceExecutionPlanCache = new WeakMap<Machine.Any, CompiledExecutionPlan>()
1149
1336
 
1150
1337
  const makeActiveExecutionPlan = (machine: Machine.Any): CompiledExecutionPlan => ({
1151
1338
  fromConfiguration: (configuration) => configuration,
1152
1339
  toConfiguration: (state) => state as ActiveConfiguration,
1153
1340
  snapshot: (state) => snapshotFromConfiguration(machine, state as ActiveConfiguration),
1154
- plan: (state, event, _retainMicrosteps, machineReferences) =>
1341
+ // The reference planner never writes a configuration in place.
1342
+ plan: (state, event, _ownership, _retainMicrosteps, machineReferences) =>
1155
1343
  planConfiguration(
1344
+ machine,
1345
+ machineReferences === undefined
1346
+ ? state as ActiveConfiguration
1347
+ : withMachineReferences(state as ActiveConfiguration, machineReferences),
1348
+ event as Machine.EventOf<any>
1349
+ ),
1350
+ planDecoded: (state, event, _ownership, _retainMicrosteps, machineReferences) =>
1351
+ planDecodedConfiguration(
1156
1352
  machine,
1157
1353
  machineReferences === undefined
1158
1354
  ? state as ActiveConfiguration
@@ -1165,11 +1361,31 @@ const makeIndexedExecutionPlan = (
1165
1361
  machine: Machine.Any,
1166
1362
  indexed: IndexedExecutionDescriptor
1167
1363
  ): CompiledExecutionPlan => ({
1168
- fromConfiguration: (configuration) => ownedIndexedStateFromActive(indexed, configuration),
1169
- toConfiguration: (state) => activeConfigurationFromIndexedState(indexed, state as OwnedIndexedState),
1170
- snapshot: (state) => snapshotFromIndexedState(indexed, state as OwnedIndexedState),
1171
- plan: (state, event, retainMicrosteps = false, machineReferences) =>
1172
- planIndexedState(machine, indexed, state as OwnedIndexedState, event, retainMicrosteps, machineReferences),
1364
+ fromConfiguration: (configuration) => indexedStateFromActive(indexed, configuration),
1365
+ toConfiguration: (state) => activeConfigurationFromIndexedState(indexed, state as IndexedExecutionState),
1366
+ snapshot: (state) => snapshotFromIndexedState(indexed, state as IndexedExecutionState),
1367
+ plan: (state, event, ownership, retainMicrosteps, machineReferences) =>
1368
+ planIndexedState(
1369
+ machine,
1370
+ indexed,
1371
+ state as IndexedExecutionState,
1372
+ event,
1373
+ true,
1374
+ retainMicrosteps,
1375
+ ownership,
1376
+ machineReferences
1377
+ ),
1378
+ planDecoded: (state, event, ownership, retainMicrosteps, machineReferences) =>
1379
+ planIndexedState(
1380
+ machine,
1381
+ indexed,
1382
+ state as IndexedExecutionState,
1383
+ event,
1384
+ false,
1385
+ retainMicrosteps,
1386
+ ownership,
1387
+ machineReferences
1388
+ ),
1173
1389
  // Only captured data constructors can use indexed startup. Unknown initializer
1174
1390
  // protocols retain generic startup so commands and emissions cannot be dropped.
1175
1391
  ...(Object.values(toImpl(machine).handlers as Record<string, CapturedStateConfig>).some((config) =>
@@ -1202,7 +1418,7 @@ const makeIndexedExecutionPlan = (
1202
1418
  ? normalized
1203
1419
  : withMachineReferences(normalized, machineReferences)
1204
1420
  const completed = completeConfigurationSync(machine, active, InitialEvent).configuration
1205
- const configuration = ownedIndexedStateFromActive(indexed, completed)
1421
+ const configuration = indexedStateFromActive(indexed, completed)
1206
1422
  const state = snapshotFromIndexedState(indexed, configuration)
1207
1423
  const done = isActiveFinalConfiguration(machine, completed)
1208
1424
  if (!done) {
@@ -1238,33 +1454,25 @@ export interface SelectedExecutionPlan {
1238
1454
  readonly plan: CompiledExecutionPlan
1239
1455
  }
1240
1456
 
1241
- const selectExecutionPlan = (
1242
- machine: Machine.Any,
1243
- strategy: ExecutionPlanStrategy
1244
- ): SelectedExecutionPlan => {
1245
- if (strategy === "generic") {
1246
- return { strategy, plan: makeActiveExecutionPlan(machine) }
1247
- }
1248
- const indexed = compileIndexedExecutionDescriptor(machine)
1249
- if (indexed === undefined) {
1250
- if (strategy === "auto") {
1251
- return { strategy: "generic", plan: makeActiveExecutionPlan(machine) }
1252
- }
1253
- throw new Error(`Machine cannot compile the requested ${strategy} execution plan`)
1254
- }
1255
- const selected = indexed.flat ? "indexed-flat" : "indexed-hierarchical"
1256
- if (strategy !== "auto" && strategy !== selected) {
1257
- throw new Error(`Machine compiled ${selected}, not the requested ${strategy} execution plan`)
1457
+ const executionPlanStrategyCache = new WeakMap<CompiledExecutionPlan, Exclude<ExecutionPlanStrategy, "auto">>()
1458
+
1459
+ /**
1460
+ * The reference execution plan of `machine`, which always plans on the generic
1461
+ * planner without indexed compilation. Cached per machine.
1462
+ *
1463
+ * @internal
1464
+ */
1465
+ export const referenceExecutionPlan = (machine: Machine.Any): CompiledExecutionPlan => {
1466
+ const cached = referenceExecutionPlanCache.get(machine)
1467
+ if (cached !== undefined) {
1468
+ return cached
1258
1469
  }
1259
- return { strategy: selected, plan: makeIndexedExecutionPlan(machine, indexed) }
1470
+ const reference = makeActiveExecutionPlan(machine)
1471
+ referenceExecutionPlanCache.set(machine, reference)
1472
+ executionPlanStrategyCache.set(reference, "generic")
1473
+ return reference
1260
1474
  }
1261
1475
 
1262
- /** @internal Test-only uncached strategy selection. */
1263
- export const selectExecutionPlanForTesting = (
1264
- machine: Machine.Any,
1265
- strategy: ExecutionPlanStrategy
1266
- ): SelectedExecutionPlan => selectExecutionPlan(machine, strategy)
1267
-
1268
1476
  export const compileExecutionPlan = (machine: Machine.Any): CompiledExecutionPlan => {
1269
1477
  const cached = executionPlanCache.get(machine)
1270
1478
  if (cached !== undefined) {
@@ -1272,8 +1480,30 @@ export const compileExecutionPlan = (machine: Machine.Any): CompiledExecutionPla
1272
1480
  }
1273
1481
  const indexed = compileIndexedExecutionDescriptor(machine)
1274
1482
  const compiled = indexed === undefined
1275
- ? makeActiveExecutionPlan(machine)
1483
+ ? referenceExecutionPlan(machine)
1276
1484
  : makeIndexedExecutionPlan(machine, indexed)
1485
+ if (indexed !== undefined) {
1486
+ executionPlanStrategyCache.set(compiled, indexed.flat ? "indexed-flat" : "indexed-hierarchical")
1487
+ }
1277
1488
  executionPlanCache.set(machine, compiled)
1278
1489
  return compiled
1279
1490
  }
1491
+
1492
+ /** @internal Test-only planner selection, delegating to the cached reference and compiled plans. */
1493
+ export const selectExecutionPlanForTesting = (
1494
+ machine: Machine.Any,
1495
+ strategy: ExecutionPlanStrategy
1496
+ ): SelectedExecutionPlan => {
1497
+ if (strategy === "generic") {
1498
+ return { strategy, plan: referenceExecutionPlan(machine) }
1499
+ }
1500
+ const plan = compileExecutionPlan(machine)
1501
+ const selected = executionPlanStrategyCache.get(plan) ?? "generic"
1502
+ if (strategy !== "auto" && strategy !== selected) {
1503
+ if (selected === "generic") {
1504
+ throw new Error(`Machine cannot compile the requested ${strategy} execution plan`)
1505
+ }
1506
+ throw new Error(`Machine compiled ${selected}, not the requested ${strategy} execution plan`)
1507
+ }
1508
+ return { strategy: selected, plan }
1509
+ }