@myclaw163/clawclaw-cli 0.8.4 → 0.8.6

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 (330) hide show
  1. package/README.md +4 -3
  2. package/docs/configuration.md +44 -26
  3. package/docs/custom-modules/README.md +7 -10
  4. package/docs/custom-modules/behavior.md +10 -19
  5. package/docs/custom-modules/perception.md +1 -1
  6. package/docs/custom-modules/trigger.md +1 -1
  7. package/docs/runtime/README.md +4 -4
  8. package/docs/runtime/official-perception-modules.md +2 -2
  9. package/docs/runtime/owner-lifecycle-and-observability.md +1 -1
  10. package/package.json +15 -2
  11. package/scripts/enable_ccl_permissions.cjs +4 -2
  12. package/scripts/find-hide-spots.py +2 -2
  13. package/scripts/postinstall.mjs +1 -4
  14. package/scripts/sync-bundled-skill.mjs +12 -159
  15. package/skills/clawclaw/SKILL.md +25 -18
  16. package/skills/clawclaw/references/BEHAVIORS.md +15 -11
  17. package/skills/clawclaw/references/COMMANDS.md +45 -41
  18. package/skills/clawclaw/references/HUB.md +25 -38
  19. package/skills/clawclaw/references/TACTICS.md +1 -1
  20. package/src/commands/account.ts +58 -14
  21. package/src/commands/behavior.ts +116 -38
  22. package/src/commands/hub.ts +110 -153
  23. package/src/commands/load.ts +138 -33
  24. package/src/commands/perception.ts +55 -24
  25. package/src/commands/persona.ts +66 -20
  26. package/src/commands/skill.ts +12 -48
  27. package/src/commands/trigger.ts +68 -40
  28. package/src/lib/account-guidance.ts +54 -9
  29. package/src/lib/agent-workspace-client.ts +135 -0
  30. package/src/lib/agent-workspace-runtime.ts +154 -0
  31. package/src/lib/agent-workspace-skills.ts +177 -0
  32. package/src/lib/agent-workspace-sync.ts +852 -0
  33. package/src/lib/gameplay-config.ts +29 -15
  34. package/src/lib/hub-client.ts +252 -34
  35. package/src/lib/hub-reminder.ts +24 -11
  36. package/src/lib/init-command.ts +0 -6
  37. package/src/lib/load-context.ts +12 -6
  38. package/src/lib/persona.ts +141 -69
  39. package/src/lib/server-status.ts +78 -0
  40. package/src/lib/skill-host.ts +160 -0
  41. package/src/lib/user-data.ts +197 -4
  42. package/src/runtime/clawclaw/behavior-read-api.ts +1 -1
  43. package/src/{strategies/pathfind → runtime/clawclaw/navigation}/astar-path.ts +1 -1
  44. package/src/{strategies/pathfind → runtime/clawclaw/navigation}/escape-planner.ts +1 -1
  45. package/src/{strategies → runtime/clawclaw/navigation}/hide-spots.ts +2 -2
  46. package/src/{strategies → runtime/clawclaw/navigation}/off-route-points.ts +6 -3
  47. package/src/{strategies/pathfind → runtime/clawclaw/navigation}/walkable-grid.ts +1 -1
  48. package/src/runtime/clawclaw/owner.ts +63 -19
  49. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +8 -2
  50. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +2 -2
  51. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +1 -1
  52. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +4 -1
  53. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +11 -5
  54. package/src/runtime/clawclaw/plugins/perception/replay.ts +0 -2
  55. package/src/runtime/framework/modules/runtime-module-loader.ts +0 -54
  56. package/src/sdk/behavior-toolkit/escape.ts +2 -2
  57. package/personas//345/217/243/346/230/257/345/277/203/351/235/236.md +0 -50
  58. package/personas//345/277/240/345/277/203/350/200/201/344/273/206.md +0 -51
  59. package/personas//346/227/240/344/272/272/350/256/276.md +0 -1
  60. package/personas//350/264/253/345/230/264/346/215/237/345/217/213.md +0 -48
  61. package/personas//350/275/257/350/220/214/350/205/271/351/273/221.md +0 -51
  62. package/scripts/compare-perception-replays.test.ts +0 -188
  63. package/scripts/enable_ccl_permissions.test.mjs +0 -163
  64. package/scripts/enable_monitor.test.mjs +0 -201
  65. package/scripts/sync-bundled-skill.test.mjs +0 -152
  66. package/scripts/watch-perception-events.test.ts +0 -43
  67. package/src/behaviors/official-finite/do-task.ts +0 -211
  68. package/src/behaviors/official-finite/evade.ts +0 -78
  69. package/src/behaviors/official-finite/find-player.ts +0 -50
  70. package/src/behaviors/official-finite/follow-player.ts +0 -70
  71. package/src/behaviors/official-finite/go-to.ts +0 -69
  72. package/src/behaviors/official-finite/hide-temporarily.ts +0 -77
  73. package/src/behaviors/official-finite/hold-position.ts +0 -48
  74. package/src/behaviors/official-finite/hunt-player.ts +0 -47
  75. package/src/behaviors/official-finite/index.test.ts +0 -249
  76. package/src/behaviors/official-finite/index.ts +0 -44
  77. package/src/behaviors/official-finite/inspect-corpse.ts +0 -64
  78. package/src/behaviors/official-finite/patrol-area.ts +0 -80
  79. package/src/behaviors/official-finite/report-corpse.ts +0 -73
  80. package/src/behaviors/official-finite/seek-kill-opportunity.ts +0 -152
  81. package/src/behaviors/official-finite/shared.ts +0 -27
  82. package/src/channel/claude-channel-server.test.ts +0 -202
  83. package/src/commands/account.test.ts +0 -570
  84. package/src/commands/behavior.test.ts +0 -158
  85. package/src/commands/communication.test.ts +0 -282
  86. package/src/commands/competition.test.ts +0 -116
  87. package/src/commands/data.test.ts +0 -89
  88. package/src/commands/events-canonical-state.test.ts +0 -406
  89. package/src/commands/events.test.ts +0 -58
  90. package/src/commands/game/index.test.ts +0 -1251
  91. package/src/commands/game-map.test.ts +0 -69
  92. package/src/commands/hub.test.ts +0 -124
  93. package/src/commands/load.test.ts +0 -440
  94. package/src/commands/perception.test.ts +0 -75
  95. package/src/commands/setup/hermes.test.ts +0 -96
  96. package/src/commands/setup/openclaw.test.ts +0 -124
  97. package/src/commands/trigger.test.ts +0 -140
  98. package/src/commands/upgrade.test.ts +0 -82
  99. package/src/lib/account-guidance.test.ts +0 -36
  100. package/src/lib/auth.test.ts +0 -151
  101. package/src/lib/behavior-export.test.ts +0 -326
  102. package/src/lib/behavior-export.ts +0 -537
  103. package/src/lib/clawclaw-skill-spectate-guidance.test.ts +0 -21
  104. package/src/lib/custom-tts.test.ts +0 -387
  105. package/src/lib/diagnostics-config.test.ts +0 -59
  106. package/src/lib/game-client-tts.test.ts +0 -151
  107. package/src/lib/game-client.test.ts +0 -250
  108. package/src/lib/gameplay-config.test.ts +0 -301
  109. package/src/lib/host-config-patcher.test.ts +0 -130
  110. package/src/lib/http-transport.test.ts +0 -124
  111. package/src/lib/hub-client.test.ts +0 -57
  112. package/src/lib/hub-install.test.ts +0 -135
  113. package/src/lib/hub-install.ts +0 -185
  114. package/src/lib/hub-unzip.test.ts +0 -69
  115. package/src/lib/init-command.test.ts +0 -103
  116. package/src/lib/load-context.test.ts +0 -62
  117. package/src/lib/match-state.test.ts +0 -134
  118. package/src/lib/official-resource-sync.test.ts +0 -199
  119. package/src/lib/official-resource-sync.ts +0 -221
  120. package/src/lib/perception-config.test.ts +0 -143
  121. package/src/lib/perception-export.test.ts +0 -145
  122. package/src/lib/perception-export.ts +0 -178
  123. package/src/lib/persona.test.ts +0 -84
  124. package/src/lib/room.test.ts +0 -88
  125. package/src/lib/server-registry.test.ts +0 -64
  126. package/src/lib/service-status.test.ts +0 -81
  127. package/src/lib/skill-version.test.ts +0 -48
  128. package/src/lib/trigger-config.test.ts +0 -102
  129. package/src/lib/trigger-export.test.ts +0 -80
  130. package/src/lib/trigger-export.ts +0 -210
  131. package/src/lib/user-data.test.ts +0 -121
  132. package/src/lib/workspace-argv.test.ts +0 -49
  133. package/src/pipeline/canonical-event-presentation.test.ts +0 -257
  134. package/src/pipeline/event-format.test.ts +0 -879
  135. package/src/pipeline/event-hints.test.ts +0 -337
  136. package/src/pipeline/game-sync-event-normalization.test.ts +0 -419
  137. package/src/pipeline/player-projection.test.ts +0 -247
  138. package/src/runtime/auto-upgrade.test.ts +0 -66
  139. package/src/runtime/canonical-event-emitter.test.ts +0 -70
  140. package/src/runtime/canonical-monitor.test.ts +0 -577
  141. package/src/runtime/clawclaw/agent-event-policy.test.ts +0 -60
  142. package/src/runtime/clawclaw/behavior-decision.test.ts +0 -43
  143. package/src/runtime/clawclaw/behavior-input-fields.test.ts +0 -175
  144. package/src/runtime/clawclaw/behavior-input.test.ts +0 -173
  145. package/src/runtime/clawclaw/behavior-observation-memory.test.ts +0 -59
  146. package/src/runtime/clawclaw/behavior-read-api.test.ts +0 -123
  147. package/src/runtime/clawclaw/notifications.test.ts +0 -47
  148. package/src/runtime/clawclaw/owner-lock.test.ts +0 -221
  149. package/src/runtime/clawclaw/owner.test.ts +0 -203
  150. package/src/runtime/clawclaw/plugins/action/action-plugin.test.ts +0 -328
  151. package/src/runtime/clawclaw/plugins/assembly.test.ts +0 -200
  152. package/src/runtime/clawclaw/plugins/behavior/activation-manager.test.ts +0 -180
  153. package/src/runtime/clawclaw/plugins/behavior/behavior-action.test.ts +0 -43
  154. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.test.ts +0 -156
  155. package/src/runtime/clawclaw/plugins/behavior/behavior-module-loader.test.ts +0 -182
  156. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.test.ts +0 -1094
  157. package/src/runtime/clawclaw/plugins/behavior/behavior-source.test.ts +0 -174
  158. package/src/runtime/clawclaw/plugins/behavior/control-driver.test.ts +0 -195
  159. package/src/runtime/clawclaw/plugins/behavior/official-goal-behavior.ts +0 -757
  160. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.test.ts +0 -283
  161. package/src/runtime/clawclaw/plugins/behavior-input-source.test.ts +0 -80
  162. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.test.ts +0 -267
  163. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.test.ts +0 -226
  164. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.test.ts +0 -239
  165. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.test.ts +0 -407
  166. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-push.integration.test.ts +0 -397
  167. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.test.ts +0 -270
  168. package/src/runtime/clawclaw/plugins/mailbox/mailbox-agent-event-batch.test.ts +0 -166
  169. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.test.ts +0 -194
  170. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.test.ts +0 -87
  171. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.test.ts +0 -2012
  172. package/src/runtime/clawclaw/plugins/perception/module-runner.test.ts +0 -214
  173. package/src/runtime/clawclaw/plugins/perception/modules/co-movement-module.ts +0 -347
  174. package/src/runtime/clawclaw/plugins/perception/modules/corpse-visibility-module.test.ts +0 -92
  175. package/src/runtime/clawclaw/plugins/perception/modules/corpse-visibility-module.ts +0 -248
  176. package/src/runtime/clawclaw/plugins/perception/modules/follow-module.ts +0 -389
  177. package/src/runtime/clawclaw/plugins/perception/modules/index.ts +0 -8
  178. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.test.ts +0 -342
  179. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.ts +0 -475
  180. package/src/runtime/clawclaw/plugins/perception/modules/parallel-module-test-helpers.ts +0 -30
  181. package/src/runtime/clawclaw/plugins/perception/modules/relation-stability.test.ts +0 -304
  182. package/src/runtime/clawclaw/plugins/perception/modules/route-module.test.ts +0 -179
  183. package/src/runtime/clawclaw/plugins/perception/modules/route-module.ts +0 -364
  184. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.test.ts +0 -81
  185. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.ts +0 -200
  186. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.test.ts +0 -216
  187. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.ts +0 -284
  188. package/src/runtime/clawclaw/plugins/perception/modules/temporal-evidence.test.ts +0 -120
  189. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.test.ts +0 -105
  190. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.ts +0 -269
  191. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.test.ts +0 -865
  192. package/src/runtime/clawclaw/plugins/perception/perception-plugin.test.ts +0 -1878
  193. package/src/runtime/clawclaw/plugins/perception/perception-source.test.ts +0 -278
  194. package/src/runtime/clawclaw/plugins/perception/replay.test.ts +0 -77
  195. package/src/runtime/clawclaw/plugins/runtime-plugins.test.ts +0 -853
  196. package/src/runtime/clawclaw/plugins/source/game-transport.test.ts +0 -287
  197. package/src/runtime/clawclaw/plugins/source/player-change-tracker.test.ts +0 -321
  198. package/src/runtime/clawclaw/plugins/source/room-transport.test.ts +0 -307
  199. package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +0 -2646
  200. package/src/runtime/clawclaw/plugins/source/task-change-tracker.test.ts +0 -212
  201. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.test.ts +0 -548
  202. package/src/runtime/clawclaw/plugins/trigger/trigger-source.test.ts +0 -169
  203. package/src/runtime/clawclaw/runtime-data-export.test.ts +0 -249
  204. package/src/runtime/clawclaw-event-catalog.test.ts +0 -128
  205. package/src/runtime/framework/action-diagnostics.test.ts +0 -81
  206. package/src/runtime/framework/capability-registry.test.ts +0 -423
  207. package/src/runtime/framework/control-coordinator.test.ts +0 -675
  208. package/src/runtime/framework/events/event-delivery-service.test.ts +0 -84
  209. package/src/runtime/framework/events/event-ingress.test.ts +0 -203
  210. package/src/runtime/framework/events/mailbox-event-repositories.test.ts +0 -710
  211. package/src/runtime/framework/events/sqlite-event-repository.test.ts +0 -802
  212. package/src/runtime/framework/mailbox/coalescer.test.ts +0 -55
  213. package/src/runtime/framework/mailbox/identity.test.ts +0 -38
  214. package/src/runtime/framework/mailbox/mailbox-dispatcher.test.ts +0 -513
  215. package/src/runtime/framework/mailbox/notification-projector.test.ts +0 -77
  216. package/src/runtime/framework/modules/runtime-module-loader.test.ts +0 -435
  217. package/src/runtime/framework/participation-manager.test.ts +0 -108
  218. package/src/runtime/framework/plugins/runtime-input-journal.test.ts +0 -179
  219. package/src/runtime/framework/plugins/runtime-plugin-scheduler.test.ts +0 -2040
  220. package/src/runtime/framework/state/durable-agent-state-snapshot.test.ts +0 -144
  221. package/src/runtime/framework/state/history/sqlite-state-history-repository.test.ts +0 -157
  222. package/src/runtime/framework/state/history/state-history.test.ts +0 -251
  223. package/src/runtime/framework/state/state-core.test.ts +0 -197
  224. package/src/runtime/game-sync-protocol.test.ts +0 -123
  225. package/src/runtime/host-monitor-rate-gate.test.ts +0 -73
  226. package/src/runtime/mailbox-host-relay.test.ts +0 -293
  227. package/src/runtime/observability/observability.test.ts +0 -583
  228. package/src/runtime/owner-control.test.ts +0 -153
  229. package/src/runtime/parent-process-watch.test.ts +0 -27
  230. package/src/runtime/pending-event-handoff.test.ts +0 -29
  231. package/src/runtime/raw-ws-log.test.ts +0 -102
  232. package/src/runtime/runtime-logger.test.ts +0 -58
  233. package/src/runtime/runtime-persistence.test.ts +0 -26
  234. package/src/runtime/runtime.test.ts +0 -1770
  235. package/src/runtime/ws-client.test.ts +0 -562
  236. package/src/sdk/action.test.ts +0 -8
  237. package/src/sdk/behavior-plugin/index.test.ts +0 -74
  238. package/src/sdk/index.test.ts +0 -45
  239. package/src/sdk/module-input/index.test.ts +0 -49
  240. package/src/sdk/perception-plugin/index.test.ts +0 -22
  241. package/src/sdk/resource-metadata.test.ts +0 -40
  242. package/src/sdk/trigger-plugin/index.test.ts +0 -41
  243. package/src/short-command/classifier.test.ts +0 -107
  244. package/src/short-command/presenter.test.ts +0 -119
  245. package/src/short-command/runner.test.ts +0 -78
  246. package/src/short-command/sensitive-data-filter.test.ts +0 -56
  247. package/src/short-command/transport-response.test.ts +0 -39
  248. package/src/strategies/avoid-lone.ts +0 -32
  249. package/src/strategies/avoid-players.ts +0 -43
  250. package/src/strategies/corpse-patrol.ts +0 -50
  251. package/src/strategies/crab-sabotage.ts +0 -48
  252. package/src/strategies/custom-module.test.ts +0 -267
  253. package/src/strategies/find-player.ts +0 -49
  254. package/src/strategies/game-utils.test.ts +0 -305
  255. package/src/strategies/game-utils.ts +0 -927
  256. package/src/strategies/goals/anchor-linger.ts +0 -77
  257. package/src/strategies/goals/avoid-lone-top.ts +0 -189
  258. package/src/strategies/goals/avoid-players-top.test.ts +0 -95
  259. package/src/strategies/goals/avoid-players-top.ts +0 -122
  260. package/src/strategies/goals/conversation-goal.ts +0 -51
  261. package/src/strategies/goals/corpse-patrol-top.ts +0 -120
  262. package/src/strategies/goals/crab-octopus-reflexes.ts +0 -109
  263. package/src/strategies/goals/crab-sabotage-top.test.ts +0 -131
  264. package/src/strategies/goals/crab-sabotage-top.ts +0 -139
  265. package/src/strategies/goals/emergency-hunt-goal.ts +0 -40
  266. package/src/strategies/goals/find-player-top.ts +0 -136
  267. package/src/strategies/goals/flee-players-goal.ts +0 -55
  268. package/src/strategies/goals/follow-companion-goal.ts +0 -130
  269. package/src/strategies/goals/goal-manager.ts +0 -41
  270. package/src/strategies/goals/goal-root-strategy.ts +0 -49
  271. package/src/strategies/goals/goal.ts +0 -28
  272. package/src/strategies/goals/hide-top.ts +0 -240
  273. package/src/strategies/goals/keep-away-goal.ts +0 -243
  274. package/src/strategies/goals/kill-frenzy-top.ts +0 -90
  275. package/src/strategies/goals/kill-lone-top.test.ts +0 -96
  276. package/src/strategies/goals/kill-lone-top.ts +0 -166
  277. package/src/strategies/goals/kill-target-goal.ts +0 -69
  278. package/src/strategies/goals/kill-target-top.test.ts +0 -65
  279. package/src/strategies/goals/kill-target-top.ts +0 -121
  280. package/src/strategies/goals/leaf-goal.ts +0 -27
  281. package/src/strategies/goals/linger-corpse-goal.ts +0 -43
  282. package/src/strategies/goals/lone-kill-core.ts +0 -86
  283. package/src/strategies/goals/lone-kill-goal.ts +0 -24
  284. package/src/strategies/goals/lone-kill-task-top.test.ts +0 -84
  285. package/src/strategies/goals/lone-kill-task-top.ts +0 -133
  286. package/src/strategies/goals/move-room-goal.ts +0 -102
  287. package/src/strategies/goals/normal-shrimp-top.test.ts +0 -112
  288. package/src/strategies/goals/normal-shrimp-top.ts +0 -248
  289. package/src/strategies/goals/paradise-fish-top.test.ts +0 -203
  290. package/src/strategies/goals/paradise-fish-top.ts +0 -234
  291. package/src/strategies/goals/patrol-top.ts +0 -68
  292. package/src/strategies/goals/report-patrol-top.ts +0 -97
  293. package/src/strategies/goals/safe-task-goal.ts +0 -130
  294. package/src/strategies/goals/social-task-top.ts +0 -192
  295. package/src/strategies/goals/task-kill-report-top.ts +0 -187
  296. package/src/strategies/goals/task-only-top.test.ts +0 -88
  297. package/src/strategies/goals/task-only-top.ts +0 -64
  298. package/src/strategies/goals/task-or-patrol-goal.ts +0 -59
  299. package/src/strategies/goals/task-report-top.ts +0 -57
  300. package/src/strategies/goals/wander-task-goal.ts +0 -33
  301. package/src/strategies/goals/warrior-shrimp-top.test.ts +0 -138
  302. package/src/strategies/goals/warrior-shrimp-top.ts +0 -293
  303. package/src/strategies/greeting.ts +0 -60
  304. package/src/strategies/hide.ts +0 -51
  305. package/src/strategies/kill-frenzy.ts +0 -32
  306. package/src/strategies/kill-lone.ts +0 -52
  307. package/src/strategies/kill-target.ts +0 -48
  308. package/src/strategies/lone-kill-task.ts +0 -48
  309. package/src/strategies/meeting-gate.test.ts +0 -59
  310. package/src/strategies/meeting-gate.ts +0 -28
  311. package/src/strategies/move-room.ts +0 -46
  312. package/src/strategies/official-long-behavior.test.ts +0 -89
  313. package/src/strategies/paradise-fish.ts +0 -70
  314. package/src/strategies/pathfind/astar-path.test.ts +0 -198
  315. package/src/strategies/pathfind/escape-planner.test.ts +0 -223
  316. package/src/strategies/patrol.ts +0 -32
  317. package/src/strategies/player-targets.test.ts +0 -10
  318. package/src/strategies/player-targets.ts +0 -18
  319. package/src/strategies/report-patrol.ts +0 -32
  320. package/src/strategies/shrimp-memory.ts +0 -87
  321. package/src/strategies/social-task.ts +0 -67
  322. package/src/strategies/speech-module.ts +0 -123
  323. package/src/strategies/task-kill-report.ts +0 -49
  324. package/src/strategies/task-only.test.ts +0 -138
  325. package/src/strategies/task-only.ts +0 -34
  326. package/src/strategies/task-report.ts +0 -50
  327. package/src/strategies/types.ts +0 -116
  328. package/src/strategies/warrior-memory.ts +0 -54
  329. /package/src/{strategies/pathfind → runtime/clawclaw/navigation}/clawclaw-walkable.bin +0 -0
  330. /package/src/{strategies/pathfind → runtime/clawclaw/navigation}/distance-field.ts +0 -0
