@pretty-chitty/core 2.0.0 → 2.1.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 (318) hide show
  1. package/README.md +8 -0
  2. package/dist/components/ActionLogDisplay.d.ts.map +1 -1
  3. package/dist/components/ActionLogDisplay.js +1 -1
  4. package/dist/components/ActionLogDisplay.js.map +1 -1
  5. package/dist/components/BottomBarButton.d.ts +3 -1
  6. package/dist/components/BottomBarButton.d.ts.map +1 -1
  7. package/dist/components/BottomBarButton.js +3 -2
  8. package/dist/components/BottomBarButton.js.map +1 -1
  9. package/dist/components/ContextGalleryDisplay.d.ts.map +1 -1
  10. package/dist/components/ContextGalleryDisplay.js +1 -1
  11. package/dist/components/ContextGalleryDisplay.js.map +1 -1
  12. package/dist/components/DemoWrapper.d.ts +30 -2
  13. package/dist/components/DemoWrapper.d.ts.map +1 -1
  14. package/dist/components/DemoWrapper.js +79 -36
  15. package/dist/components/DemoWrapper.js.map +1 -1
  16. package/dist/components/FullScreenGalleryDisplay.d.ts.map +1 -1
  17. package/dist/components/FullScreenGalleryDisplay.js +2 -2
  18. package/dist/components/FullScreenGalleryDisplay.js.map +1 -1
  19. package/dist/components/Gallery/BuiltItem.d.ts +6 -2
  20. package/dist/components/Gallery/BuiltItem.d.ts.map +1 -1
  21. package/dist/components/Gallery/BuiltItem.js +28 -9
  22. package/dist/components/Gallery/BuiltItem.js.map +1 -1
  23. package/dist/components/Gallery/GalleryController.d.ts +18 -0
  24. package/dist/components/Gallery/GalleryController.d.ts.map +1 -1
  25. package/dist/components/Gallery/GalleryController.js +67 -0
  26. package/dist/components/Gallery/GalleryController.js.map +1 -1
  27. package/dist/components/Gallery/GalleryViewer.d.ts +6 -1
  28. package/dist/components/Gallery/GalleryViewer.d.ts.map +1 -1
  29. package/dist/components/Gallery/GalleryViewer.js +48 -10
  30. package/dist/components/Gallery/GalleryViewer.js.map +1 -1
  31. package/dist/components/Gallery/LayoutManager.d.ts +6 -0
  32. package/dist/components/Gallery/LayoutManager.d.ts.map +1 -1
  33. package/dist/components/Gallery/LayoutManager.js +23 -3
  34. package/dist/components/Gallery/LayoutManager.js.map +1 -1
  35. package/dist/components/Gallery/constants.d.ts +2 -0
  36. package/dist/components/Gallery/constants.d.ts.map +1 -1
  37. package/dist/components/Gallery/constants.js +2 -0
  38. package/dist/components/Gallery/constants.js.map +1 -1
  39. package/dist/components/Gallery/registry.d.ts +34 -0
  40. package/dist/components/Gallery/registry.d.ts.map +1 -0
  41. package/dist/components/Gallery/registry.js +17 -0
  42. package/dist/components/Gallery/registry.js.map +1 -0
  43. package/dist/components/GameDesigner.d.ts.map +1 -1
  44. package/dist/components/GameDesigner.js +42 -10
  45. package/dist/components/GameDesigner.js.map +1 -1
  46. package/dist/components/InlineGalleryDisplay.d.ts.map +1 -1
  47. package/dist/components/InlineGalleryDisplay.js +2 -2
  48. package/dist/components/InlineGalleryDisplay.js.map +1 -1
  49. package/dist/components/LiveButton.d.ts.map +1 -1
  50. package/dist/components/LiveButton.js +5 -2
  51. package/dist/components/LiveButton.js.map +1 -1
  52. package/dist/components/MatchViewer.d.ts +6 -1
  53. package/dist/components/MatchViewer.d.ts.map +1 -1
  54. package/dist/components/MatchViewer.js +9 -3
  55. package/dist/components/MatchViewer.js.map +1 -1
  56. package/dist/components/Panel/MultiPanel.d.ts.map +1 -1
  57. package/dist/components/Panel/MultiPanel.js +18 -0
  58. package/dist/components/Panel/MultiPanel.js.map +1 -1
  59. package/dist/components/Panel/PanelContents.d.ts.map +1 -1
  60. package/dist/components/Panel/PanelContents.js +92 -23
  61. package/dist/components/Panel/PanelContents.js.map +1 -1
  62. package/dist/components/Panel/PanelTabStack.d.ts.map +1 -1
  63. package/dist/components/Panel/PanelTabStack.js +1 -1
  64. package/dist/components/Panel/PanelTabStack.js.map +1 -1
  65. package/dist/components/PanelSpark.d.ts.map +1 -1
  66. package/dist/components/PanelSpark.js +3 -2
  67. package/dist/components/PanelSpark.js.map +1 -1
  68. package/dist/components/Playground.d.ts.map +1 -1
  69. package/dist/components/Playground.js +10 -4
  70. package/dist/components/Playground.js.map +1 -1
  71. package/dist/components/PromptControls.d.ts.map +1 -1
  72. package/dist/components/PromptControls.js +4 -2
  73. package/dist/components/PromptControls.js.map +1 -1
  74. package/dist/components/SparkLineChart.d.ts.map +1 -1
  75. package/dist/components/SparkLineChart.js +22 -26
  76. package/dist/components/SparkLineChart.js.map +1 -1
  77. package/dist/components/TimeControlBar.d.ts.map +1 -1
  78. package/dist/components/TimeControlBar.js +5 -3
  79. package/dist/components/TimeControlBar.js.map +1 -1
  80. package/dist/components/TokenizedMarkdown.d.ts +23 -0
  81. package/dist/components/TokenizedMarkdown.d.ts.map +1 -0
  82. package/dist/components/TokenizedMarkdown.js +144 -0
  83. package/dist/components/TokenizedMarkdown.js.map +1 -0
  84. package/dist/components/TokenizedMessage.d.ts +6 -0
  85. package/dist/components/TokenizedMessage.d.ts.map +1 -1
  86. package/dist/components/TokenizedMessage.js +20 -19
  87. package/dist/components/TokenizedMessage.js.map +1 -1
  88. package/dist/components/TopBarPlayers.d.ts.map +1 -1
  89. package/dist/components/TopBarPlayers.js +1 -1
  90. package/dist/components/TopBarPlayers.js.map +1 -1
  91. package/dist/components/Tutorial/BrowserNarration.d.ts +55 -0
  92. package/dist/components/Tutorial/BrowserNarration.d.ts.map +1 -0
  93. package/dist/components/Tutorial/BrowserNarration.js +240 -0
  94. package/dist/components/Tutorial/BrowserNarration.js.map +1 -0
  95. package/dist/components/Tutorial/TutorialBox.d.ts +26 -0
  96. package/dist/components/Tutorial/TutorialBox.d.ts.map +1 -0
  97. package/dist/components/Tutorial/TutorialBox.js +239 -0
  98. package/dist/components/Tutorial/TutorialBox.js.map +1 -0
  99. package/dist/components/Tutorial/TutorialDevPanel.d.ts +9 -0
  100. package/dist/components/Tutorial/TutorialDevPanel.d.ts.map +1 -0
  101. package/dist/components/Tutorial/TutorialDevPanel.js +92 -0
  102. package/dist/components/Tutorial/TutorialDevPanel.js.map +1 -0
  103. package/dist/components/Tutorial/TutorialOverlay.d.ts +7 -0
  104. package/dist/components/Tutorial/TutorialOverlay.d.ts.map +1 -0
  105. package/dist/components/Tutorial/TutorialOverlay.js +1132 -0
  106. package/dist/components/Tutorial/TutorialOverlay.js.map +1 -0
  107. package/dist/components/Tutorial/targetRects.d.ts +67 -0
  108. package/dist/components/Tutorial/targetRects.d.ts.map +1 -0
  109. package/dist/components/Tutorial/targetRects.js +241 -0
  110. package/dist/components/Tutorial/targetRects.js.map +1 -0
  111. package/dist/game/Chit.d.ts +7 -0
  112. package/dist/game/Chit.d.ts.map +1 -1
  113. package/dist/game/Chit.js +20 -5
  114. package/dist/game/Chit.js.map +1 -1
  115. package/dist/game/ClientTimeState.d.ts +14 -0
  116. package/dist/game/ClientTimeState.d.ts.map +1 -1
  117. package/dist/game/ClientTimeState.js +17 -0
  118. package/dist/game/ClientTimeState.js.map +1 -1
  119. package/dist/game/Game.d.ts +6 -0
  120. package/dist/game/Game.d.ts.map +1 -1
  121. package/dist/game/GameTheme.d.ts +3 -0
  122. package/dist/game/GameTheme.d.ts.map +1 -1
  123. package/dist/game/GameTheme.js +2 -0
  124. package/dist/game/GameTheme.js.map +1 -1
  125. package/dist/game/Match.d.ts +8 -2
  126. package/dist/game/Match.d.ts.map +1 -1
  127. package/dist/game/Match.js +4 -1
  128. package/dist/game/Match.js.map +1 -1
  129. package/dist/game/Pick.d.ts +2 -0
  130. package/dist/game/Pick.d.ts.map +1 -1
  131. package/dist/game/Pick.js +17 -1
  132. package/dist/game/Pick.js.map +1 -1
  133. package/dist/game/PlayerPromptStatusChit.d.ts +8 -0
  134. package/dist/game/PlayerPromptStatusChit.d.ts.map +1 -1
  135. package/dist/game/PlayerPromptStatusChit.js +5 -1
  136. package/dist/game/PlayerPromptStatusChit.js.map +1 -1
  137. package/dist/game/Prompt.d.ts +15 -0
  138. package/dist/game/Prompt.d.ts.map +1 -1
  139. package/dist/game/Prompt.js +16 -0
  140. package/dist/game/Prompt.js.map +1 -1
  141. package/dist/game/Turn.d.ts +15 -4
  142. package/dist/game/Turn.d.ts.map +1 -1
  143. package/dist/game/Turn.js +173 -60
  144. package/dist/game/Turn.js.map +1 -1
  145. package/dist/game/TurnState.d.ts +12 -1
  146. package/dist/game/TurnState.d.ts.map +1 -1
  147. package/dist/game/TurnState.js +15 -3
  148. package/dist/game/TurnState.js.map +1 -1
  149. package/dist/game/ai/AiClientPrompts.d.ts +20 -3
  150. package/dist/game/ai/AiClientPrompts.d.ts.map +1 -1
  151. package/dist/game/ai/AiClientPrompts.js +42 -6
  152. package/dist/game/ai/AiClientPrompts.js.map +1 -1
  153. package/dist/game/ai/AiPlayerView.js +2 -0
  154. package/dist/game/ai/AiPlayerView.js.map +1 -1
  155. package/dist/game/clientTransport/ClientPrompts.d.ts +20 -1
  156. package/dist/game/clientTransport/ClientPrompts.d.ts.map +1 -1
  157. package/dist/game/clientTransport/ClientPrompts.js +30 -1
  158. package/dist/game/clientTransport/ClientPrompts.js.map +1 -1
  159. package/dist/game/clientTransport/ClientTime.d.ts +13 -0
  160. package/dist/game/clientTransport/ClientTime.d.ts.map +1 -1
  161. package/dist/game/clientTransport/ClientTime.js +51 -11
  162. package/dist/game/clientTransport/ClientTime.js.map +1 -1
  163. package/dist/game/tutorial/TutorialController.d.ts +300 -0
  164. package/dist/game/tutorial/TutorialController.d.ts.map +1 -0
  165. package/dist/game/tutorial/TutorialController.js +1182 -0
  166. package/dist/game/tutorial/TutorialController.js.map +1 -0
  167. package/dist/game/tutorial/TutorialRuntime.d.ts +89 -0
  168. package/dist/game/tutorial/TutorialRuntime.d.ts.map +1 -0
  169. package/dist/game/tutorial/TutorialRuntime.js +261 -0
  170. package/dist/game/tutorial/TutorialRuntime.js.map +1 -0
  171. package/dist/game/tutorial/TutorialTheme.d.ts +28 -0
  172. package/dist/game/tutorial/TutorialTheme.d.ts.map +1 -0
  173. package/dist/game/tutorial/TutorialTheme.js +39 -0
  174. package/dist/game/tutorial/TutorialTheme.js.map +1 -0
  175. package/dist/game/tutorial/allowed.d.ts +2 -0
  176. package/dist/game/tutorial/allowed.d.ts.map +1 -0
  177. package/dist/game/tutorial/allowed.js +119 -0
  178. package/dist/game/tutorial/allowed.js.map +1 -0
  179. package/dist/game/tutorial/checks.d.ts +58 -0
  180. package/dist/game/tutorial/checks.d.ts.map +1 -0
  181. package/dist/game/tutorial/checks.js +144 -0
  182. package/dist/game/tutorial/checks.js.map +1 -0
  183. package/dist/game/tutorial/createDemoMatch.d.ts +47 -0
  184. package/dist/game/tutorial/createDemoMatch.d.ts.map +1 -0
  185. package/dist/game/tutorial/createDemoMatch.js +67 -0
  186. package/dist/game/tutorial/createDemoMatch.js.map +1 -0
  187. package/dist/game/tutorial/defineTutorial.d.ts +353 -0
  188. package/dist/game/tutorial/defineTutorial.d.ts.map +1 -0
  189. package/dist/game/tutorial/defineTutorial.js +86 -0
  190. package/dist/game/tutorial/defineTutorial.js.map +1 -0
  191. package/dist/game/tutorial/runTutorial.d.ts +63 -0
  192. package/dist/game/tutorial/runTutorial.d.ts.map +1 -0
  193. package/dist/game/tutorial/runTutorial.js +273 -0
  194. package/dist/game/tutorial/runTutorial.js.map +1 -0
  195. package/dist/hooks/usePanelNavigation.d.ts +28 -0
  196. package/dist/hooks/usePanelNavigation.d.ts.map +1 -0
  197. package/dist/hooks/usePanelNavigation.js +36 -0
  198. package/dist/hooks/usePanelNavigation.js.map +1 -0
  199. package/dist/hooks/useTimeController.d.ts +2 -1
  200. package/dist/hooks/useTimeController.d.ts.map +1 -1
  201. package/dist/hooks/useTimeController.js +6 -2
  202. package/dist/hooks/useTimeController.js.map +1 -1
  203. package/dist/hooks/useTutorial.d.ts +48 -0
  204. package/dist/hooks/useTutorial.d.ts.map +1 -0
  205. package/dist/hooks/useTutorial.js +16 -0
  206. package/dist/hooks/useTutorial.js.map +1 -0
  207. package/dist/index.d.ts +36 -0
  208. package/dist/index.d.ts.map +1 -1
  209. package/dist/index.html +12 -0
  210. package/dist/index.js +19 -2
  211. package/dist/index.js.map +1 -1
  212. package/dist/main.0792d734cde2c688d5f7.hot-update.js +16991 -0
  213. package/dist/main.0792d734cde2c688d5f7.hot-update.js.map +1 -0
  214. package/dist/main.0792d734cde2c688d5f7.hot-update.json +1 -0
  215. package/dist/pretty-chitty.js +204513 -0
  216. package/dist/pretty-chitty.js.map +1 -0
  217. package/dist/rendering/CameraWrapperPerspective.d.ts +5 -0
  218. package/dist/rendering/CameraWrapperPerspective.d.ts.map +1 -1
  219. package/dist/rendering/CameraWrapperPerspective.js +16 -0
  220. package/dist/rendering/CameraWrapperPerspective.js.map +1 -1
  221. package/dist/rendering/ChitGalleryItemInstance.d.ts +1 -0
  222. package/dist/rendering/ChitGalleryItemInstance.d.ts.map +1 -1
  223. package/dist/rendering/ChitGalleryItemInstance.js +12 -0
  224. package/dist/rendering/ChitGalleryItemInstance.js.map +1 -1
  225. package/dist/rendering/ChitRenderInstance.d.ts +9 -1
  226. package/dist/rendering/ChitRenderInstance.d.ts.map +1 -1
  227. package/dist/rendering/ChitRenderInstance.js +28 -0
  228. package/dist/rendering/ChitRenderInstance.js.map +1 -1
  229. package/dist/rendering/RootChitRenderInstance.d.ts +2 -0
  230. package/dist/rendering/RootChitRenderInstance.d.ts.map +1 -1
  231. package/dist/rendering/RootChitRenderInstance.js +29 -0
  232. package/dist/rendering/RootChitRenderInstance.js.map +1 -1
  233. package/dist/utilities/Annotations.d.ts +15 -0
  234. package/dist/utilities/Annotations.d.ts.map +1 -1
  235. package/dist/utilities/Annotations.js +31 -7
  236. package/dist/utilities/Annotations.js.map +1 -1
  237. package/dist/utilities/CanvasStack/CanvasStack.d.ts +2 -0
  238. package/dist/utilities/CanvasStack/CanvasStack.d.ts.map +1 -1
  239. package/dist/utilities/CanvasStack/CanvasStack.js +4 -0
  240. package/dist/utilities/CanvasStack/CanvasStack.js.map +1 -1
  241. package/dist/utilities/TokenizedText.d.ts +6 -0
  242. package/dist/utilities/TokenizedText.d.ts.map +1 -1
  243. package/dist/utilities/TokenizedText.js.map +1 -1
  244. package/dist/utilities/zIndex.d.ts +1 -0
  245. package/dist/utilities/zIndex.d.ts.map +1 -1
  246. package/dist/utilities/zIndex.js +1 -0
  247. package/dist/utilities/zIndex.js.map +1 -1
  248. package/package.json +3 -2
  249. package/src/library/components/ActionLogDisplay.tsx +1 -0
  250. package/src/library/components/BottomBarButton.tsx +5 -0
  251. package/src/library/components/ContextGalleryDisplay.tsx +2 -0
  252. package/src/library/components/DemoWrapper.tsx +147 -44
  253. package/src/library/components/FullScreenGalleryDisplay.tsx +3 -0
  254. package/src/library/components/Gallery/BuiltItem.ts +30 -9
  255. package/src/library/components/Gallery/GalleryController.ts +72 -1
  256. package/src/library/components/Gallery/GalleryViewer.tsx +54 -10
  257. package/src/library/components/Gallery/LayoutManager.ts +30 -6
  258. package/src/library/components/Gallery/constants.ts +2 -0
  259. package/src/library/components/Gallery/registry.ts +44 -0
  260. package/src/library/components/GameDesigner.tsx +121 -12
  261. package/src/library/components/InlineGalleryDisplay.tsx +5 -0
  262. package/src/library/components/LiveButton.tsx +8 -5
  263. package/src/library/components/MatchViewer.tsx +14 -3
  264. package/src/library/components/Panel/MultiPanel.tsx +21 -0
  265. package/src/library/components/Panel/PanelContents.tsx +70 -1
  266. package/src/library/components/Panel/PanelTabStack.tsx +1 -0
  267. package/src/library/components/PanelSpark.tsx +9 -4
  268. package/src/library/components/Playground.tsx +48 -21
  269. package/src/library/components/PromptControls.tsx +7 -3
  270. package/src/library/components/SparkLineChart.tsx +23 -27
  271. package/src/library/components/TimeControlBar.tsx +5 -3
  272. package/src/library/components/TokenizedMarkdown.tsx +224 -0
  273. package/src/library/components/TokenizedMessage.tsx +28 -32
  274. package/src/library/components/TopBarPlayers.tsx +12 -9
  275. package/src/library/components/Tutorial/BrowserNarration.ts +233 -0
  276. package/src/library/components/Tutorial/TutorialBox.tsx +506 -0
  277. package/src/library/components/Tutorial/TutorialDevPanel.tsx +297 -0
  278. package/src/library/components/Tutorial/TutorialOverlay.tsx +1301 -0
  279. package/src/library/components/Tutorial/targetRects.ts +273 -0
  280. package/src/library/game/Chit.ts +21 -5
  281. package/src/library/game/ClientTimeState.ts +18 -0
  282. package/src/library/game/Game.ts +7 -0
  283. package/src/library/game/GameTheme.ts +4 -0
  284. package/src/library/game/Match.ts +12 -2
  285. package/src/library/game/Pick.ts +16 -1
  286. package/src/library/game/PlayerPromptStatusChit.ts +5 -1
  287. package/src/library/game/Prompt.ts +20 -0
  288. package/src/library/game/Turn.ts +179 -61
  289. package/src/library/game/TurnState.ts +26 -3
  290. package/src/library/game/ai/AI_GUIDE.md +10 -0
  291. package/src/library/game/ai/AiClientPrompts.ts +60 -11
  292. package/src/library/game/ai/AiPlayerView.ts +2 -0
  293. package/src/library/game/clientTransport/ClientPrompts.ts +31 -1
  294. package/src/library/game/clientTransport/ClientTime.ts +54 -13
  295. package/src/library/game/serialize.test.ts +275 -0
  296. package/src/library/game/tutorial/TUTORIAL_GUIDE.md +411 -0
  297. package/src/library/game/tutorial/TutorialController.test.ts +731 -0
  298. package/src/library/game/tutorial/TutorialController.ts +1286 -0
  299. package/src/library/game/tutorial/TutorialRuntime.ts +311 -0
  300. package/src/library/game/tutorial/TutorialTheme.ts +67 -0
  301. package/src/library/game/tutorial/allowed.ts +145 -0
  302. package/src/library/game/tutorial/checks.ts +186 -0
  303. package/src/library/game/tutorial/createDemoMatch.ts +115 -0
  304. package/src/library/game/tutorial/defineTutorial.ts +414 -0
  305. package/src/library/game/tutorial/runTutorial.ts +331 -0
  306. package/src/library/game/undo.test.ts +282 -0
  307. package/src/library/hooks/usePanelNavigation.tsx +65 -0
  308. package/src/library/hooks/useTimeController.tsx +6 -2
  309. package/src/library/hooks/useTutorial.tsx +76 -0
  310. package/src/library/index.ts +57 -2
  311. package/src/library/rendering/CameraWrapperPerspective.ts +17 -0
  312. package/src/library/rendering/ChitGalleryItemInstance.ts +12 -0
  313. package/src/library/rendering/ChitRenderInstance.ts +34 -0
  314. package/src/library/rendering/RootChitRenderInstance.ts +30 -1
  315. package/src/library/utilities/Annotations.ts +35 -7
  316. package/src/library/utilities/CanvasStack/CanvasStack.ts +6 -1
  317. package/src/library/utilities/TokenizedText.ts +6 -0
  318. package/src/library/utilities/zIndex.ts +1 -0