@@ -1,2040 +0,0 @@
1
- import { describe, expect, it, vi } from 'vitest';
2
- import type { CanonicalEvent, CommitEventResult } from '../events/types.js';
3
- import { MemoryStateHistoryRepository } from '../state/history/memory-state-history-repository.js';
4
- import type { RuntimeScope } from '../state/types.js';
5
- import type {
6
- RuntimeEpochPlugin,
7
- RuntimeInputBatch,
8
- } from './contracts.js';
9
- import { MemoryRuntimeInputJournal } from './runtime-input-journal.js';
10
- import { RuntimePluginScheduler, type RuntimeEpochWork } from './runtime-plugin-scheduler.js';
11
-
12
- const scope: RuntimeScope = {
13
- adapterId: 'test-game',
14
- accountId: 'account-1',
15
- sessionId: 'session-1',
16
- segmentId: 'segment-1',
17
- segmentSeq: 1,
18
- };
19
-
20
- interface Harness {
21
- scheduler: RuntimePluginScheduler;
22
- journal: MemoryRuntimeInputJournal;
23
- work(marker: number, overrides?: Partial<RuntimeInputBatch>): RuntimeEpochWork;
24
- events: CanonicalEvent[];
25
- eventListRequests: Array<{
26
- afterCommitSeq: number;
27
- maxCommitSeq: number;
28
- epochSeq?: number;
29
- maxEpochSeq?: number;
30
- }>;
31
- diagnostics: Array<{
32
- name: string;
33
- attributes: Record<string, unknown>;
34
- severity?: 'debug' | 'info' | 'warn' | 'error';
35
- }>;
36
- }
37
-
38
- function canonicalEvent(
39
- commitSeq: number,
40
- type: string,
41
- epochSeq = 1,
42
- payload: Record<string, unknown> = {},
43
- ): CanonicalEvent {
44
- return {
45
- commitSeq,
46
- epochSeq,
47
- eventId: `event-${commitSeq}`,
48
- sessionId: scope.sessionId,
49
- segmentId: scope.segmentId,
50
- type,
51
- producer: 'local_synth',
52
- deliveryClass: 'internal_only',
53
- occurredAt: '2026-07-22T00:00:00.000Z',
54
- receivedAt: '2026-07-22T00:00:00.000Z',
55
- payload,
56
- sourceId: 'test.plugin',
57
- replayed: false,
58
- };
59
- }
60
-
61
- function harness(
62
- plugins: RuntimeEpochPlugin[],
63
- options: {
64
- pluginTimeoutMs?: number;
65
- maxCatchUpEpochs?: number;
66
- diagnosticTimingWindowMs?: number;
67
- nowMs?: () => number;
68
- seedEvents?: CanonicalEvent[];
69
- journal?: MemoryRuntimeInputJournal;
70
- currentSegment?: () => { kind: string; identity?: string };
71
- } = {},
72
- ): Harness {
73
- const journal = options.journal ?? new MemoryRuntimeInputJournal();
74
- const history = new MemoryStateHistoryRepository();
75
- const events = [...(options.seedEvents ?? [])];
76
- const eventListRequests: Harness['eventListRequests'] = [];
77
- const diagnostics: Harness['diagnostics'] = [];
78
- history.openScope(scope);
79
- const scheduler = new RuntimePluginScheduler({
80
- plugins,
81
- inputJournal: journal,
82
- pluginStore: journal,
83
- stateHistory: history,
84
- commitInputEvents: async (work) => {
85
- const committed: CanonicalEvent[] = [];
86
- for (const [index, sourceEvent] of work.epoch.events.entries()) {
87
- const event = {
88
- ...canonicalEvent(events.length + 1, sourceEvent.type, work.epoch.epochSeq, sourceEvent.payload),
89
- eventId: `source:${work.epoch.epochSeq}:${index}`,
90
- producer: sourceEvent.producer ?? 'backend_push' as const,
91
- };
92
- events.push(event);
93
- committed.push(event);
94
- }
95
- return committed;
96
- },
97
- listEvents: (request) => {
98
- eventListRequests.push({
99
- afterCommitSeq: request.afterCommitSeq,
100
- maxCommitSeq: request.maxCommitSeq,
101
- ...(request.epochSeq === undefined ? {} : { epochSeq: request.epochSeq }),
102
- ...(request.maxEpochSeq === undefined ? {} : { maxEpochSeq: request.maxEpochSeq }),
103
- });
104
- return events.filter((event) => (
105
- event.commitSeq > request.afterCommitSeq
106
- && event.commitSeq <= request.maxCommitSeq
107
- && (request.epochSeq === undefined || event.epochSeq === request.epochSeq)
108
- && (
109
- request.maxEpochSeq === undefined
110
- || event.epochSeq === undefined
111
- || event.epochSeq <= request.maxEpochSeq
112
- )
113
- && (!request.types || request.types.includes(event.type))
114
- ));
115
- },
116
- publishEvent: async (pluginId, epoch, proposal, proposalIndex): Promise<CommitEventResult> => {
117
- const event = canonicalEvent(
118
- events.length + 1,
119
- proposal.type,
120
- epoch.epochSeq,
121
- proposal.payload,
122
- );
123
- event.eventId = `${pluginId}:${epoch.epochSeq}:${proposalIndex}`;
124
- event.producerPluginId = pluginId;
125
- event.producerOutputIndex = proposalIndex;
126
- events.push(event);
127
- return { inserted: true, event };
128
- },
129
- highWaterCommitSeq: () => events.at(-1)?.commitSeq ?? 0,
130
- onDiagnostic: (name, attributes, _scope, severity) => diagnostics.push({
131
- name,
132
- attributes,
133
- ...(severity === undefined ? {} : { severity }),
134
- }),
135
- pluginTimeoutMs: options.pluginTimeoutMs,
136
- maxCatchUpEpochs: options.maxCatchUpEpochs,
137
- diagnosticTimingWindowMs: options.diagnosticTimingWindowMs,
138
- nowMs: options.nowMs,
139
- currentSegment: options.currentSegment,
140
- });
141
-
142
- return {
143
- scheduler,
144
- journal,
145
- events,
146
- eventListRequests,
147
- diagnostics,
148
- work(marker: number, overrides: Partial<RuntimeInputBatch> = {}): RuntimeEpochWork {
149
- const batch: RuntimeInputBatch = {
150
- scope,
151
- sourceId: 'test.source',
152
- connectionId: 'connection-1',
153
- sourceKey: `message-${marker}`,
154
- sourceSeq: marker,
155
- domainTick: marker,
156
- state: { marker },
157
- events: [],
158
- completeness: 'complete',
159
- receivedAt: new Date(marker * 100).toISOString(),
160
- ...overrides,
161
- };
162
- const epoch = journal.accept(batch).epoch;
163
- const previousState = history.latestStateFrame(scope)?.state ?? null;
164
- const frame = history.appendStateFrame({
165
- epochSeq: epoch.epochSeq,
166
- scope,
167
- sourceId: batch.sourceId,
168
- connectionId: batch.connectionId,
169
- sourceKey: batch.sourceKey,
170
- sourceSeq: batch.sourceSeq,
171
- backendTick: marker,
172
- receivedAtMs: marker * 100,
173
- state: batch.state,
174
- }).frame;
175
- return {
176
- epoch,
177
- frame,
178
- currentState: {
179
- state: batch.state,
180
- stateStatus: {
181
- status: 'fresh',
182
- semantics: 'latest_received',
183
- source: 'owner_memory',
184
- scope,
185
- connectionId: batch.connectionId,
186
- connectionState: 'connected',
187
- receivedAtMs: marker * 100,
188
- ageMs: 0,
189
- backendTick: marker,
190
- reason: null,
191
- },
192
- },
193
- previousState,
194
- epochEvents: [],
195
- };
196
- },
197
- };
198
- }
199
-
200
- describe('RuntimePluginScheduler', () => {
201
- it('uses after as a completion barrier even when the upstream plugin returns no Event', async () => {
202
- const calls: string[] = [];
203
- const plugins: RuntimeEpochPlugin[] = [{
204
- kind: 'epoch',
205
- id: 'a',
206
- version: '1',
207
- produces: { states: ['a.state'] },
208
- update: () => {
209
- calls.push('a');
210
- return {
211
- outcome: 'processed',
212
- states: [{ topic: 'a.state', value: { ready: true } }],
213
- };
214
- },
215
- }, {
216
- kind: 'epoch',
217
- id: 'b',
218
- version: '1',
219
- after: ['a'],
220
- consumes: { states: ['a.state'] },
221
- update: (input) => {
222
- calls.push('b');
223
- expect(input.upstreamStates).toEqual({ 'a.state': { ready: true } });
224
- expect(input.epochEvents).toEqual([]);
225
- return { outcome: 'noop', reason: 'zero_event_is_complete' };
226
- },
227
- }];
228
- const test = harness(plugins);
229
-
230
- const result = await test.scheduler.enqueue(test.work(1));
231
-
232
- expect(calls).toEqual(['a', 'b']);
233
- expect(result.outcomes.map((outcome) => [outcome.pluginId, outcome.outcome])).toEqual([
234
- ['a', 'processed'],
235
- ['b', 'noop'],
236
- ]);
237
- expect(test.journal.states(1)).toMatchObject([
238
- { pluginId: 'a', topic: 'a.state', value: { ready: true } },
239
- ]);
240
- expect(result.durationMs).toBeGreaterThanOrEqual(0);
241
- expect(test.journal.pluginRecords(1)).toEqual(expect.arrayContaining([
242
- expect.objectContaining({ pluginId: 'a', durationMs: expect.any(Number) }),
243
- expect.objectContaining({ pluginId: 'b', durationMs: expect.any(Number) }),
244
- ]));
245
- expect(test.diagnostics.some((entry) => [
246
- 'runtime.epoch.closed',
247
- 'runtime.epoch.queued',
248
- 'runtime.epoch.input_events_committed',
249
- 'runtime.plugin.invocation_started',
250
- 'runtime.plugin.invocation_completed',
251
- 'runtime.plugin.event_cursor',
252
- ].includes(entry.name))).toBe(false);
253
- await test.scheduler.close();
254
- expect(test.diagnostics.filter((entry) => entry.name === 'runtime.plugin.timing_window'))
255
- .toEqual(expect.arrayContaining([
256
- expect.objectContaining({
257
- attributes: expect.objectContaining({ plugin_id: 'a', invocation_count: 1 }),
258
- }),
259
- expect.objectContaining({
260
- attributes: expect.objectContaining({ plugin_id: 'b', invocation_count: 1 }),
261
- }),
262
- ]));
263
- });
264
-
265
- it('persists plugin State before advancing completed-through progress', async () => {
266
- const order: string[] = [];
267
- class OrderedJournal extends MemoryRuntimeInputJournal {
268
- override saveStates(records: Parameters<MemoryRuntimeInputJournal['saveStates']>[0]): void {
269
- order.push('states');
270
- super.saveStates(records);
271
- }
272
-
273
- override savePluginProgress(
274
- progress: Parameters<MemoryRuntimeInputJournal['savePluginProgress']>[0],
275
- progressScope: Parameters<MemoryRuntimeInputJournal['savePluginProgress']>[1],
276
- ): void {
277
- order.push('progress');
278
- super.savePluginProgress(progress, progressScope);
279
- }
280
- }
281
- const journal = new OrderedJournal();
282
- const test = harness([{
283
- kind: 'epoch',
284
- id: 'stateful',
285
- version: '1',
286
- produces: { states: ['stateful.output'] },
287
- update: () => ({
288
- outcome: 'processed',
289
- states: [{ topic: 'stateful.output', value: { ready: true } }],
290
- }),
291
- }], { journal });
292
-
293
- await test.scheduler.enqueue(test.work(1));
294
-
295
- expect(order).toEqual(['states', 'progress']);
296
- await test.scheduler.close();
297
- });
298
-
299
- it('runs plugins in the same dependency layer concurrently', async () => {
300
- let release!: () => void;
301
- const gate = new Promise<void>((resolve) => { release = resolve; });
302
- const started: string[] = [];
303
- const plugin = (id: string): RuntimeEpochPlugin => ({
304
- kind: 'epoch',
305
- id,
306
- version: '1',
307
- async update() {
308
- started.push(id);
309
- await gate;
310
- return { outcome: 'noop' };
311
- },
312
- });
313
- const test = harness([plugin('a'), plugin('b')]);
314
- const completion = test.scheduler.enqueue(test.work(1));
315
-
316
- await vi.waitFor(() => expect(started.sort()).toEqual(['a', 'b']));
317
- release();
318
- await completion;
319
- await test.scheduler.close();
320
- });
321
-
322
- it('uses a separate recovery deadline without relaxing the live update deadline', async () => {
323
- const recovered = vi.fn(async () => {
324
- await new Promise((resolve) => setTimeout(resolve, 30));
325
- });
326
- const test = harness([{
327
- kind: 'epoch',
328
- id: 'slow-recovery',
329
- version: '1',
330
- timeoutMs: 5,
331
- recoveryTimeoutMs: 100,
332
- recover: recovered,
333
- async update() {
334
- await new Promise((resolve) => setTimeout(resolve, 30));
335
- return { outcome: 'noop' };
336
- },
337
- }]);
338
-
339
- await expect(test.scheduler.activateScope(scope)).resolves.toBeUndefined();
340
- expect(recovered).toHaveBeenCalledOnce();
341
- expect(test.scheduler.descriptors()).toMatchObject([{
342
- id: 'slow-recovery',
343
- timeoutMs: 5,
344
- recoveryTimeoutMs: 100,
345
- }]);
346
-
347
- const result = await test.scheduler.enqueue(test.work(1));
348
- expect(result.outcomes).toMatchObject([{
349
- pluginId: 'slow-recovery',
350
- outcome: 'failed',
351
- }]);
352
- await test.scheduler.close();
353
- });
354
-
355
- it('unlocks a dependent plugin as soon as its own producer completes', async () => {
356
- let releaseUnrelated!: () => void;
357
- const unrelatedGate = new Promise<void>((resolve) => { releaseUnrelated = resolve; });
358
- const dependentRan = vi.fn();
359
- const test = harness([{
360
- kind: 'epoch',
361
- id: 'a',
362
- version: '1',
363
- produces: { states: ['a.state'], events: ['a.event'] },
364
- update: () => ({
365
- outcome: 'processed',
366
- states: [{ topic: 'a.state', value: { ready: true } }],
367
- events: [{ type: 'a.event', dedupeKey: 'a:1', payload: { ready: true } }],
368
- }),
369
- }, {
370
- kind: 'epoch',
371
- id: 'b',
372
- version: '1',
373
- after: ['a'],
374
- consumes: { states: ['a.state'], events: ['a.event'] },
375
- update: (input) => {
376
- expect(input.upstreamStates).toEqual({ 'a.state': { ready: true } });
377
- expect(input.epochEvents).toMatchObject([{
378
- epochSeq: 1,
379
- producerPluginId: 'a',
380
- producerOutputIndex: 0,
381
- }]);
382
- dependentRan();
383
- return { outcome: 'noop' };
384
- },
385
- }, {
386
- kind: 'epoch',
387
- id: 'unrelated',
388
- version: '1',
389
- async update() {
390
- await unrelatedGate;
391
- return { outcome: 'noop' };
392
- },
393
- }]);
394
-
395
- const completion = test.scheduler.enqueue(test.work(1));
396
- await vi.waitFor(() => expect(dependentRan).toHaveBeenCalledOnce());
397
- expect(test.journal.pluginProgress('unrelated', scope).completedThroughEpochSeq).toBe(0);
398
- expect(test.journal.states(1)).toMatchObject([{
399
- epochSeq: 1,
400
- pluginId: 'a',
401
- topic: 'a.state',
402
- }]);
403
- releaseUnrelated();
404
- await completion;
405
- await test.scheduler.close();
406
- });
407
-
408
- it('caps plugin history reads at the invocation epoch', async () => {
409
- let releaseFirst!: () => void;
410
- const firstGate = new Promise<void>((resolve) => { releaseFirst = resolve; });
411
- const seen: Array<number | undefined> = [];
412
- const test = harness([{
413
- kind: 'epoch',
414
- id: 'bounded-history',
415
- version: '1',
416
- async update(input, context) {
417
- if (input.epoch.epochSeq === 1) await firstGate;
418
- seen.push(context.stateHistory.latestStateFrame(scope)?.epochSeq);
419
- return { outcome: 'noop' };
420
- },
421
- }]);
422
-
423
- const first = test.scheduler.enqueue(test.work(1));
424
- const secondWork = test.work(2);
425
- releaseFirst();
426
- const second = test.scheduler.enqueue(secondWork);
427
- await Promise.all([first, second]);
428
-
429
- expect(seen).toEqual([1, 2]);
430
- await test.scheduler.close();
431
- });
432
-
433
- it('reports lag only when the bounded pending view crosses a threshold or recovers', async () => {
434
- let release!: () => void;
435
- const gate = new Promise<void>((resolve) => { release = resolve; });
436
- const started: number[] = [];
437
- const test = harness([{
438
- kind: 'epoch',
439
- id: 'a',
440
- version: '1',
441
- async update(input) {
442
- started.push(input.epoch.epochSeq);
443
- if (input.epoch.epochSeq === 1) await gate;
444
- return { outcome: 'noop' };
445
- },
446
- }, {
447
- kind: 'epoch',
448
- id: 'b',
449
- version: '1',
450
- after: ['a'],
451
- update: () => ({ outcome: 'noop' }),
452
- }]);
453
- const completions = [test.scheduler.enqueue(test.work(1))];
454
- await vi.waitFor(() => expect(started).toEqual([1]));
455
- completions.push(test.scheduler.enqueue(test.work(2)));
456
- completions.push(test.scheduler.enqueue(test.work(3)));
457
-
458
- expect(test.diagnostics.filter((entry) => entry.name === 'runtime.view.lag_degraded').at(-1)?.attributes)
459
- .toMatchObject({
460
- previous_band: 'healthy',
461
- current_band: 'degraded',
462
- latest_epoch_seq: 3,
463
- max_lag_epoch_count: 3,
464
- plugin_progress: [
465
- {
466
- plugin_id: 'a',
467
- completed_through_epoch_seq: 0,
468
- ready_through_epoch_seq: 3,
469
- lag_epoch_count: 3,
470
- },
471
- {
472
- plugin_id: 'b',
473
- completed_through_epoch_seq: 0,
474
- ready_through_epoch_seq: 0,
475
- lag_epoch_count: 3,
476
- },
477
- ],
478
- });
479
-
480
- release();
481
- await Promise.all(completions);
482
- expect(test.diagnostics.filter((entry) => entry.name === 'runtime.view.lag_recovered').at(-1)?.attributes)
483
- .toMatchObject({
484
- previous_band: 'degraded',
485
- current_band: 'healthy',
486
- latest_epoch_seq: 3,
487
- max_lag_epoch_count: 2,
488
- plugin_progress: [],
489
- });
490
- expect(test.diagnostics.some((entry) => entry.name === 'runtime.plugin.lag')).toBe(false);
491
- await test.scheduler.close();
492
- });
493
-
494
- it('caps critical lag diagnostics at ten pending epochs', async () => {
495
- let release!: () => void;
496
- const gate = new Promise<void>((resolve) => { release = resolve; });
497
- const started: number[] = [];
498
- const test = harness([{
499
- kind: 'epoch',
500
- id: 'slow',
501
- version: '1',
502
- async update(input) {
503
- started.push(input.epoch.epochSeq);
504
- if (input.epoch.epochSeq === 1) await gate;
505
- return { outcome: 'noop' };
506
- },
507
- }]);
508
- const completions = [test.scheduler.enqueue(test.work(1))];
509
- await vi.waitFor(() => expect(started).toEqual([1]));
510
- for (let marker = 2; marker <= 12; marker += 1) {
511
- completions.push(test.scheduler.enqueue(test.work(marker)));
512
- }
513
-
514
- expect(test.diagnostics.filter((entry) => entry.name === 'runtime.view.lag_critical').at(-1))
515
- .toMatchObject({
516
- severity: 'warn',
517
- attributes: {
518
- current_band: 'critical',
519
- max_lag_epoch_count: 10,
520
- lag_count_capped: true,
521
- plugin_progress: [{
522
- plugin_id: 'slow',
523
- lag_epoch_count: 10,
524
- lag_count_capped: true,
525
- }],
526
- },
527
- });
528
-
529
- release();
530
- await Promise.all(completions);
531
- await test.scheduler.close();
532
- });
533
-
534
- it('keeps exact plugin durations in the journal and emits only timing windows plus slow samples', async () => {
535
- let nowMs = 0;
536
- let durationMs = 10;
537
- const test = harness([{
538
- kind: 'epoch',
539
- id: 'ordinary',
540
- version: '1',
541
- update() {
542
- nowMs += durationMs;
543
- return { outcome: 'noop', reason: 'timed' };
544
- },
545
- }], {
546
- nowMs: () => nowMs,
547
- diagnosticTimingWindowMs: 10_000,
548
- });
549
-
550
- await test.scheduler.enqueue(test.work(1));
551
- expect(test.journal.pluginRecords(1)).toMatchObject([{ durationMs: 10 }]);
552
- expect(test.diagnostics.some((entry) => entry.name === 'runtime.plugin.timing_window'))
553
- .toBe(false);
554
-
555
- nowMs = 10_010;
556
- durationMs = 20;
557
- await test.scheduler.enqueue(test.work(2));
558
- expect(test.journal.pluginRecords(2)).toMatchObject([{ durationMs: 20 }]);
559
- expect(test.diagnostics).toContainEqual(expect.objectContaining({
560
- name: 'runtime.plugin.timing_window',
561
- attributes: expect.objectContaining({
562
- plugin_id: 'ordinary',
563
- invocation_count: 1,
564
- duration_avg_ms: 10,
565
- duration_p95_ms: 10,
566
- duration_max_ms: 10,
567
- }),
568
- }));
569
- expect(test.diagnostics.some((entry) => entry.name === 'runtime.plugin.invocation_completed'))
570
- .toBe(false);
571
-
572
- await test.scheduler.close();
573
- expect(test.diagnostics.filter((entry) => entry.name === 'runtime.plugin.timing_window'))
574
- .toHaveLength(2);
575
- });
576
-
577
- it('reports 250ms ordinary plugins and 1000ms Behavior plugins as slow', async () => {
578
- let ordinaryNow = 0;
579
- const ordinary = harness([{
580
- kind: 'epoch',
581
- id: 'ordinary',
582
- version: '1',
583
- update() {
584
- ordinaryNow += 250;
585
- return { outcome: 'noop' };
586
- },
587
- }], { nowMs: () => ordinaryNow });
588
- await ordinary.scheduler.enqueue(ordinary.work(1));
589
- expect(ordinary.diagnostics).toContainEqual(expect.objectContaining({
590
- name: 'runtime.plugin.slow',
591
- severity: 'warn',
592
- attributes: expect.objectContaining({
593
- plugin_id: 'ordinary',
594
- duration_ms: 250,
595
- threshold_ms: 250,
596
- }),
597
- }));
598
- expect(ordinary.diagnostics.some((entry) => entry.name === 'runtime.epoch.slow'))
599
- .toBe(false);
600
- await ordinary.scheduler.close();
601
-
602
- let behaviorNow = 0;
603
- const behavior = harness([{
604
- kind: 'epoch',
605
- id: 'clawclaw.behavior',
606
- version: '1',
607
- update() {
608
- behaviorNow += 1_000;
609
- return { outcome: 'noop' };
610
- },
611
- }], { nowMs: () => behaviorNow });
612
- await behavior.scheduler.enqueue(behavior.work(1));
613
- expect(behavior.diagnostics).toEqual(expect.arrayContaining([
614
- expect.objectContaining({
615
- name: 'runtime.plugin.slow',
616
- attributes: expect.objectContaining({
617
- plugin_id: 'clawclaw.behavior',
618
- duration_ms: 1_000,
619
- threshold_ms: 1_000,
620
- }),
621
- }),
622
- expect.objectContaining({
623
- name: 'runtime.epoch.slow',
624
- attributes: expect.objectContaining({ duration_ms: 1_000, threshold_ms: 1_000 }),
625
- }),
626
- ]));
627
- await behavior.scheduler.close();
628
- });
629
-
630
- it('bounds every-epoch catch-up and explicitly coalesces to latest', async () => {
631
- let release!: () => void;
632
- const gate = new Promise<void>((resolve) => { release = resolve; });
633
- const calls: number[] = [];
634
- const plugin: RuntimeEpochPlugin = {
635
- kind: 'epoch',
636
- id: 'slow',
637
- version: '1',
638
- catchUp: 'every_epoch',
639
- async update(input) {
640
- calls.push(input.epoch.epochSeq);
641
- if (input.epoch.epochSeq === 1) await gate;
642
- return { outcome: 'noop' };
643
- },
644
- };
645
- const test = harness([plugin], { maxCatchUpEpochs: 5 });
646
- const completions = [test.scheduler.enqueue(test.work(1))];
647
- await vi.waitFor(() => expect(calls).toEqual([1]));
648
- for (let marker = 2; marker <= 10; marker += 1) {
649
- completions.push(test.scheduler.enqueue(test.work(marker)));
650
- }
651
- release();
652
- const results = await Promise.all(completions);
653
-
654
- expect(calls).toEqual([1, 2, 3, 4, 5, 10]);
655
- expect(results.slice(5, 9).every((result) => (
656
- result.outcomes.every((outcome) => outcome.outcome === 'coalesced')
657
- ))).toBe(true);
658
- expect(test.journal.pluginProgress('slow', scope)).toMatchObject({
659
- completedThroughEpochSeq: 10,
660
- eventCursor: 0,
661
- });
662
- expect(test.diagnostics).toContainEqual(expect.objectContaining({
663
- name: 'runtime.plugin.invocations_coalesced',
664
- attributes: expect.objectContaining({
665
- skipped_from_epoch_seq: 6,
666
- skipped_through_epoch_seq: 9,
667
- coalesced_epoch_count: 4,
668
- }),
669
- }));
670
- expect(test.diagnostics.some((entry) => (
671
- entry.name === 'runtime.plugin.catchup_started'
672
- || entry.name === 'runtime.plugin.catchup_completed'
673
- ))).toBe(false);
674
- await test.scheduler.close();
675
- });
676
-
677
- it('processes a non-coalescible boundary before newer queued epochs', async () => {
678
- let release!: () => void;
679
- const gate = new Promise<void>((resolve) => { release = resolve; });
680
- const calls: number[] = [];
681
- const test = harness([{
682
- kind: 'epoch',
683
- id: 'boundary-aware',
684
- version: '1',
685
- catchUp: 'every_epoch',
686
- async update(input) {
687
- calls.push(input.epoch.epochSeq);
688
- if (input.epoch.epochSeq === 1) await gate;
689
- return { outcome: 'noop' };
690
- },
691
- }], { maxCatchUpEpochs: 1 });
692
-
693
- const completions = [test.scheduler.enqueue(test.work(1))];
694
- await vi.waitFor(() => expect(calls).toEqual([1]));
695
- completions.push(test.scheduler.enqueue(test.work(2)));
696
- completions.push(test.scheduler.enqueue(test.work(3, { coalescing: 'forbidden' })));
697
- completions.push(test.scheduler.enqueue(test.work(4)));
698
- release();
699
- const results = await Promise.all(completions);
700
-
701
- expect(calls).toEqual([1, 3, 4]);
702
- expect(results[1].outcomes).toEqual([
703
- expect.objectContaining({ outcome: 'coalesced', reason: 'required_epoch_boundary' }),
704
- ]);
705
- expect(results[2].outcomes).toEqual([
706
- expect.objectContaining({ outcome: 'noop' }),
707
- ]);
708
- await test.scheduler.close();
709
- });
710
-
711
- it('does not cancel an active non-coalescible latest-only invocation', async () => {
712
- let release!: () => void;
713
- const gate = new Promise<void>((resolve) => { release = resolve; });
714
- const calls: number[] = [];
715
- const test = harness([{
716
- kind: 'epoch',
717
- id: 'latest-boundary-aware',
718
- version: '1',
719
- catchUp: 'latest_only',
720
- async update(input) {
721
- calls.push(input.epoch.epochSeq);
722
- if (input.epoch.epochSeq === 1) await gate;
723
- return { outcome: 'noop' };
724
- },
725
- }]);
726
-
727
- const first = test.scheduler.enqueue(test.work(1, { coalescing: 'forbidden' }));
728
- await vi.waitFor(() => expect(calls).toEqual([1]));
729
- const second = test.scheduler.enqueue(test.work(2));
730
- await new Promise((resolve) => setTimeout(resolve, 0));
731
- expect(calls).toEqual([1]);
732
- release();
733
-
734
- const [firstResult] = await Promise.all([first, second]);
735
- expect(firstResult.outcomes).toEqual([expect.objectContaining({ outcome: 'noop' })]);
736
- expect(calls).toEqual([1, 2]);
737
- await test.scheduler.close();
738
- });
739
-
740
- it('drops a buffered latest-only proposal before ordered commit can perform side effects', async () => {
741
- let releaseBoundary!: () => void;
742
- const boundaryGate = new Promise<void>((resolve) => { releaseBoundary = resolve; });
743
- const updates: number[] = [];
744
- const commits: number[] = [];
745
- const test = harness([{
746
- kind: 'epoch',
747
- id: 'latest-ordered-commit',
748
- version: '1',
749
- catchUp: 'latest_only',
750
- maxInFlight: 3,
751
- produces: { states: ['latest-ordered.state'] },
752
- async update(input) {
753
- updates.push(input.epoch.epochSeq);
754
- if (input.epoch.epochSeq === 1) await boundaryGate;
755
- return {
756
- outcome: 'processed' as const,
757
- proposal: { value: input.epoch.epochSeq },
758
- };
759
- },
760
- commit(input, proposal) {
761
- commits.push(input.epoch.epochSeq);
762
- return {
763
- outcome: 'processed' as const,
764
- states: [{
765
- topic: 'latest-ordered.state',
766
- value: (proposal.proposal as { value: number }).value,
767
- }],
768
- };
769
- },
770
- }]);
771
-
772
- const first = test.scheduler.enqueue(test.work(1, { coalescing: 'forbidden' }));
773
- await vi.waitFor(() => expect(updates).toEqual([1]));
774
- const second = test.scheduler.enqueue(test.work(2));
775
- await vi.waitFor(() => expect(updates).toEqual([1, 2]));
776
- const third = test.scheduler.enqueue(test.work(3));
777
- await vi.waitFor(() => expect(updates).toEqual([1, 2, 3]));
778
-
779
- releaseBoundary();
780
- const results = await Promise.all([first, second, third]);
781
-
782
- expect(commits).toEqual([1, 3]);
783
- expect(results[1].outcomes).toMatchObject([{
784
- pluginId: 'latest-ordered-commit',
785
- outcome: 'coalesced',
786
- reason: 'newer_epoch_available_before_commit',
787
- }]);
788
- expect(test.journal.states(2)).toEqual([]);
789
- expect(test.diagnostics).toContainEqual(expect.objectContaining({
790
- name: 'runtime.plugin.stale_output_rejected',
791
- attributes: expect.objectContaining({
792
- epoch_seq: 2,
793
- newer_epoch_seq: 3,
794
- reason: 'newer_epoch_available_before_commit',
795
- }),
796
- }));
797
- await test.scheduler.close();
798
- });
799
-
800
- it('cancels an in-flight latest-only invocation when a newer epoch arrives', async () => {
801
- let release!: () => void;
802
- const gate = new Promise<void>((resolve) => { release = resolve; });
803
- const calls: number[] = [];
804
- const test = harness([{
805
- kind: 'epoch',
806
- id: 'latest',
807
- version: '1',
808
- catchUp: 'latest_only',
809
- produces: { states: ['latest.state'] },
810
- async update(input) {
811
- calls.push(input.epoch.epochSeq);
812
- if (input.epoch.epochSeq === 1) await gate;
813
- return {
814
- outcome: 'processed',
815
- states: [{ topic: 'latest.state', value: input.epoch.epochSeq }],
816
- };
817
- },
818
- }]);
819
-
820
- const first = test.scheduler.enqueue(test.work(1));
821
- await vi.waitFor(() => expect(calls).toEqual([1]));
822
- const second = test.scheduler.enqueue(test.work(2));
823
-
824
- expect((await first).outcomes).toMatchObject([{
825
- pluginId: 'latest',
826
- outcome: 'coalesced',
827
- reason: 'newer_epoch_available',
828
- }]);
829
- let secondSettled = false;
830
- void second.then(() => { secondSettled = true; });
831
- await new Promise((resolve) => setTimeout(resolve, 0));
832
- expect(secondSettled).toBe(false);
833
- expect(calls).toEqual([1]);
834
-
835
- release();
836
- expect((await second).outcomes).toMatchObject([{
837
- pluginId: 'latest',
838
- outcome: 'processed',
839
- }]);
840
- expect(test.journal.states(1)).toEqual([]);
841
- expect(test.journal.states(2)).toMatchObject([{ topic: 'latest.state', value: 2 }]);
842
- expect(test.diagnostics).toEqual(expect.arrayContaining([
843
- expect.objectContaining({
844
- name: 'runtime.plugin.invocation_cancelled',
845
- attributes: expect.objectContaining({ reason: 'newer_epoch_available' }),
846
- }),
847
- ]));
848
- await vi.waitFor(() => expect(test.diagnostics).toEqual(expect.arrayContaining([
849
- expect.objectContaining({
850
- name: 'runtime.plugin.stale_output_rejected',
851
- attributes: expect.objectContaining({ reason: 'newer_epoch_available' }),
852
- }),
853
- ])));
854
- await test.scheduler.close();
855
- });
856
-
857
- it('supports wildcard State and Event subscriptions without making them scheduling gates', async () => {
858
- const seen: Array<Record<string, unknown>> = [];
859
- const test = harness([{
860
- kind: 'epoch',
861
- id: 'producer',
862
- version: '1',
863
- produces: { states: ['producer.state'] },
864
- update: () => ({
865
- outcome: 'processed',
866
- states: [{ topic: 'producer.state', value: { ready: true } }],
867
- }),
868
- }, {
869
- kind: 'epoch',
870
- id: 'consumer',
871
- version: '1',
872
- after: ['producer'],
873
- consumes: { states: ['*'], events: ['*'] },
874
- update: (input) => {
875
- seen.push({
876
- upstreamStates: input.upstreamStates,
877
- pendingTypes: input.pendingEvents.map((event) => event.type),
878
- });
879
- return { outcome: 'noop' };
880
- },
881
- }], { seedEvents: [canonicalEvent(1, 'signal')] });
882
-
883
- await test.scheduler.enqueue(test.work(1));
884
-
885
- expect(seen).toEqual([{
886
- upstreamStates: { 'producer.state': { ready: true } },
887
- pendingTypes: ['signal'],
888
- }]);
889
- await test.scheduler.close();
890
- });
891
-
892
- it('queries exact-epoch Events for epoch input and accounting without narrowing pending Events', async () => {
893
- const legacy = canonicalEvent(1, 'signal');
894
- delete legacy.epochSeq;
895
- const epochOne = canonicalEvent(2, 'signal', 1);
896
- const epochTwo = canonicalEvent(3, 'signal', 2);
897
- const seen: Array<{
898
- epochSeq: number;
899
- epochEventIds: string[];
900
- pendingEventIds: string[];
901
- }> = [];
902
- const test = harness([{
903
- kind: 'epoch',
904
- id: 'consumer',
905
- version: '1',
906
- consumes: { events: ['signal'] },
907
- update(input) {
908
- seen.push({
909
- epochSeq: input.epoch.epochSeq,
910
- epochEventIds: input.epochEvents.map((event) => event.eventId),
911
- pendingEventIds: input.pendingEvents.map((event) => event.eventId),
912
- });
913
- return { outcome: 'noop' };
914
- },
915
- }], { seedEvents: [legacy, epochOne, epochTwo] });
916
-
917
- const first = await test.scheduler.enqueue(test.work(1));
918
- const second = await test.scheduler.enqueue(test.work(2));
919
-
920
- expect(first.eventCount).toBe(1);
921
- expect(second.eventCount).toBe(1);
922
- expect(seen).toEqual([{
923
- epochSeq: 1,
924
- epochEventIds: [epochOne.eventId],
925
- pendingEventIds: [legacy.eventId, epochOne.eventId],
926
- }, {
927
- epochSeq: 2,
928
- epochEventIds: [epochTwo.eventId],
929
- pendingEventIds: [legacy.eventId, epochOne.eventId, epochTwo.eventId],
930
- }]);
931
- expect(test.eventListRequests.filter((request) => (
932
- request.epochSeq === undefined && request.maxEpochSeq === undefined
933
- ))).toEqual([]);
934
- expect(test.eventListRequests.filter((request) => request.epochSeq !== undefined))
935
- .toEqual(expect.arrayContaining([
936
- expect.objectContaining({ epochSeq: 1 }),
937
- expect.objectContaining({ epochSeq: 2 }),
938
- ]));
939
- expect(test.eventListRequests.filter((request) => request.maxEpochSeq !== undefined))
940
- .toEqual(expect.arrayContaining([
941
- expect.objectContaining({ maxEpochSeq: 1 }),
942
- expect.objectContaining({ maxEpochSeq: 2 }),
943
- ]));
944
- await test.scheduler.close();
945
- });
946
-
947
- it('does not advance an Event cursor on noop unless the plugin confirms consumption', async () => {
948
- const pendingCounts: number[] = [];
949
- const plugin: RuntimeEpochPlugin = {
950
- kind: 'epoch',
951
- id: 'consumer',
952
- version: '1',
953
- consumes: { events: ['signal'] },
954
- update(input) {
955
- pendingCounts.push(input.pendingEvents.length);
956
- return input.epoch.epochSeq === 2
957
- ? { outcome: 'processed', consumeEventsThroughCommitSeq: 1 }
958
- : { outcome: 'noop' };
959
- },
960
- };
961
- const test = harness([plugin], { seedEvents: [canonicalEvent(1, 'signal')] });
962
-
963
- await test.scheduler.enqueue(test.work(1));
964
- await test.scheduler.enqueue(test.work(2));
965
- await test.scheduler.enqueue(test.work(3));
966
-
967
- expect(pendingCounts).toEqual([1, 1, 0]);
968
- expect(test.journal.pluginProgress('consumer', scope)).toMatchObject({
969
- completedThroughEpochSeq: 3,
970
- eventCursor: 1,
971
- });
972
- await test.scheduler.close();
973
- });
974
-
975
- it('makes the last committed plugin checkpoint available to the next epoch', async () => {
976
- const seen: unknown[] = [];
977
- const test = harness([{
978
- kind: 'epoch',
979
- id: 'checkpointed',
980
- version: '1',
981
- update(input, context) {
982
- seen.push(context.checkpoint());
983
- return input.epoch.epochSeq === 1
984
- ? { outcome: 'processed', checkpoint: { lastEpochSeq: 1 } }
985
- : { outcome: 'noop' };
986
- },
987
- }]);
988
-
989
- await test.scheduler.enqueue(test.work(1));
990
- await test.scheduler.enqueue(test.work(2));
991
-
992
- expect(seen).toEqual([undefined, { lastEpochSeq: 1 }]);
993
- expect(test.journal.pluginProgress('checkpointed', scope)).toMatchObject({
994
- completedThroughEpochSeq: 2,
995
- checkpoint: { lastEpochSeq: 1 },
996
- });
997
- await test.scheduler.close();
998
- });
999
-
1000
- it('does not rerun a plugin already committed in an open recovery epoch', async () => {
1001
- const recoveredUpdate = vi.fn(() => ({ outcome: 'noop' as const }));
1002
- const seen: Array<Record<string, unknown>> = [];
1003
- const event = canonicalEvent(1, 'a.done', 1, { recovered: true });
1004
- event.sourceId = 'runtime-plugin:a';
1005
- const test = harness([{
1006
- kind: 'epoch',
1007
- id: 'a',
1008
- version: '1',
1009
- produces: { states: ['a.state'], events: ['a.done'] },
1010
- update: recoveredUpdate,
1011
- }, {
1012
- kind: 'epoch',
1013
- id: 'b',
1014
- version: '1',
1015
- after: ['a'],
1016
- consumes: { states: ['a.state'], events: ['a.done'] },
1017
- update(input) {
1018
- seen.push({
1019
- states: input.upstreamStates,
1020
- epochEvents: input.epochEvents.map((item) => item.type),
1021
- pendingEvents: input.pendingEvents.map((item) => item.type),
1022
- });
1023
- return {
1024
- outcome: 'processed',
1025
- consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)?.commitSeq,
1026
- };
1027
- },
1028
- }], { seedEvents: [event] });
1029
- const work = test.work(1);
1030
- test.journal.saveStates([{
1031
- epochSeq: 1,
1032
- pluginId: 'a',
1033
- topic: 'a.state',
1034
- value: { recovered: true },
1035
- }]);
1036
- test.journal.savePluginProgress({
1037
- pluginId: 'a',
1038
- completedThroughEpochSeq: 1,
1039
- eventCursor: 0,
1040
- checkpoint: { durable: true },
1041
- updatedAt: new Date().toISOString(),
1042
- }, scope);
1043
-
1044
- const result = await test.scheduler.enqueue(work);
1045
-
1046
- expect(recoveredUpdate).not.toHaveBeenCalled();
1047
- expect(result.outcomes[0]).toMatchObject({
1048
- pluginId: 'a',
1049
- outcome: 'noop',
1050
- reason: 'recovered:already_completed',
1051
- });
1052
- expect(seen).toEqual([{
1053
- states: { 'a.state': { recovered: true } },
1054
- epochEvents: ['a.done'],
1055
- pendingEvents: ['a.done'],
1056
- }]);
1057
- expect(test.journal.pluginProgress('a', scope)).toMatchObject({
1058
- completedThroughEpochSeq: 1,
1059
- checkpoint: { durable: true },
1060
- });
1061
- expect(test.eventListRequests.filter((request) => (
1062
- request.epochSeq === undefined && request.maxEpochSeq === undefined
1063
- ))).toEqual([]);
1064
- await test.scheduler.close();
1065
- });
1066
-
1067
- it('runs lifecycle flush without mutating an already closed epoch', async () => {
1068
- const calls: string[] = [];
1069
- const test = harness([{
1070
- kind: 'epoch',
1071
- id: 'producer',
1072
- version: '1',
1073
- produces: { states: ['final.state'], events: ['final.signal'] },
1074
- update: () => ({
1075
- outcome: 'processed' as const,
1076
- states: [{ topic: 'final.state', value: { ready: true } }],
1077
- events: [{ type: 'final.signal', dedupeKey: 'final', payload: { ready: true } }],
1078
- }),
1079
- flush: () => { calls.push('producer'); },
1080
- }, {
1081
- kind: 'epoch',
1082
- id: 'consumer',
1083
- version: '1',
1084
- after: ['producer'],
1085
- consumes: { states: ['final.state'], events: ['final.signal'] },
1086
- update: (input) => ({
1087
- outcome: 'processed',
1088
- consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq,
1089
- }),
1090
- flush: () => { calls.push('consumer'); },
1091
- }]);
1092
-
1093
- await test.scheduler.enqueue(test.work(1));
1094
- const statesBeforeClose = test.journal.states(1);
1095
- const recordsBeforeClose = test.journal.pluginRecords(1);
1096
- await test.scheduler.close();
1097
-
1098
- expect(calls).toEqual(['producer', 'consumer']);
1099
- expect(test.journal.states(1)).toEqual(statesBeforeClose);
1100
- expect(test.journal.pluginRecords(1)).toEqual(recordsBeforeClose);
1101
- expect(test.journal.pluginProgress('consumer', scope)).toMatchObject({ eventCursor: 1 });
1102
- });
1103
-
1104
- it('records a timeout as failed and rejects the late output', async () => {
1105
- let release!: () => void;
1106
- const gate = new Promise<void>((resolve) => { release = resolve; });
1107
- const plugin: RuntimeEpochPlugin = {
1108
- kind: 'epoch',
1109
- id: 'late',
1110
- version: '1',
1111
- timeoutMs: 10,
1112
- produces: { states: ['late.state'] },
1113
- async update() {
1114
- await gate;
1115
- return {
1116
- outcome: 'processed',
1117
- states: [{ topic: 'late.state', value: true }],
1118
- };
1119
- },
1120
- };
1121
- const test = harness([plugin], { pluginTimeoutMs: 1_000 });
1122
-
1123
- const result = await test.scheduler.enqueue(test.work(1));
1124
- expect(result.outcomes).toMatchObject([{ pluginId: 'late', outcome: 'failed' }]);
1125
- expect(test.journal.states(1)).toEqual([]);
1126
- release();
1127
- await vi.waitFor(() => expect(test.diagnostics.some((entry) => (
1128
- entry.name === 'runtime.plugin.stale_output_rejected'
1129
- ))).toBe(true));
1130
- expect(test.journal.states(1)).toEqual([]);
1131
- expect(test.diagnostics.some((entry) => entry.name === 'runtime.plugin.invocation_cancelled'))
1132
- .toBe(true);
1133
- expect(test.diagnostics).toEqual(expect.arrayContaining([
1134
- expect.objectContaining({ name: 'runtime.plugin.invocation_cancelled', severity: 'warn' }),
1135
- expect.objectContaining({ name: 'runtime.plugin.invocation_failed', severity: 'error' }),
1136
- expect.objectContaining({ name: 'runtime.plugin.stale_output_rejected', severity: 'warn' }),
1137
- ]));
1138
- await test.scheduler.close();
1139
- });
1140
-
1141
- it('keeps a legacy update lease after timeout so the next epoch cannot overlap it', async () => {
1142
- let releaseFirst!: () => void;
1143
- const firstGate = new Promise<void>((resolve) => { releaseFirst = resolve; });
1144
- const started: number[] = [];
1145
- let active = 0;
1146
- let maxActive = 0;
1147
- const test = harness([{
1148
- kind: 'epoch',
1149
- id: 'legacy-timeout-lease',
1150
- version: '1',
1151
- timeoutMs: 20,
1152
- async update(input) {
1153
- active += 1;
1154
- maxActive = Math.max(maxActive, active);
1155
- started.push(input.epoch.epochSeq);
1156
- try {
1157
- if (input.epoch.epochSeq === 1) await firstGate;
1158
- return { outcome: 'noop' };
1159
- } finally {
1160
- active -= 1;
1161
- }
1162
- },
1163
- }]);
1164
-
1165
- const first = await test.scheduler.enqueue(test.work(1));
1166
- expect(first.outcomes[0]?.outcome).toBe('failed');
1167
- expect(active).toBe(1);
1168
- const second = test.scheduler.enqueue(test.work(2));
1169
- await new Promise((resolve) => setTimeout(resolve, 40));
1170
- expect(started).toEqual([1]);
1171
- expect(maxActive).toBe(1);
1172
-
1173
- releaseFirst();
1174
- expect((await second).outcomes[0]?.outcome).toBe('noop');
1175
- expect(started).toEqual([1, 2]);
1176
- expect(maxActive).toBe(1);
1177
- await test.scheduler.close();
1178
- });
1179
-
1180
- it('keeps stale parallel computations in maxInFlight capacity until they settle', async () => {
1181
- let releaseFirst!: () => void;
1182
- let releaseSecond!: () => void;
1183
- const firstGate = new Promise<void>((resolve) => { releaseFirst = resolve; });
1184
- const secondGate = new Promise<void>((resolve) => { releaseSecond = resolve; });
1185
- const started: number[] = [];
1186
- let active = 0;
1187
- let maxActive = 0;
1188
- const test = harness([{
1189
- kind: 'epoch',
1190
- id: 'parallel-timeout-capacity',
1191
- version: '1',
1192
- maxInFlight: 2,
1193
- timeoutMs: 20,
1194
- async update(input) {
1195
- active += 1;
1196
- maxActive = Math.max(maxActive, active);
1197
- const epochSeq = input.epoch.epochSeq;
1198
- started.push(epochSeq);
1199
- try {
1200
- if (epochSeq === 1) await firstGate;
1201
- if (epochSeq === 2) await secondGate;
1202
- return { outcome: 'noop' };
1203
- } finally {
1204
- active -= 1;
1205
- }
1206
- },
1207
- }]);
1208
-
1209
- const first = await test.scheduler.enqueue(test.work(1));
1210
- expect(first.outcomes[0]?.outcome).toBe('failed');
1211
- const second = test.scheduler.enqueue(test.work(2));
1212
- const third = test.scheduler.enqueue(test.work(3));
1213
- await vi.waitFor(() => expect(started).toEqual([1, 2]));
1214
- await new Promise((resolve) => setTimeout(resolve, 40));
1215
- expect(started).toEqual([1, 2]);
1216
- expect(active).toBe(2);
1217
- expect(maxActive).toBe(2);
1218
-
1219
- releaseFirst();
1220
- await vi.waitFor(() => expect(started).toEqual([1, 2, 3]));
1221
- releaseSecond();
1222
- const results = await Promise.all([second, third]);
1223
- expect(results[0].outcomes[0]?.outcome).toBe('failed');
1224
- expect(results[1].outcomes[0]?.outcome).toBe('noop');
1225
- expect(maxActive).toBe(2);
1226
- await test.scheduler.close();
1227
- });
1228
-
1229
- it('runs dependent plugins after an upstream timeout with the missing output omitted', async () => {
1230
- let release!: () => void;
1231
- const gate = new Promise<void>((resolve) => { release = resolve; });
1232
- const downstream = vi.fn((input: any) => {
1233
- expect(input.upstreamStates).toEqual({});
1234
- return { outcome: 'noop' as const, reason: 'upstream_output_unavailable' };
1235
- });
1236
- const test = harness([{
1237
- kind: 'epoch',
1238
- id: 'slow-upstream',
1239
- version: '1',
1240
- timeoutMs: 10,
1241
- produces: { states: ['slow.state'] },
1242
- async update() {
1243
- await gate;
1244
- return {
1245
- outcome: 'processed',
1246
- states: [{ topic: 'slow.state', value: true }],
1247
- };
1248
- },
1249
- }, {
1250
- kind: 'epoch',
1251
- id: 'downstream',
1252
- version: '1',
1253
- after: ['slow-upstream'],
1254
- consumes: { states: ['slow.state'] },
1255
- update: downstream,
1256
- }]);
1257
-
1258
- const result = await test.scheduler.enqueue(test.work(1));
1259
-
1260
- expect(result.outcomes).toEqual(expect.arrayContaining([
1261
- expect.objectContaining({ pluginId: 'slow-upstream', outcome: 'failed' }),
1262
- expect.objectContaining({ pluginId: 'downstream', outcome: 'noop' }),
1263
- ]));
1264
- expect(downstream).toHaveBeenCalledOnce();
1265
- expect(test.journal.pluginProgress('slow-upstream', scope).completedThroughEpochSeq).toBe(1);
1266
- expect(test.journal.pluginProgress('downstream', scope).completedThroughEpochSeq).toBe(1);
1267
- release();
1268
- await vi.waitFor(() => expect(test.diagnostics.some((entry) => (
1269
- entry.name === 'runtime.plugin.stale_output_rejected'
1270
- ))).toBe(true));
1271
- await test.scheduler.close();
1272
- });
1273
-
1274
- it('retries a failed invocation according to the plugin failure policy', async () => {
1275
- let attempts = 0;
1276
- const test = harness([{
1277
- kind: 'epoch',
1278
- id: 'retrying',
1279
- version: '1',
1280
- failurePolicy: { mode: 'retry', maxAttempts: 2 },
1281
- produces: { states: ['retrying.state'] },
1282
- update() {
1283
- attempts += 1;
1284
- if (attempts === 1) throw new Error('retry me');
1285
- return {
1286
- outcome: 'processed',
1287
- states: [{ topic: 'retrying.state', value: { attempts } }],
1288
- };
1289
- },
1290
- }]);
1291
-
1292
- const result = await test.scheduler.enqueue(test.work(1));
1293
-
1294
- expect(attempts).toBe(2);
1295
- expect(result.outcomes).toMatchObject([{ pluginId: 'retrying', outcome: 'processed' }]);
1296
- expect(test.journal.states(1)).toMatchObject([{
1297
- pluginId: 'retrying',
1298
- value: { attempts: 2 },
1299
- }]);
1300
- expect(test.diagnostics.some((entry) => entry.name === 'runtime.plugin.invocation_retrying'))
1301
- .toBe(true);
1302
- await test.scheduler.close();
1303
- });
1304
-
1305
- it('records failed completions for a paused plugin without blocking later epochs', async () => {
1306
- const update = vi.fn(() => { throw new Error('pause me'); });
1307
- const test = harness([{
1308
- kind: 'epoch',
1309
- id: 'pausing',
1310
- version: '1',
1311
- failurePolicy: 'pause',
1312
- update,
1313
- }]);
1314
-
1315
- const first = await test.scheduler.enqueue(test.work(1));
1316
- const second = await test.scheduler.enqueue(test.work(2));
1317
-
1318
- expect(update).toHaveBeenCalledOnce();
1319
- expect(first.outcomes).toMatchObject([{ pluginId: 'pausing', outcome: 'failed' }]);
1320
- expect(second.outcomes).toMatchObject([{
1321
- pluginId: 'pausing',
1322
- outcome: 'failed',
1323
- reason: 'plugin_paused',
1324
- }]);
1325
- expect(test.journal.pluginProgress('pausing', scope).completedThroughEpochSeq).toBe(2);
1326
- await test.scheduler.close();
1327
- });
1328
-
1329
- it('terminates the scheduler when a plugin uses the terminate failure policy', async () => {
1330
- const test = harness([{
1331
- kind: 'epoch',
1332
- id: 'fatal',
1333
- version: '1',
1334
- failurePolicy: 'terminate',
1335
- update: () => { throw new Error('fatal plugin failure'); },
1336
- }]);
1337
-
1338
- await expect(test.scheduler.enqueue(test.work(1))).rejects.toThrow(
1339
- 'Runtime Epoch Plugin "fatal" terminated the Runtime',
1340
- );
1341
- await expect(test.scheduler.enqueue(test.work(2))).rejects.toThrow(
1342
- 'Runtime Epoch Plugin "fatal" terminated the Runtime',
1343
- );
1344
- expect(test.journal.listOpen(scope)).toHaveLength(2);
1345
- await test.scheduler.close();
1346
- });
1347
-
1348
- it('binds plugin diagnostics to the current plugin and epoch', async () => {
1349
- const test = harness([{
1350
- kind: 'epoch',
1351
- id: 'diagnostic-producer',
1352
- version: '1',
1353
- update(_input, context) {
1354
- context.diagnostic('runtime.plugin.coverage_gap', {
1355
- missing_from_epoch_seq: 1,
1356
- missing_to_epoch_seq: 2,
1357
- });
1358
- return { outcome: 'noop', reason: 'diagnostic_test' };
1359
- },
1360
- }]);
1361
-
1362
- await test.scheduler.enqueue(test.work(3));
1363
-
1364
- expect(test.diagnostics).toContainEqual({
1365
- name: 'runtime.plugin.coverage_gap',
1366
- severity: 'debug',
1367
- attributes: expect.objectContaining({
1368
- plugin_id: 'diagnostic-producer',
1369
- epoch_seq: 1,
1370
- missing_from_epoch_seq: 1,
1371
- missing_to_epoch_seq: 2,
1372
- }),
1373
- });
1374
- await test.scheduler.close();
1375
- });
1376
-
1377
- it('runs opt-in updates across epochs concurrently but publishes their results in epoch order', async () => {
1378
- let releaseFirst!: () => void;
1379
- const firstGate = new Promise<void>((resolve) => { releaseFirst = resolve; });
1380
- const started: number[] = [];
1381
- const test = harness([{
1382
- kind: 'epoch',
1383
- id: 'parallel-compute',
1384
- version: '1',
1385
- maxInFlight: 2,
1386
- produces: { events: ['parallel.finished'] },
1387
- async update(input) {
1388
- const epochSeq = input.epoch.epochSeq;
1389
- started.push(epochSeq);
1390
- if (epochSeq === 1) await firstGate;
1391
- return {
1392
- outcome: 'processed',
1393
- events: [{
1394
- type: 'parallel.finished',
1395
- dedupeKey: `parallel:${epochSeq}`,
1396
- payload: { epoch_seq: epochSeq },
1397
- }],
1398
- };
1399
- },
1400
- }]);
1401
-
1402
- const first = test.scheduler.enqueue(test.work(1));
1403
- await vi.waitFor(() => expect(started).toEqual([1]));
1404
- const second = test.scheduler.enqueue(test.work(2));
1405
- await vi.waitFor(() => expect(started).toEqual([1, 2]));
1406
- expect(test.events).toEqual([]);
1407
-
1408
- releaseFirst();
1409
- await Promise.all([first, second]);
1410
-
1411
- expect(test.events.map((event) => event.payload.epoch_seq)).toEqual([1, 2]);
1412
- expect(test.journal.pluginProgress('parallel-compute', scope).completedThroughEpochSeq).toBe(2);
1413
- await test.scheduler.close();
1414
- });
1415
-
1416
- it('keeps every strict-ordered slot while parallel computation is capacity bounded', async () => {
1417
- let releaseFirst!: () => void;
1418
- const firstGate = new Promise<void>((resolve) => { releaseFirst = resolve; });
1419
- const updated: number[] = [];
1420
- const committed: number[] = [];
1421
- const test = harness([{
1422
- kind: 'epoch',
1423
- id: 'strict-ordered-parallel',
1424
- version: '1',
1425
- catchUp: 'strict_ordered',
1426
- maxInFlight: 2,
1427
- update(input) {
1428
- const epochSeq = input.epoch.epochSeq;
1429
- updated.push(epochSeq);
1430
- return { outcome: 'processed', proposal: { epochSeq } };
1431
- },
1432
- async commit(input) {
1433
- const epochSeq = input.epoch.epochSeq;
1434
- committed.push(epochSeq);
1435
- if (epochSeq === 1) await firstGate;
1436
- return { outcome: 'noop', reason: `committed:${epochSeq}` };
1437
- },
1438
- }], { maxCatchUpEpochs: 1 });
1439
-
1440
- const completions = [1, 2, 3, 4].map((marker) => test.scheduler.enqueue(test.work(marker)));
1441
- await vi.waitFor(() => expect(updated).toEqual([1, 2]));
1442
- expect(committed).toEqual([1]);
1443
-
1444
- releaseFirst();
1445
- const results = await Promise.all(completions);
1446
-
1447
- expect(updated).toEqual([1, 2, 3, 4]);
1448
- expect(committed).toEqual([1, 2, 3, 4]);
1449
- expect(results.every((result) => result.outcomes[0]?.outcome === 'noop')).toBe(true);
1450
- expect(test.journal.pluginProgress('strict-ordered-parallel', scope).completedThroughEpochSeq).toBe(4);
1451
- await test.scheduler.close();
1452
- });
1453
-
1454
- it('drops a successful buffered proposal outside the parallel catch-up window before commit', async () => {
1455
- let releaseFirstCommit!: () => void;
1456
- const firstCommitGate = new Promise<void>((resolve) => { releaseFirstCommit = resolve; });
1457
- const updated: number[] = [];
1458
- const committed: number[] = [];
1459
- const test = harness([{
1460
- kind: 'epoch',
1461
- id: 'parallel-buffer-window',
1462
- version: '1',
1463
- maxInFlight: 3,
1464
- produces: { states: ['parallel-buffer.state'] },
1465
- update(input) {
1466
- const epochSeq = input.epoch.epochSeq;
1467
- updated.push(epochSeq);
1468
- return { outcome: 'processed', proposal: { epochSeq } };
1469
- },
1470
- async commit(input) {
1471
- const epochSeq = input.epoch.epochSeq;
1472
- committed.push(epochSeq);
1473
- if (epochSeq === 1) await firstCommitGate;
1474
- return {
1475
- outcome: 'processed',
1476
- states: [{ topic: 'parallel-buffer.state', value: epochSeq }],
1477
- };
1478
- },
1479
- }], { maxCatchUpEpochs: 2 });
1480
-
1481
- const completions = [test.scheduler.enqueue(test.work(1))];
1482
- await vi.waitFor(() => expect(committed).toEqual([1]));
1483
- for (let marker = 2; marker <= 4; marker += 1) {
1484
- completions.push(test.scheduler.enqueue(test.work(marker)));
1485
- }
1486
- await vi.waitFor(() => expect(updated).toEqual([1, 2]));
1487
-
1488
- releaseFirstCommit();
1489
- const results = await Promise.all(completions);
1490
-
1491
- expect(updated).toEqual([1, 2, 3, 4]);
1492
- expect(committed).toEqual([1, 3, 4]);
1493
- expect(results[1].outcomes).toMatchObject([{
1494
- pluginId: 'parallel-buffer-window',
1495
- outcome: 'coalesced',
1496
- reason: 'catch_up_limit',
1497
- }]);
1498
- expect(test.journal.states(2)).toEqual([]);
1499
- expect(test.journal.pluginProgress('parallel-buffer-window', scope).completedThroughEpochSeq).toBe(4);
1500
- await test.scheduler.close();
1501
- });
1502
-
1503
- it('preserves a forbidden buffered proposal outside the parallel catch-up window', async () => {
1504
- let releaseFirstCommit!: () => void;
1505
- const firstCommitGate = new Promise<void>((resolve) => { releaseFirstCommit = resolve; });
1506
- const committed: number[] = [];
1507
- const test = harness([{
1508
- kind: 'epoch',
1509
- id: 'parallel-buffer-boundary',
1510
- version: '1',
1511
- maxInFlight: 3,
1512
- update(input) {
1513
- return { outcome: 'processed', proposal: input.epoch.epochSeq };
1514
- },
1515
- async commit(input) {
1516
- const epochSeq = input.epoch.epochSeq;
1517
- committed.push(epochSeq);
1518
- if (epochSeq === 1) await firstCommitGate;
1519
- return { outcome: 'noop' };
1520
- },
1521
- }], { maxCatchUpEpochs: 2 });
1522
-
1523
- const first = test.scheduler.enqueue(test.work(1));
1524
- await vi.waitFor(() => expect(committed).toEqual([1]));
1525
- const second = test.scheduler.enqueue(test.work(2, { coalescing: 'forbidden' }));
1526
- const third = test.scheduler.enqueue(test.work(3));
1527
- const fourth = test.scheduler.enqueue(test.work(4));
1528
-
1529
- releaseFirstCommit();
1530
- const results = await Promise.all([first, second, third, fourth]);
1531
-
1532
- expect(committed).toEqual([1, 2, 3, 4]);
1533
- expect(results.every((result) => result.outcomes[0]?.outcome === 'noop')).toBe(true);
1534
- await test.scheduler.close();
1535
- });
1536
-
1537
- it('does not hide a buffered parallel failure behind catch-up coalescing', async () => {
1538
- let releaseFirstCommit!: () => void;
1539
- const firstCommitGate = new Promise<void>((resolve) => { releaseFirstCommit = resolve; });
1540
- const committed: number[] = [];
1541
- const test = harness([{
1542
- kind: 'epoch',
1543
- id: 'parallel-buffer-failure',
1544
- version: '1',
1545
- maxInFlight: 3,
1546
- update(input) {
1547
- if (input.epoch.epochSeq === 2) throw new Error('buffered-update-failed');
1548
- return { outcome: 'processed', proposal: input.epoch.epochSeq };
1549
- },
1550
- async commit(input) {
1551
- const epochSeq = input.epoch.epochSeq;
1552
- committed.push(epochSeq);
1553
- if (epochSeq === 1) await firstCommitGate;
1554
- return { outcome: 'noop' };
1555
- },
1556
- }], { maxCatchUpEpochs: 2 });
1557
-
1558
- const first = test.scheduler.enqueue(test.work(1));
1559
- await vi.waitFor(() => expect(committed).toEqual([1]));
1560
- const second = test.scheduler.enqueue(test.work(2));
1561
- const third = test.scheduler.enqueue(test.work(3));
1562
- const fourth = test.scheduler.enqueue(test.work(4));
1563
-
1564
- releaseFirstCommit();
1565
- const results = await Promise.all([first, second, third, fourth]);
1566
-
1567
- expect(results[1].outcomes).toMatchObject([{
1568
- pluginId: 'parallel-buffer-failure',
1569
- outcome: 'failed',
1570
- reason: 'buffered-update-failed',
1571
- }]);
1572
- expect(committed).toEqual([1, 3, 4]);
1573
- await test.scheduler.close();
1574
- });
1575
-
1576
- it('passes opaque parallel proposals through a strictly ordered commit hook with current progress', async () => {
1577
- let releaseFirst!: () => void;
1578
- const firstGate = new Promise<void>((resolve) => { releaseFirst = resolve; });
1579
- const computed: number[] = [];
1580
- const committed: Array<{ epochSeq: number; completedThrough: number }> = [];
1581
- const test = harness([{
1582
- kind: 'epoch',
1583
- id: 'parallel-reducer',
1584
- version: '1',
1585
- maxInFlight: 2,
1586
- produces: { states: ['parallel.state'] },
1587
- async update(input) {
1588
- const epochSeq = input.epoch.epochSeq;
1589
- computed.push(epochSeq);
1590
- if (epochSeq === 1) await firstGate;
1591
- return { outcome: 'processed', proposal: { epochSeq } };
1592
- },
1593
- commit(input, computation, context) {
1594
- const proposal = computation.proposal as { epochSeq: number };
1595
- committed.push({
1596
- epochSeq: input.epoch.epochSeq,
1597
- completedThrough: context.progress().completedThroughEpochSeq,
1598
- });
1599
- return {
1600
- outcome: 'processed',
1601
- states: [{ topic: 'parallel.state', value: proposal.epochSeq }],
1602
- checkpoint: { through: proposal.epochSeq },
1603
- };
1604
- },
1605
- }]);
1606
-
1607
- const first = test.scheduler.enqueue(test.work(1));
1608
- await vi.waitFor(() => expect(computed).toEqual([1]));
1609
- const second = test.scheduler.enqueue(test.work(2));
1610
- await vi.waitFor(() => expect(computed).toEqual([1, 2]));
1611
- expect(committed).toEqual([]);
1612
-
1613
- releaseFirst();
1614
- await Promise.all([first, second]);
1615
-
1616
- expect(committed).toEqual([
1617
- { epochSeq: 1, completedThrough: 0 },
1618
- { epochSeq: 2, completedThrough: 1 },
1619
- ]);
1620
- expect(test.journal.states(1)).toMatchObject([{ topic: 'parallel.state', value: 1 }]);
1621
- expect(test.journal.states(2)).toMatchObject([{ topic: 'parallel.state', value: 2 }]);
1622
- expect(test.journal.pluginProgress('parallel-reducer', scope).checkpoint).toEqual({ through: 2 });
1623
- await test.scheduler.close();
1624
- });
1625
-
1626
- it('freezes the segment view for each parallel update invocation', async () => {
1627
- let release!: () => void;
1628
- const gate = new Promise<void>((resolve) => { release = resolve; });
1629
- let currentKind = 'game';
1630
- const seen: string[] = [];
1631
- const test = harness([{
1632
- kind: 'epoch',
1633
- id: 'parallel-segment-snapshot',
1634
- version: '1',
1635
- maxInFlight: 2,
1636
- async update(_input, context) {
1637
- seen.push(context.currentSegment().kind);
1638
- await gate;
1639
- seen.push(context.currentSegment().kind);
1640
- return { outcome: 'noop' };
1641
- },
1642
- }], { currentSegment: () => ({ kind: currentKind }) });
1643
-
1644
- const completion = test.scheduler.enqueue(test.work(1));
1645
- await vi.waitFor(() => expect(seen).toEqual(['game']));
1646
- currentKind = 'meeting';
1647
- release();
1648
- await completion;
1649
-
1650
- expect(seen).toEqual(['game', 'game']);
1651
- await test.scheduler.close();
1652
- });
1653
-
1654
- it('rebuilds ordered commit Event input from the latest plugin cursor', async () => {
1655
- let releaseFirst!: () => void;
1656
- const firstGate = new Promise<void>((resolve) => { releaseFirst = resolve; });
1657
- const seen: Array<{ epochSeq: number; cursor: number; pending: number[] }> = [];
1658
- const test = harness([{
1659
- kind: 'epoch',
1660
- id: 'parallel-cursor',
1661
- version: '1',
1662
- maxInFlight: 2,
1663
- consumes: { events: ['watched'] },
1664
- async update(input) {
1665
- if (input.epoch.epochSeq === 1) await firstGate;
1666
- return { outcome: 'processed', proposal: input.epoch.epochSeq };
1667
- },
1668
- commit(input, _computation, context) {
1669
- const pending = input.pendingEvents.map((event) => event.commitSeq);
1670
- seen.push({
1671
- epochSeq: input.epoch.epochSeq,
1672
- cursor: context.progress().eventCursor,
1673
- pending,
1674
- });
1675
- return {
1676
- outcome: 'noop',
1677
- consumeEventsThroughCommitSeq: pending.at(-1) ?? context.progress().eventCursor,
1678
- };
1679
- },
1680
- }]);
1681
-
1682
- const first = test.scheduler.enqueue(test.work(1, {
1683
- events: [{ type: 'watched', payload: { marker: 1 } }],
1684
- }));
1685
- const second = test.scheduler.enqueue(test.work(2, {
1686
- events: [{ type: 'watched', payload: { marker: 2 } }],
1687
- }));
1688
- await vi.waitFor(() => expect(test.events).toHaveLength(2));
1689
- releaseFirst();
1690
- await Promise.all([first, second]);
1691
-
1692
- expect(seen).toEqual([
1693
- { epochSeq: 1, cursor: 0, pending: [1] },
1694
- { epochSeq: 2, cursor: 1, pending: [2] },
1695
- ]);
1696
- expect(test.journal.pluginProgress('parallel-cursor', scope).eventCursor).toBe(2);
1697
- await test.scheduler.close();
1698
- });
1699
-
1700
- it('drops an unfinished parallel head only after it falls outside the catch-up window', async () => {
1701
- let releaseFirst!: () => void;
1702
- const firstGate = new Promise<void>((resolve) => { releaseFirst = resolve; });
1703
- const started: number[] = [];
1704
- const test = harness([{
1705
- kind: 'epoch',
1706
- id: 'parallel-window',
1707
- version: '1',
1708
- maxInFlight: 4,
1709
- async update(input) {
1710
- const epochSeq = input.epoch.epochSeq;
1711
- started.push(epochSeq);
1712
- if (epochSeq === 1) await firstGate;
1713
- return { outcome: 'noop' };
1714
- },
1715
- }], { maxCatchUpEpochs: 3 });
1716
-
1717
- const completions = [test.scheduler.enqueue(test.work(1))];
1718
- await vi.waitFor(() => expect(started).toEqual([1]));
1719
- for (let marker = 2; marker <= 4; marker += 1) {
1720
- completions.push(test.scheduler.enqueue(test.work(marker)));
1721
- }
1722
-
1723
- const results = await Promise.all(completions);
1724
- expect(results[0].outcomes).toMatchObject([{
1725
- pluginId: 'parallel-window',
1726
- outcome: 'coalesced',
1727
- reason: 'catch_up_limit',
1728
- }]);
1729
- expect(results.slice(1).every((result) => (
1730
- result.outcomes[0]?.outcome === 'noop'
1731
- ))).toBe(true);
1732
-
1733
- releaseFirst();
1734
- await vi.waitFor(() => expect(test.diagnostics).toContainEqual(expect.objectContaining({
1735
- name: 'runtime.plugin.stale_output_rejected',
1736
- attributes: expect.objectContaining({ reason: 'catch_up_limit' }),
1737
- })));
1738
- await test.scheduler.close();
1739
- });
1740
-
1741
- it('uses a smaller plugin concurrency limit as its parallel catch-up window', async () => {
1742
- const started: number[] = [];
1743
- const test = harness([{
1744
- kind: 'epoch',
1745
- id: 'parallel-plugin-window',
1746
- version: '1',
1747
- maxInFlight: 2,
1748
- async update(input, context) {
1749
- const epochSeq = input.epoch.epochSeq;
1750
- started.push(epochSeq);
1751
- if (epochSeq === 1) {
1752
- await new Promise<void>((_resolve, reject) => {
1753
- const abort = (): void => reject(context.signal.reason);
1754
- if (context.signal.aborted) abort();
1755
- else context.signal.addEventListener('abort', abort, { once: true });
1756
- });
1757
- }
1758
- return { outcome: 'noop' };
1759
- },
1760
- }], { maxCatchUpEpochs: 10 });
1761
-
1762
- const first = test.scheduler.enqueue(test.work(1));
1763
- await vi.waitFor(() => expect(started).toEqual([1]));
1764
- const second = test.scheduler.enqueue(test.work(2));
1765
- await vi.waitFor(() => expect(started).toEqual([1, 2]));
1766
- const third = test.scheduler.enqueue(test.work(3));
1767
-
1768
- const results = await Promise.all([first, second, third]);
1769
- expect(results[0].outcomes).toMatchObject([{
1770
- pluginId: 'parallel-plugin-window',
1771
- outcome: 'coalesced',
1772
- reason: 'catch_up_limit',
1773
- }]);
1774
- expect(started).toEqual([1, 2, 3]);
1775
- await test.scheduler.close();
1776
- });
1777
-
1778
- it('never drops a forbidden parallel head and blocks parallel update Actions', async () => {
1779
- let releaseFirst!: () => void;
1780
- const firstGate = new Promise<void>((resolve) => { releaseFirst = resolve; });
1781
- const started: number[] = [];
1782
- const test = harness([{
1783
- kind: 'epoch',
1784
- id: 'parallel-boundary',
1785
- version: '1',
1786
- maxInFlight: 2,
1787
- async update(input, context) {
1788
- const epochSeq = input.epoch.epochSeq;
1789
- started.push(epochSeq);
1790
- if (epochSeq === 1) await firstGate;
1791
- if (epochSeq === 2) {
1792
- expect(() => context.capabilities.provideObservation(null as never)).toThrow(
1793
- /cannot register capabilities from a parallel update/,
1794
- );
1795
- expect(() => context.capabilities.provideAction(null as never)).toThrow(
1796
- /cannot register capabilities from a parallel update/,
1797
- );
1798
- await expect(context.capabilities.performAction('test.action', {})).rejects.toThrow(
1799
- /cannot perform Action from a parallel update/,
1800
- );
1801
- }
1802
- return { outcome: 'noop' };
1803
- },
1804
- }], { maxCatchUpEpochs: 2 });
1805
-
1806
- const first = test.scheduler.enqueue(test.work(1, { coalescing: 'forbidden' }));
1807
- await vi.waitFor(() => expect(started).toEqual([1]));
1808
- const second = test.scheduler.enqueue(test.work(2));
1809
- const third = test.scheduler.enqueue(test.work(3));
1810
- await vi.waitFor(() => expect(started).toEqual([1, 2]));
1811
- await new Promise((resolve) => setTimeout(resolve, 0));
1812
- expect(started).toEqual([1, 2]);
1813
-
1814
- releaseFirst();
1815
- const results = await Promise.all([first, second, third]);
1816
- expect(results.flatMap((result) => result.outcomes).every((outcome) => (
1817
- outcome.outcome === 'noop'
1818
- ))).toBe(true);
1819
- expect(started).toEqual([1, 2, 3]);
1820
- await test.scheduler.close();
1821
- });
1822
-
1823
- it('starts ten parallel computes and starts the eleventh only after Runtime drops the stale head', async () => {
1824
- const started: number[] = [];
1825
- let firstAborted = false;
1826
- const test = harness([{
1827
- kind: 'epoch',
1828
- id: 'parallel-capacity',
1829
- version: '1',
1830
- maxInFlight: 10,
1831
- async update(input, context) {
1832
- const epochSeq = input.epoch.epochSeq;
1833
- started.push(epochSeq);
1834
- if (epochSeq === 1) {
1835
- await new Promise<void>((_resolve, reject) => {
1836
- const abort = (): void => {
1837
- firstAborted = true;
1838
- reject(context.signal.reason);
1839
- };
1840
- if (context.signal.aborted) abort();
1841
- else context.signal.addEventListener('abort', abort, { once: true });
1842
- });
1843
- }
1844
- return { outcome: 'noop' };
1845
- },
1846
- }], { maxCatchUpEpochs: 10 });
1847
-
1848
- const completions = [test.scheduler.enqueue(test.work(1))];
1849
- await vi.waitFor(() => expect(started).toEqual([1]));
1850
- for (let marker = 2; marker <= 10; marker += 1) {
1851
- completions.push(test.scheduler.enqueue(test.work(marker)));
1852
- }
1853
- await vi.waitFor(() => expect(started).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
1854
- const eleventh = test.scheduler.enqueue(test.work(11));
1855
- completions.push(eleventh);
1856
- await new Promise((resolve) => setTimeout(resolve, 0));
1857
- await vi.waitFor(() => expect(firstAborted).toBe(true));
1858
- await vi.waitFor(() => expect(started).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]));
1859
-
1860
- const results = await Promise.all(completions);
1861
- expect(results[0].outcomes).toMatchObject([{
1862
- pluginId: 'parallel-capacity',
1863
- outcome: 'coalesced',
1864
- reason: 'catch_up_limit',
1865
- }]);
1866
- expect(results.slice(1).every((result) => result.outcomes[0]?.outcome === 'noop')).toBe(true);
1867
- await test.scheduler.close();
1868
- });
1869
-
1870
- it('holds the ordered commit lease after timeout until the underlying commit settles', async () => {
1871
- let releaseFirstCommit!: () => void;
1872
- const firstCommitGate = new Promise<void>((resolve) => { releaseFirstCommit = resolve; });
1873
- const committed: number[] = [];
1874
- const test = harness([{
1875
- kind: 'epoch',
1876
- id: 'ordered-timeout',
1877
- version: '1',
1878
- maxInFlight: 2,
1879
- timeoutMs: 20,
1880
- update(input) {
1881
- return { outcome: 'processed', proposal: input.epoch.epochSeq };
1882
- },
1883
- async commit(input) {
1884
- const epochSeq = input.epoch.epochSeq;
1885
- committed.push(epochSeq);
1886
- if (epochSeq === 1) await firstCommitGate;
1887
- return { outcome: 'noop' };
1888
- },
1889
- }]);
1890
-
1891
- const first = test.scheduler.enqueue(test.work(1));
1892
- const second = test.scheduler.enqueue(test.work(2));
1893
- await vi.waitFor(() => expect(committed).toEqual([1]));
1894
- await new Promise((resolve) => setTimeout(resolve, 40));
1895
- expect(committed).toEqual([1]);
1896
-
1897
- releaseFirstCommit();
1898
- const results = await Promise.all([first, second]);
1899
- expect(committed).toEqual([1, 2]);
1900
- expect(results[0].outcomes[0]?.outcome).toBe('failed');
1901
- expect(results[1].outcomes[0]?.outcome).toBe('noop');
1902
- await test.scheduler.close();
1903
- });
1904
-
1905
- it('does not stop a scope while an ordered commit or buffered result remains', async () => {
1906
- let releaseFirstCommit!: () => void;
1907
- const firstCommitGate = new Promise<void>((resolve) => { releaseFirstCommit = resolve; });
1908
- const commits: number[] = [];
1909
- const stopped: string[] = [];
1910
- const test = harness([{
1911
- kind: 'epoch',
1912
- id: 'ordered-close',
1913
- version: '1',
1914
- maxInFlight: 2,
1915
- update(input) {
1916
- return { outcome: 'processed', proposal: input.epoch.epochSeq };
1917
- },
1918
- async commit(input) {
1919
- commits.push(input.epoch.epochSeq);
1920
- if (input.epoch.epochSeq === 1) await firstCommitGate;
1921
- return { outcome: 'noop' };
1922
- },
1923
- stop(reason) {
1924
- stopped.push(reason);
1925
- },
1926
- }]);
1927
-
1928
- const first = test.scheduler.enqueue(test.work(1));
1929
- const second = test.scheduler.enqueue(test.work(2));
1930
- await vi.waitFor(() => expect(commits).toEqual([1]));
1931
- const closing = test.scheduler.close();
1932
- await new Promise((resolve) => setTimeout(resolve, 20));
1933
- expect(stopped).toEqual([]);
1934
- expect(commits).toEqual([1]);
1935
-
1936
- releaseFirstCommit();
1937
- await Promise.all([first, second, closing]);
1938
- expect(commits).toEqual([1, 2]);
1939
- expect(stopped).toEqual(['shutdown']);
1940
- });
1941
-
1942
- it('logs a plugin flush failure without failing shutdown or skipping peer plugins', async () => {
1943
- const flushed: string[] = [];
1944
- const test = harness([{
1945
- kind: 'epoch',
1946
- id: 'flush-failure',
1947
- version: '1',
1948
- update: () => ({ outcome: 'noop' }),
1949
- flush() {
1950
- flushed.push('flush-failure');
1951
- throw new Error('broken plugin flush');
1952
- },
1953
- }, {
1954
- kind: 'epoch',
1955
- id: 'flush-peer',
1956
- version: '1',
1957
- update: () => ({ outcome: 'noop' }),
1958
- flush() {
1959
- flushed.push('flush-peer');
1960
- },
1961
- }]);
1962
-
1963
- await test.scheduler.enqueue(test.work(1));
1964
- await expect(test.scheduler.close()).resolves.toBeUndefined();
1965
-
1966
- expect(flushed).toEqual(['flush-failure', 'flush-peer']);
1967
- expect(test.diagnostics).toContainEqual(expect.objectContaining({
1968
- name: 'runtime.plugin.flush_failed',
1969
- severity: 'error',
1970
- attributes: expect.objectContaining({
1971
- plugin_id: 'flush-failure',
1972
- reason: 'shutdown',
1973
- error_code: 'RUNTIME_PLUGIN_FLUSH_FAILED',
1974
- }),
1975
- }));
1976
- });
1977
-
1978
- it('drains buffered parallel work in order when a failure pauses the plugin', async () => {
1979
- let releaseFirst!: () => void;
1980
- const firstGate = new Promise<void>((resolve) => { releaseFirst = resolve; });
1981
- const started: number[] = [];
1982
- const test = harness([{
1983
- kind: 'epoch',
1984
- id: 'parallel-pause',
1985
- version: '1',
1986
- maxInFlight: 3,
1987
- failurePolicy: 'pause',
1988
- async update(input) {
1989
- const epochSeq = input.epoch.epochSeq;
1990
- started.push(epochSeq);
1991
- if (epochSeq === 1) await firstGate;
1992
- if (epochSeq === 2) throw new Error('pause parallel work');
1993
- return { outcome: 'noop' };
1994
- },
1995
- }]);
1996
-
1997
- const completions = [test.scheduler.enqueue(test.work(1, { coalescing: 'forbidden' }))];
1998
- await vi.waitFor(() => expect(started).toEqual([1]));
1999
- for (let marker = 2; marker <= 4; marker += 1) {
2000
- completions.push(test.scheduler.enqueue(test.work(marker)));
2001
- }
2002
- await vi.waitFor(() => expect(started).toEqual([1, 2, 3]));
2003
- releaseFirst();
2004
-
2005
- const results = await Promise.all(completions);
2006
- expect(started).toEqual([1, 2, 3]);
2007
- expect(results.map((result) => result.outcomes[0]?.outcome)).toEqual([
2008
- 'noop',
2009
- 'failed',
2010
- 'failed',
2011
- 'failed',
2012
- ]);
2013
- expect(results[2].outcomes[0]?.reason).toBe('plugin_paused');
2014
- expect(results[3].outcomes[0]?.reason).toBe('plugin_paused');
2015
- expect(test.journal.pluginProgress('parallel-pause', scope).completedThroughEpochSeq).toBe(4);
2016
- await test.scheduler.close();
2017
- });
2018
-
2019
- it('rejects missing dependencies and dependency cycles at startup', () => {
2020
- const base = (id: string, after: string[] = []): RuntimeEpochPlugin => ({
2021
- kind: 'epoch', id, version: '1', after, update: () => ({ outcome: 'noop' }),
2022
- });
2023
- expect(() => harness([base('a', ['missing'])])).toThrow(/depends on missing/);
2024
- expect(() => harness([base('a', ['b']), base('b', ['a'])])).toThrow(/dependency cycle/);
2025
- expect(() => harness([{
2026
- ...base('a'), capabilities: { provides: ['shared.capability'] },
2027
- }, {
2028
- ...base('b'), capabilities: { provides: ['shared.capability'] },
2029
- }])).toThrow(/provided by both/);
2030
- expect(() => harness([{ ...base('invalid-concurrency'), maxInFlight: 0 }])).toThrow(
2031
- /maxInFlight must be an integer between 1 and 10/,
2032
- );
2033
- expect(() => harness([{ ...base('excessive-concurrency'), maxInFlight: 11 }])).toThrow(
2034
- /maxInFlight must be an integer between 1 and 10/,
2035
- );
2036
- expect(() => harness([base('invalid-catch-up')], { maxCatchUpEpochs: 11 })).toThrow(
2037
- /maxCatchUpEpochs must be an integer between 1 and 10/,
2038
- );
2039
- });
2040
- });