@@ -93,17 +93,50 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
93
93
  private lockedChitStates: ChitStateLookup = {};
94
94
  private lastChitStates: ChitStateLookup = {};
95
95
  private dirtyChitIds = new Set<string>();
96
+ // Locked roots of absorbed sub-turns. A sub-turn never deletes its own locked roots, so the next
97
+ // flush here checks whether any of them lost their parent.
98
+ private absorbedRootIds = new Set<string>();
96
99
  private pendingNewChits = new Set<Chit>();
97
100
  private _statePool?: Map<string, string>;
98
- private _serializeCache?: SerializeCache;
101
+
102
+ // serialize() replays this turn's diffs from its locked snapshot. Checkpoints are that replay
103
+ // captured part-way, so a request walks only the steps after the nearest one. They cover only
104
+ // steps that can no longer change (flushes, and sub-turn steps every turn of which the parent
105
+ // has absorbed) and merge sub-turns in absorption order, so they hold the same chit states for
106
+ // every player and are shared by every connection to the match.
107
+ private _checkpoints: SerializeCheckpoint[] = [];
108
+ // Set once the parent has absorbed this turn. From then on we are only walked by the parent, which
109
+ // holds the chit map we started from, so we keep neither our locked snapshot nor checkpoints.
110
+ private absorbed = false;
111
+ /** Tests only: false keeps every finished turn's snapshot and checkpoints. @internal */
112
+ static releaseAbsorbedTurns = true;
113
+ /** Steps between checkpoints: the most a request walks before it reaches the live step. @internal */
114
+ static serializeCheckpointInterval = 32;
115
+ /** Tests only: false makes every serialize() replay from the locked snapshot. @internal */
116
+ static serializeCheckpoints = true;
117
+
118
+ /** Drop every checkpoint that includes the step at `index`, which is about to change. */
119
+ private dropCheckpointsFrom(index: number) {
120
+ if (this._checkpoints.length && this._checkpoints[this._checkpoints.length - 1].nextIndex > index) {
121
+ this._checkpoints = this._checkpoints.filter((c) => c.nextIndex <= index);
122
+ }
123
+ }
99
124
 
100
125
  /**
101
- * Drop any cached serialize() reconstruction on this turn and every ancestor,
102
- * since their snapshots include our contribution.
126
+ * Checkpoints stay at least `serializeCheckpointInterval` steps apart, except the last one,
127
+ * which marks wherever the latest walk ended and is replaced as walks reach further.
103
128
  */
104
- private invalidateSerializeCache() {
105
- this._serializeCache = undefined;
106
- this.parent?.invalidateSerializeCache();
129
+ private addCheckpoint(checkpoint: SerializeCheckpoint) {
130
+ const checkpoints = this._checkpoints;
131
+ const last = checkpoints[checkpoints.length - 1];
132
+ if (last && last.nextIndex >= checkpoint.nextIndex) {
133
+ return;
134
+ }
135
+ const previous = checkpoints.length >= 2 ? checkpoints[checkpoints.length - 2].nextIndex : 0;
136
+ if (last && last.nextIndex - previous < Turn.serializeCheckpointInterval) {
137
+ checkpoints.pop();
138
+ }
139
+ checkpoints.push(checkpoint);
107
140
  }
108
141
 
109
142
  private get statePool(): Map<string, string> {
@@ -200,12 +233,18 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
200
233
  return p.id;
201
234
  });
202
235
 
203
- // now serialize all chits in their "locked" state
236
+ // now serialize all chits in their "locked" state. createTurn flushes the parent right before
237
+ // building us, so a clean chit's state there is already current and interned.
238
+ const parentStates = this.parent?.lastChitStates;
204
239
  Object.values(this.chitLookup).forEach((c) => {
205
240
  if (!c.id) {
206
241
  throw new Error("Cannot serialize a chit without an id");
207
242
  }
208
- this.lastChitStates[c.id] = this.lockedChitStates[c.id] = this.internState(c.serialize(this._playerIds));
243
+ const parentState = parentStates?.[c.id];
244
+ this.lastChitStates[c.id] = this.lockedChitStates[c.id] =
245
+ parentState !== undefined && parentState !== Chit.deletedIfSerialized() && !c._dirty
246
+ ? parentState
247
+ : this.internState(c.serialize(this._playerIds));
209
248
  });
210
249
  }
211
250
 
@@ -276,6 +315,7 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
276
315
 
277
316
  const flushStep = step as FlushClockStep;
278
317
  flushStep.log = message;
318
+ this.dropCheckpointsFrom(this.clockSteps.length - 1);
279
319
  }
280
320
 
281
321
  /**
@@ -302,6 +342,7 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
302
342
  message = message(step.log!);
303
343
  }
304
344
  step.log = message;
345
+ this.dropCheckpointsFrom(lastIndex);
305
346
  }
306
347
 
307
348
  _zipStartPoint = 0;
@@ -330,8 +371,8 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
330
371
  }
331
372
 
332
373
  if (hasChange) {
333
- // Pops and in-place merges can leave any cached walk pointing into invalid territory.
334
- this.invalidateSerializeCache();
374
+ // The merged step changed in place: checkpoints that include it are stale.
375
+ this.dropCheckpointsFrom(this.clockSteps.length - 1);
335
376
  this.pass++;
336
377
  // No trailing force-flush: it would only push an empty FlushClockStep (no chit
337
378
  // diff, no log) that the client has to walk through for no visual change. The
@@ -401,17 +442,22 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
401
442
  sawChange = true;
402
443
  }
403
444
  }
404
- this.dirtyChitIds.clear();
405
445
 
406
- // 3. Detect deleted chits — orphans in lastChitStates that weren't serialized above
407
- const deletedRoots: Chit[] = [];
408
- for (const id of Object.keys(this.lastChitStates)) {
409
- if (this.lastChitStates[id] === Chit.deletedIfSerialized()) continue;
446
+ // 3. Detect deleted chits — orphans in lastChitStates. Losing a parent marks a chit dirty, so
447
+ // only this flush's dirty chits and the roots of absorbed sub-turns can have become orphans.
448
+ const deletedRoots = new Set<Chit>();
449
+ const checkOrphan = (id: string) => {
450
+ const lastState = this.lastChitStates[id];
451
+ if (lastState === undefined || lastState === Chit.deletedIfSerialized()) return;
410
452
  const chit = this.chitLookup[id];
411
453
  if (chit && !chit.parent && !this.chitsToLock.includes(chit)) {
412
- deletedRoots.push(chit);
454
+ deletedRoots.add(chit);
413
455
  }
414
- }
456
+ };
457
+ this.dirtyChitIds.forEach(checkOrphan);
458
+ this.absorbedRootIds.forEach(checkOrphan);
459
+ this.dirtyChitIds.clear();
460
+ this.absorbedRootIds.clear();
415
461
 
416
462
  for (const chit of deletedRoots) {
417
463
  if (chit.id) {
@@ -436,9 +482,9 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
436
482
  throw new Error("Cannot flush while subturns are active");
437
483
  }
438
484
 
485
+ // Appending leaves every checkpoint valid, ours and our ancestors': theirs stop before the
486
+ // step that holds us until we have been absorbed.
439
487
  this.clockSteps.push(new FlushClockStep(this.clock, newStates));
440
- // Ancestors' caches included our prior contribution; the new step makes them stale.
441
- this.parent?.invalidateSerializeCache();
442
488
  }
443
489
  }
444
490
 
@@ -493,17 +539,19 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
493
539
 
494
540
  this.decisionIndex++;
495
541
 
542
+ let step: SubTurnsClockStep<P, R>;
496
543
  if (this.activeSubTurns.length === 0) {
497
- this.clockSteps.push(new SubTurnsClockStep(this.clock, [turn]));
544
+ step = new SubTurnsClockStep(this.clock, [turn]);
545
+ this.clockSteps.push(step);
498
546
  } else {
499
547
  const lastStep = this.clockSteps[this.clockSteps.length - 1];
500
548
  if (!(lastStep instanceof SubTurnsClockStep)) {
501
549
  throw new Error("Unexpected clocksteps stage");
502
550
  }
503
551
  lastStep.turns.push(turn);
552
+ step = lastStep;
504
553
  }
505
- // Either case mutates a step our own cache (or an ancestor's) may have already walked past.
506
- this.invalidateSerializeCache();
554
+ // Neither case touches a checkpoint: none reaches a step with a turn still to absorb.
507
555
 
508
556
  this.activeSubTurns.push(turn);
509
557
 
@@ -526,6 +574,10 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
526
574
  });
527
575
 
528
576
  this.lastChitStates = { ...this.lastChitStates, ...turn.lastChitStates };
577
+ turn.chitsToLock.forEach((chit) => chit.id && this.absorbedRootIds.add(chit.id));
578
+ // serialize() merges the step's turns in this order, so a chit written by several parallel
579
+ // turns serializes as the engine now holds it.
580
+ step.absorbed.push(turn);
529
581
  turn.releasePostAbsorptionRefs();
530
582
 
531
583
  return result;
@@ -534,8 +586,8 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
534
586
  /**
535
587
  * Called by the parent right after it has absorbed our `chitLookup` and `lastChitStates`.
536
588
  * After this we will only ever be walked via `serialize` / `chitsHistory` / `gameLog`,
537
- * which only need `clockSteps` and `lockedChitStates` — so drop the heavy per-chit
538
- * bookkeeping to keep finished sub-turns from pinning hundreds of chit references.
589
+ * and only by the parent, which needs nothing of ours but `clockSteps` — so drop the heavy
590
+ * per-chit bookkeeping to keep finished sub-turns from pinning hundreds of chit references.
539
591
  * @internal
540
592
  */
541
593
  private releasePostAbsorptionRefs() {
@@ -544,7 +596,14 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
544
596
  this.lastChitStates = {};
545
597
  this.pendingNewChits.clear();
546
598
  this.dirtyChitIds.clear();
547
- this._serializeCache = undefined;
599
+ this.absorbedRootIds.clear();
600
+ if (!Turn.releaseAbsorbedTurns) return;
601
+ // The locked snapshot and every checkpoint are full copies of the chit map, and a long game
602
+ // has hundreds of finished turns. The parent walks into us with its own map, which at our
603
+ // step holds exactly what the snapshot held, so a finished turn keeps neither.
604
+ this.absorbed = true;
605
+ this.lockedChitStates = {};
606
+ this._checkpoints = [];
548
607
  }
549
608
 
550
609
  public async runParallelTurns<A>(
@@ -821,7 +880,8 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
821
880
  };
822
881
 
823
882
  // Seed with the initial locked state so chits that never diff in this turn still
824
- // surface their starting form (flush steps now hold diffs only).
883
+ // surface their starting form (flush steps now hold diffs only). A finished turn has no
884
+ // snapshot; the parent already logged that state before walking into it.
825
885
  ids.forEach((id) => {
826
886
  const initial = this.lockedChitStates[id];
827
887
  if (initial !== undefined) {
@@ -846,8 +906,12 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
846
906
  return result;
847
907
  }
848
908
 
849
- /** @internal */
850
- serialize(playerId: string, clock: number): ChitSerializationResponse {
909
+ /**
910
+ * `into` is the parent's working chit map while it walks this turn. A finished turn has no
911
+ * snapshot of its own and writes its diffs straight into it; the parent then needs no merge.
912
+ * @internal
913
+ */
914
+ serialize(playerId: string, clock: number, into?: ChitStateLookup): ChitSerializationResponse {
851
915
  clock = Math.max(0, Math.min(clock, this.playerVisibleClockTime(playerId)));
852
916
 
853
917
  let chits: ChitStateLookup;
@@ -856,24 +920,41 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
856
920
  let resultingClock: number;
857
921
  let index: number;
858
922
 
859
- const cache = this._serializeCache;
860
- if (cache && cache.playerId === playerId && clock >= cache.resultingClock) {
861
- chits = { ...cache.chits };
862
- subTurns = cache.subTurns ? { ...cache.subTurns } : undefined;
863
- log = cache.log ? { ...cache.log } : undefined;
864
- resultingClock = cache.resultingClock;
865
- index = cache.nextIndex;
923
+ // Resume from the furthest checkpoint that ends at or before the target clock
924
+ let checkpoint: SerializeCheckpoint | undefined;
925
+ for (let i = this._checkpoints.length - 1; i >= 0; i--) {
926
+ if (this._checkpoints[i].resultingClock <= clock) {
927
+ checkpoint = this._checkpoints[i];
928
+ break;
929
+ }
930
+ }
931
+ if (checkpoint) {
932
+ chits = { ...checkpoint.chits };
933
+ subTurns = checkpoint.subTurns ? { ...checkpoint.subTurns } : undefined;
934
+ log = checkpoint.log ? { ...checkpoint.log } : undefined;
935
+ resultingClock = checkpoint.resultingClock;
936
+ index = checkpoint.nextIndex;
866
937
  } else {
867
938
  // Diff-replay: seed with the initial locked snapshot and merge every flush diff
868
- // up to (but not including) the target clock.
869
- chits = { ...this.lockedChitStates };
939
+ // up to (but not including) the target clock. A finished turn's snapshot was the parent's
940
+ // map at this step, which is what the parent hands us.
941
+ chits = this.absorbed ? (into ?? {}) : { ...this.lockedChitStates };
870
942
  subTurns = undefined;
871
943
  log = undefined;
872
944
  resultingClock = -1;
873
945
  index = 0;
874
946
  }
875
947
 
876
- let cacheable = true;
948
+ const snapshot = (): SerializeCheckpoint => ({
949
+ nextIndex: index,
950
+ chits: { ...chits },
951
+ subTurns: subTurns ? { ...subTurns } : undefined,
952
+ log: log ? { ...log } : undefined,
953
+ resultingClock: resultingClock === -1 ? clock : resultingClock,
954
+ });
955
+ // True while every step walked is final and was consumed whole, so the walk may be checkpointed
956
+ let checkpointable = Turn.serializeCheckpoints && !this.absorbed;
957
+ let lastCheckpointIndex = index;
877
958
  while (index < this.clockSteps.length) {
878
959
  const clockStep = this.clockSteps[index];
879
960
  if (clockStep.startClock >= clock) break;
@@ -890,13 +971,21 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
890
971
  subTurns = {};
891
972
  resultingClock = clockStep.startClock;
892
973
  let remainingClocksToSpend = clock - clockStep.startClock;
893
- for (const turn of clockStep.visibleTurns(playerId)) {
974
+ // A step every turn of which has been absorbed is final, and asked for in full it reads the
975
+ // same for every player: its turns merge in absorption order, the order their changes
976
+ // landed in `lastChitStates`, so a chit written by two parallel turns serializes as the
977
+ // engine holds it. A step still in motion, or asked for part-way, is walked as this player
978
+ // may see it, and the walk stops there: a later request has to re-walk it.
979
+ const final = clockStep.fullyAbsorbed && clock >= clockStep.endClock();
980
+ for (const turn of final ? clockStep.absorbed : clockStep.visibleTurns(playerId)) {
894
981
  const time = Math.max(remainingClocksToSpend, 0);
895
982
  if (time <= 0) break;
896
983
 
897
984
  // we are going forward so we never want to have a turn go backwards. ever.
898
- const serialized = turn.serialize(playerId, time);
899
- Object.assign(chits, serialized.chits);
985
+ const serialized = turn.serialize(playerId, time, chits);
986
+ if (serialized.chits !== chits) {
987
+ Object.assign(chits, serialized.chits);
988
+ }
900
989
 
901
990
  resultingClock += serialized.clockDetails.clock;
902
991
  remainingClocksToSpend -= serialized.clockDetails.clock;
@@ -905,30 +994,24 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
905
994
  log = { message: serialized.log.message, clock: serialized.log.clock + clockStep.startClock };
906
995
  }
907
996
  }
908
- // We can only advance `index` past this step (and cache from here) if the
909
- // requested `clock` consumed this step's *entire* extent — i.e. every visible
910
- // sub-turn was asked for at least its full clock time. Otherwise a future
911
- // request at a higher `clock` needs to re-ask the sub-turn for more time,
912
- // which means re-processing this same step.
913
- if (clock < clockStep.endClock(playerId)) {
914
- cacheable = false;
997
+ if (!final) {
998
+ checkpointable = false;
915
999
  break;
916
1000
  }
917
1001
  index++;
918
1002
  } else {
919
1003
  index++;
920
1004
  }
1005
+
1006
+ if (checkpointable && index - lastCheckpointIndex >= Turn.serializeCheckpointInterval) {
1007
+ this.addCheckpoint(snapshot());
1008
+ lastCheckpointIndex = index;
1009
+ }
921
1010
  }
922
1011
 
923
- if (cacheable) {
924
- this._serializeCache = {
925
- playerId,
926
- nextIndex: index,
927
- chits: { ...chits },
928
- subTurns: subTurns ? { ...subTurns } : undefined,
929
- log: log ? { ...log } : undefined,
930
- resultingClock: resultingClock === -1 ? clock : resultingClock,
931
- };
1012
+ // Remember where this walk ended, so a request for a later clock continues from here
1013
+ if (checkpointable && index > lastCheckpointIndex) {
1014
+ this.addCheckpoint(snapshot());
932
1015
  }
933
1016
 
934
1017
  return {
@@ -1202,8 +1285,34 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
1202
1285
  return result;
1203
1286
  }
1204
1287
 
1288
+ /**
1289
+ * Takes every chit this turn made (and those a sub-turn still running under it made) off the board,
1290
+ * ahead of a parent's restart. The parent never absorbed us, so its own reset knows nothing of them:
1291
+ * left alone they would stay on the board, and the next sub-turn would lock them as if they had
1292
+ * always been there. Chits we only changed are the parent's to restore.
1293
+ */
1294
+ private discardCreatedChits() {
1295
+ this.activeSubTurns.forEach((t) => t.discardCreatedChits());
1296
+ for (const chit of Object.values(this.chitLookup)) {
1297
+ if (chit.id && this.lockedChitStates[chit.id] === undefined) {
1298
+ chit.forgetFallbackUnlessHidden();
1299
+ chit.removeFromParent();
1300
+ }
1301
+ }
1302
+ for (const chit of this.pendingNewChits) {
1303
+ if (!chit.id) {
1304
+ chit.forgetFallbackUnlessHidden();
1305
+ chit.removeFromParent();
1306
+ }
1307
+ }
1308
+ this.pendingNewChits.clear();
1309
+ }
1310
+
1205
1311
  private restartExecution() {
1206
- this.activeSubTurns.forEach((t) => t.destroy());
1312
+ this.activeSubTurns.forEach((t) => {
1313
+ t.discardCreatedChits();
1314
+ t.destroy();
1315
+ });
1207
1316
 
1208
1317
  const chits = Object.values(this.chitLookup).filter((chit) => chit.id);
1209
1318
 
@@ -1216,6 +1325,7 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
1216
1325
  if (lockedState) {
1217
1326
  chit.deserialize(lockedState, this.findChit);
1218
1327
  } else {
1328
+ chit.forgetFallbackUnlessHidden(); // a chit made to come from another piece must not linger beside it
1219
1329
  chit.removeFromParent(); // effectively "deletes" it. In practice, the `fn` will recreate a new chit which will have the new ID, which replaces this one.
1220
1330
  }
1221
1331
  });
@@ -1235,6 +1345,7 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
1235
1345
 
1236
1346
  this.lastChitStates = { ...this.lockedChitStates }; // reset our known chit states
1237
1347
  this.dirtyChitIds.clear();
1348
+ this.absorbedRootIds.clear();
1238
1349
  this.pendingNewChits.clear();
1239
1350
  // chits were deserialized back to locked state — mark them clean so future
1240
1351
  // modifications correctly trigger markDirty() → notifyChitDirty()
@@ -1247,7 +1358,7 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
1247
1358
  this.unresolvedPrompt = undefined;
1248
1359
  this.activeSubTurns = [];
1249
1360
  this.pass++;
1250
- this.invalidateSerializeCache();
1361
+ this._checkpoints = [];
1251
1362
  }
1252
1363
  }
1253
1364
 
@@ -1258,8 +1369,8 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
1258
1369
  type ChitLookup = { [id: string]: Chit };
1259
1370
  type ChitStateLookup = { [id: string]: string };
1260
1371
 
1261
- type SerializeCache = {
1262
- playerId: string;
1372
+ /** serialize()'s replay captured after `nextIndex` steps; see Turn._checkpoints */
1373
+ type SerializeCheckpoint = {
1263
1374
  nextIndex: number;
1264
1375
  chits: ChitStateLookup;
1265
1376
  subTurns?: { [turnId: string]: ClockDetails };
@@ -1273,6 +1384,13 @@ abstract class ClockStep {
1273
1384
  }
1274
1385
 
1275
1386
  class SubTurnsClockStep<P extends PlayerChit, R extends RootChit<P>> extends ClockStep {
1387
+ /** The turns the parent has absorbed, in that order: the order their changes landed in its state */
1388
+ public absorbed: Turn<any, P, R>[] = [];
1389
+
1390
+ get fullyAbsorbed() {
1391
+ return this.absorbed.length === this.turns.length;
1392
+ }
1393
+
1276
1394
  visibleTurns(playerId?: string) {
1277
1395
  if (this.turns.length === 1 || playerId === undefined) {
1278
1396
  return this.turns;
@@ -12,6 +12,14 @@ export type RngResponse = { readonly type: "rng"; value: number[] };
12
12
 
13
13
  export type Decision = PromptResponse | RngResponse | TurnState;
14
14
 
15
+ /**
16
+ * Where a match's random numbers come from. Called once per `rng()` / `takeRng(count)` draw with the
17
+ * number of values wanted; return that many numbers in [0, 1), or `undefined` to fall back to
18
+ * `Math.random`. Draws are persisted in the turn state as always, so a source only matters for a
19
+ * draw that has not been made yet (never on replay, reload or undo).
20
+ */
21
+ export type RngSource = (count: number) => number[] | undefined;
22
+
15
23
  export class TurnState {
16
24
  readonly type = "turn";
17
25
  id = "root";
@@ -30,9 +38,24 @@ export class TurnState {
30
38
  private parentTurnState: TurnState | undefined;
31
39
  private parentTurnIndex = 0;
32
40
 
41
+ /** Set on the root turn state (see `Match`); sub-turns inherit it. Not serialized. */
42
+ public rngSource?: RngSource;
43
+
44
+ private get rng(): RngSource | undefined {
45
+ return this.rngSource ?? this.parentTurnState?.rng;
46
+ }
47
+
48
+ private draw(count: number): number[] {
49
+ const scripted = this.rng?.(count);
50
+ if (scripted && scripted.length === count) {
51
+ return scripted;
52
+ }
53
+ return Array.from({ length: count }, () => Math.random());
54
+ }
55
+
33
56
  toJSON() {
34
57
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
35
- const { parentTurnIndex, parentTurnState, ...rest } = this;
58
+ const { parentTurnIndex, parentTurnState, rngSource, ...rest } = this;
36
59
  return rest;
37
60
  }
38
61
 
@@ -75,7 +98,7 @@ export class TurnState {
75
98
  }
76
99
  return (result as RngResponse).value[0];
77
100
  } else if (index === this.decisions.length) {
78
- const rng = Math.random();
101
+ const rng = this.draw(1)[0];
79
102
  this.decisions.push({
80
103
  type: "rng",
81
104
  value: [rng],
@@ -94,7 +117,7 @@ export class TurnState {
94
117
  }
95
118
  return (result as RngResponse).value;
96
119
  } else if (index === this.decisions.length) {
97
- const rngs = Array.from({ length: count }, () => Math.random());
120
+ const rngs = this.draw(count);
98
121
  this.decisions.push({
99
122
  type: "rng",
100
123
  value: rngs,
@@ -194,6 +194,16 @@ Narrow on `opt.kind` before using `chit`, `target` or `button`, then cast to you
194
194
  the best.
195
195
  - **Untagged options in the same prompt score 0.** Keep that in mind when choosing your scale.
196
196
 
197
+ ### Harness hooks
198
+
199
+ Harnesses (playouts, tutorials) can steer a bot without touching the game's rules:
200
+ `connectAiPlayer(match, id, { choose, hold })`. `choose(scored, ctx)` is consulted for every prompt,
201
+ the engine's Confirm included: return an index to force that option, `undefined` for the normal
202
+ choice, or `null` to leave the prompt unanswered for now. `hold(prompt)` keeps the bot from
203
+ answering while it returns true for the current prompt (look at the prompt to let some through, such
204
+ as the engine's Confirm). After either, call `handle.prompts.recheck()` when whatever held
205
+ the bot may have changed.
206
+
197
207
  ## Step 4 — Hidden information
198
208
 
199
209
  The default view is the live board: the bot *could* read other hands, deck order, and other
@@ -55,10 +55,22 @@ export type AiPlayerOptions = {
55
55
  */
56
56
  temperature?: number;
57
57
  /**
58
- * Override the choice: return the index into `scored` to take, or undefined for the normal
59
- * choice. For harnesses (forced moves in playouts, scripted openings), not for game rules.
58
+ * Override the choice: return the index into `scored` to take, undefined for the normal choice,
59
+ * or null to leave the prompt unanswered for now (call `recheck()` when that may have changed).
60
+ * Consulted for every prompt, the engine's Confirm included. For harnesses (forced moves in
61
+ * playouts, scripted openings, tutorials), not for game rules.
60
62
  */
61
- choose?: (scored: { option: AiOption; score: number }[], ctx: AiContext<any, any, any>) => number | undefined;
63
+ choose?: (
64
+ scored: { option: AiOption; score: number }[],
65
+ ctx: AiContext<any, any, any>,
66
+ ) => number | null | undefined;
67
+ /**
68
+ * While this returns true for the current prompt, the bot leaves it unanswered (call `recheck()`
69
+ * when that may have changed). For harnesses that hold a bot back, like a tutorial waiting for the
70
+ * step that scripts its next move. It sees the prompt so it can let some through (the engine's own
71
+ * Confirm, which ends a turn the script never mentions).
72
+ */
73
+ hold?: (prompt: PromptSerialization) => boolean;
62
74
  /** Called after every decision with each option's score and the chosen index (for logging and audits). */
63
75
  onDecision?: (decision: AiDecision) => void;
64
76
  /**
@@ -232,7 +244,13 @@ export class AiClientPrompts<P extends PlayerChit, R extends RootChit<P>, M = an
232
244
  }
233
245
  this.running = true;
234
246
  try {
235
- while (this.latest && this.latest.seq !== this.handledSeq && !this.disposed && this._enabled) {
247
+ while (
248
+ this.latest &&
249
+ this.latest.seq !== this.handledSeq &&
250
+ !this.disposed &&
251
+ this._enabled &&
252
+ !this.options.hold?.(this.latest.prompt)
253
+ ) {
236
254
  const current = this.latest;
237
255
  this.handledSeq = current.seq;
238
256
  try {
@@ -252,6 +270,22 @@ export class AiClientPrompts<P extends PlayerChit, R extends RootChit<P>, M = an
252
270
  }
253
271
  }
254
272
 
273
+ /** Seq of a prompt `choose` chose to leave unanswered */
274
+ private heldSeq = -1;
275
+
276
+ /**
277
+ * Looks at the current prompt again: answers it if `hold` no longer holds the bot and `choose` no
278
+ * longer leaves it unanswered. Does nothing to a prompt the bot already answered.
279
+ */
280
+ public recheck() {
281
+ if (this.disposed) return;
282
+ if (this.latest && this.heldSeq === this.latest.seq) {
283
+ this.heldSeq = -1;
284
+ this.handledSeq = -1;
285
+ }
286
+ void this.pump();
287
+ }
288
+
255
289
  private isCurrent(entry: QueuedPrompt) {
256
290
  return !this.disposed && this._enabled && this.latest?.seq === entry.seq;
257
291
  }
@@ -328,6 +362,11 @@ export class AiClientPrompts<P extends PlayerChit, R extends RootChit<P>, M = an
328
362
  }
329
363
 
330
364
  const chosen = this.choose(prompt, candidates);
365
+ if (!chosen) {
366
+ // The harness wants this prompt left alone for now (see `recheck`)
367
+ this.heldSeq = entry.seq;
368
+ return;
369
+ }
331
370
  const memoryBefore = this.memory;
332
371
  // Written before the answer is sent, so the save that follows the answer carries it
333
372
  this.setMemory(applyPlan(memoryBefore, chosen.plan));
@@ -429,17 +468,12 @@ export class AiClientPrompts<P extends PlayerChit, R extends RootChit<P>, M = an
429
468
  return button;
430
469
  }
431
470
 
432
- private choose(prompt: PromptSerialization, candidates: AiOption[]): Scored<M> {
471
+ private choose(prompt: PromptSerialization, candidates: AiOption[]): Scored<M> | null {
433
472
  const ai = this.game.ai;
434
473
  const rules: { [key: string]: AiRule<P, R, M> } = (ai?.rules as any) ?? {};
435
474
  const defaultRule = ai?.default as AiRule<P, R, M> | undefined;
436
475
  const ruleFor = (o: AiOption) => (o.key ? rules[o.key] : undefined) ?? defaultRule;
437
476
 
438
- if (!candidates.some((o) => ruleFor(o))) {
439
- candidates.forEach((o) => this.noteUntagged(o));
440
- return { option: this.chooseLegacy(prompt, candidates), score: 0 };
441
- }
442
-
443
477
  const root = this.view.root as R;
444
478
  const ctx: AiContext<P, R, M> = {
445
479
  view: root,
@@ -452,6 +486,19 @@ export class AiClientPrompts<P extends PlayerChit, R extends RootChit<P>, M = an
452
486
  params: this.options.params,
453
487
  };
454
488
 
489
+ if (!candidates.some((o) => ruleFor(o))) {
490
+ // No rule applies (an untagged pick, or the engine's own Confirm): the harness still decides
491
+ candidates.forEach((o) => this.noteUntagged(o));
492
+ const unscored: Scored<M>[] = candidates.map((option) => ({ option, score: 0 }));
493
+ const forced = this.options.choose?.(unscored, ctx);
494
+ if (forced === null) return null;
495
+ if (forced !== undefined && forced >= 0 && forced < unscored.length) {
496
+ this.options.onDecision?.({ playerId: this.playerId, prompt: ctx.prompt, scored: unscored, chosen: forced, ctx });
497
+ return unscored[forced];
498
+ }
499
+ return { option: this.chooseLegacy(prompt, candidates), score: 0 };
500
+ }
501
+
455
502
  const scored: Scored<M>[] = candidates.map((option) => {
456
503
  const rule = ruleFor(option);
457
504
  if (!rule) {
@@ -468,7 +515,9 @@ export class AiClientPrompts<P extends PlayerChit, R extends RootChit<P>, M = an
468
515
  });
469
516
 
470
517
  const scores = scored.map((s) => s.score);
471
- let index = this.options.choose?.(scored, ctx);
518
+ const forced = this.options.choose?.(scored, ctx);
519
+ if (forced === null) return null;
520
+ let index = forced;
472
521
  if (index === undefined || index < 0 || index >= scored.length) {
473
522
  const temperature = this.options.temperature ?? this.game.ai?.temperature;
474
523
  index =
@@ -85,6 +85,8 @@ export class AiPlayerView extends ConnectionObject {
85
85
 
86
86
  Object.values(this.chitLookup).forEach((chit) => {
87
87
  if (chit.id && !serialized[chit.id] && this.lastSerializedState[chit.id] !== undefined) {
88
+ // Back into its bag if it came from one; otherwise gone, as a visible fallback would keep it drawn
89
+ chit.forgetFallbackUnlessHidden();
88
90
  if (chit.parentFallback) {
89
91
  chit.beginDeserializing();
90
92
  chit.setParent(chit.parentFallback, chit.parentOutlet ?? "graveyard");