@myclaw163/clawclaw-cli 0.6.112 → 0.7.5

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 (422) hide show
  1. package/QUICKSTART.md +46 -0
  2. package/QUICKSTART_HERMES.md +134 -0
  3. package/QUICKSTART_OPENCLAW.md +134 -0
  4. package/QUICKSTART_OTHER.md +134 -0
  5. package/README.md +23 -398
  6. package/bin/clawclaw-cli.mjs +9 -1
  7. package/docs/configuration.md +197 -0
  8. package/docs/runtime/README.md +52 -0
  9. package/docs/runtime/agent-notifications.md +55 -0
  10. package/docs/runtime/components-and-boundaries.md +213 -0
  11. package/docs/runtime/events-and-state.md +105 -0
  12. package/docs/runtime/owner-lifecycle-and-observability.md +69 -0
  13. package/docs/runtime/perception-replay.md +51 -0
  14. package/docs/runtime/short-commands-and-capabilities.md +55 -0
  15. package/docs/runtime/strategy-runtime.md +111 -0
  16. package/docs//350/207/252/345/256/232/344/271/211/346/204/237/347/237/245.md +488 -0
  17. package/docs//350/207/252/345/256/232/344/271/211/347/255/226/347/225/245.md +395 -0
  18. package/package.json +26 -8
  19. package/scripts/check-skill-command-surface.mjs +16 -7
  20. package/scripts/compare-perception-replays.test.ts +188 -0
  21. package/scripts/compare-perception-replays.ts +589 -0
  22. package/scripts/generate-spatial-facts.py +246 -0
  23. package/scripts/package-readme.mjs +48 -0
  24. package/scripts/replay-perception.ts +347 -0
  25. package/scripts/sync-frontend-map.mjs +195 -0
  26. package/scripts/watch-perception-events.test.ts +43 -0
  27. package/scripts/watch-perception-events.ts +162 -0
  28. package/skills/clawclaw/SKILL.md +121 -65
  29. package/skills/clawclaw/references/CHATTERBOX.md +2 -4
  30. package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +1 -1
  31. package/skills/clawclaw/references/COMMANDS.md +95 -61
  32. package/skills/clawclaw/references/GAME-MECHANICS.md +19 -9
  33. package/skills/clawclaw/references/HUB.md +5 -5
  34. package/skills/clawclaw/references/STRATEGIES.md +34 -17
  35. package/skills/clawclaw/references/STREAM.md +82 -46
  36. package/src/assets/clawclaw-map.json +1692 -0
  37. package/src/assets/clawclaw-spatial-facts.json +1291 -0
  38. package/src/assets/clawclaw-spatial-model.txt +142 -0
  39. package/src/cli.ts +21 -47
  40. package/src/commands/account.test.ts +229 -50
  41. package/src/commands/account.ts +456 -223
  42. package/src/commands/communication.test.ts +259 -0
  43. package/src/commands/communication.ts +391 -0
  44. package/src/commands/competition.test.ts +116 -0
  45. package/src/commands/competition.ts +50 -28
  46. package/src/commands/data.test.ts +57 -1
  47. package/src/commands/data.ts +79 -4
  48. package/src/commands/events-canonical-state.test.ts +187 -0
  49. package/src/commands/events.test.ts +50 -136
  50. package/src/commands/events.ts +175 -241
  51. package/src/commands/game/index.test.ts +510 -0
  52. package/src/commands/game/index.ts +556 -0
  53. package/src/commands/game-map.test.ts +48 -7
  54. package/src/commands/hub.test.ts +2 -23
  55. package/src/commands/hub.ts +4 -16
  56. package/src/commands/load.test.ts +10 -22
  57. package/src/commands/load.ts +15 -2
  58. package/src/commands/peek.ts +2 -3
  59. package/src/commands/perception.test.ts +46 -0
  60. package/src/commands/perception.ts +92 -0
  61. package/src/commands/setup/codex.ts +0 -1
  62. package/src/commands/strategy.test.ts +139 -102
  63. package/src/commands/strategy.ts +175 -103
  64. package/src/commands/upgrade.ts +0 -21
  65. package/src/lib/auth.test.ts +35 -0
  66. package/src/lib/auth.ts +45 -6
  67. package/src/lib/diagnostics-config.test.ts +59 -0
  68. package/src/lib/diagnostics-config.ts +76 -0
  69. package/src/lib/game-client.test.ts +166 -0
  70. package/src/lib/game-client.ts +316 -87
  71. package/src/lib/game-context.ts +33 -4
  72. package/src/lib/gameplay-config.test.ts +66 -0
  73. package/src/lib/gameplay-config.ts +151 -0
  74. package/src/lib/http-transport.test.ts +63 -0
  75. package/src/lib/http-transport.ts +76 -10
  76. package/src/lib/init-command.test.ts +25 -1
  77. package/src/lib/init-command.ts +66 -1
  78. package/src/lib/participation-leave.ts +78 -0
  79. package/src/lib/perception-config.test.ts +138 -0
  80. package/src/lib/perception-config.ts +101 -0
  81. package/src/lib/room.test.ts +14 -0
  82. package/src/lib/room.ts +28 -2
  83. package/src/lib/server-registry.test.ts +15 -5
  84. package/src/lib/server-registry.ts +9 -10
  85. package/src/lib/strategy-export.test.ts +123 -44
  86. package/src/lib/strategy-export.ts +110 -81
  87. package/src/lib/user-data.test.ts +2 -0
  88. package/src/lib/user-data.ts +17 -16
  89. package/src/pipeline/canonical-event-presentation.test.ts +196 -0
  90. package/src/pipeline/canonical-event-presentation.ts +71 -0
  91. package/src/pipeline/event-format.test.ts +357 -59
  92. package/src/pipeline/event-format.ts +365 -80
  93. package/src/pipeline/event-hints.test.ts +241 -0
  94. package/src/pipeline/event-hints.ts +202 -51
  95. package/src/pipeline/game-sync-event-normalization.test.ts +239 -0
  96. package/src/pipeline/game-sync-event-normalization.ts +215 -0
  97. package/src/pipeline/player-projection.test.ts +164 -102
  98. package/src/pipeline/player-projection.ts +194 -235
  99. package/src/runtime/canonical-event-emitter.test.ts +70 -0
  100. package/src/runtime/canonical-event-emitter.ts +78 -0
  101. package/src/runtime/canonical-monitor.test.ts +575 -0
  102. package/src/runtime/canonical-monitor.ts +388 -0
  103. package/src/runtime/clawclaw/agent-event-policy.test.ts +27 -0
  104. package/src/runtime/clawclaw/agent-event-policy.ts +35 -0
  105. package/src/runtime/clawclaw/index.ts +4 -0
  106. package/src/runtime/clawclaw/notifications.test.ts +47 -0
  107. package/src/runtime/clawclaw/notifications.ts +65 -0
  108. package/src/runtime/clawclaw/owner-lock.test.ts +221 -0
  109. package/src/runtime/clawclaw/owner.ts +945 -0
  110. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +299 -0
  111. package/src/runtime/clawclaw/plugins/action/index.ts +1 -0
  112. package/src/runtime/clawclaw/plugins/assembly.test.ts +81 -0
  113. package/src/runtime/clawclaw/plugins/assembly.ts +116 -0
  114. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.test.ts +150 -0
  115. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +100 -0
  116. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +162 -0
  117. package/src/runtime/clawclaw/plugins/derived-event/index.ts +2 -0
  118. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.test.ts +223 -0
  119. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +236 -0
  120. package/src/runtime/clawclaw/plugins/game-query/index.ts +1 -0
  121. package/src/runtime/clawclaw/plugins/index.ts +7 -0
  122. package/src/runtime/clawclaw/plugins/mailbox/index.ts +3 -0
  123. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +77 -0
  124. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +91 -0
  125. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.test.ts +1008 -0
  126. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +475 -0
  127. package/src/runtime/clawclaw/plugins/perception/contracts.ts +32 -0
  128. package/src/runtime/clawclaw/plugins/perception/index.ts +8 -0
  129. package/src/runtime/clawclaw/plugins/perception/module-runner.test.ts +204 -0
  130. package/src/runtime/clawclaw/plugins/perception/module-runner.ts +290 -0
  131. package/src/runtime/clawclaw/plugins/perception/modules/co-movement-module.ts +324 -0
  132. package/src/runtime/clawclaw/plugins/perception/modules/follow-module.ts +365 -0
  133. package/src/runtime/clawclaw/plugins/perception/modules/index.ts +7 -0
  134. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.test.ts +341 -0
  135. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.ts +447 -0
  136. package/src/runtime/clawclaw/plugins/perception/modules/parallel-module-test-helpers.ts +30 -0
  137. package/src/runtime/clawclaw/plugins/perception/modules/relation-stability.test.ts +289 -0
  138. package/src/runtime/clawclaw/plugins/perception/modules/route-module.test.ts +180 -0
  139. package/src/runtime/clawclaw/plugins/perception/modules/route-module.ts +329 -0
  140. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.test.ts +82 -0
  141. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.ts +172 -0
  142. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.test.ts +212 -0
  143. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.ts +256 -0
  144. package/src/runtime/clawclaw/plugins/perception/modules/temporal-evidence.test.ts +121 -0
  145. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.test.ts +106 -0
  146. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.ts +225 -0
  147. package/src/runtime/clawclaw/plugins/perception/official-module-ids.ts +11 -0
  148. package/src/runtime/clawclaw/plugins/perception/official-modules.ts +31 -0
  149. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.test.ts +759 -0
  150. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +707 -0
  151. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +215 -0
  152. package/src/runtime/clawclaw/plugins/perception/perception-module-loader.ts +61 -0
  153. package/src/runtime/clawclaw/plugins/perception/perception-plugin.test.ts +1516 -0
  154. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1529 -0
  155. package/src/runtime/clawclaw/plugins/perception/perception-source.test.ts +119 -0
  156. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +244 -0
  157. package/src/runtime/clawclaw/plugins/perception/replay.test.ts +65 -0
  158. package/src/runtime/clawclaw/plugins/perception/replay.ts +86 -0
  159. package/src/runtime/clawclaw/plugins/perception/shared/math.ts +107 -0
  160. package/src/runtime/clawclaw/plugins/perception/spatial-facts.ts +114 -0
  161. package/src/runtime/clawclaw/plugins/perception/visual-state-projector.ts +98 -0
  162. package/src/runtime/clawclaw/plugins/runtime-plugins.test.ts +1019 -0
  163. package/src/runtime/clawclaw/plugins/source/game-transport.test.ts +287 -0
  164. package/src/runtime/clawclaw/plugins/source/game-transport.ts +281 -0
  165. package/src/runtime/clawclaw/plugins/source/index.ts +5 -0
  166. package/src/runtime/clawclaw/plugins/source/player-change-tracker.test.ts +270 -0
  167. package/src/runtime/clawclaw/plugins/source/player-change-tracker.ts +151 -0
  168. package/src/runtime/clawclaw/plugins/source/room-transport.test.ts +307 -0
  169. package/src/runtime/clawclaw/plugins/source/room-transport.ts +480 -0
  170. package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +1909 -0
  171. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +2055 -0
  172. package/src/runtime/clawclaw/plugins/source/source-transports.ts +30 -0
  173. package/src/runtime/clawclaw/plugins/source/types.ts +79 -0
  174. package/src/runtime/clawclaw/plugins/strategy/context-capabilities.ts +5 -0
  175. package/src/runtime/clawclaw/plugins/strategy/examples/task-only-strategy.test.ts +177 -0
  176. package/src/runtime/clawclaw/plugins/strategy/examples/task-only-strategy.ts +185 -0
  177. package/src/runtime/clawclaw/plugins/strategy/index.ts +8 -0
  178. package/src/runtime/clawclaw/plugins/strategy/local-strategy-executor.ts +412 -0
  179. package/src/runtime/clawclaw/plugins/strategy/strategy-action.ts +73 -0
  180. package/src/runtime/clawclaw/plugins/strategy/strategy-analysis-thread-host.ts +183 -0
  181. package/src/runtime/clawclaw/plugins/strategy/strategy-executor-types.ts +25 -0
  182. package/src/runtime/clawclaw/plugins/strategy/strategy-executor.test.ts +693 -0
  183. package/src/runtime/clawclaw/plugins/strategy/strategy-game-api.ts +57 -0
  184. package/src/runtime/clawclaw/plugins/strategy/strategy-module-loader.ts +164 -0
  185. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.test.ts +1936 -0
  186. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.ts +1557 -0
  187. package/src/runtime/clawclaw/plugins/strategy/strategy-source.test.ts +131 -0
  188. package/src/runtime/clawclaw/plugins/strategy/strategy-source.ts +413 -0
  189. package/src/runtime/clawclaw/plugins/strategy/thread-strategy-executor.ts +792 -0
  190. package/src/runtime/clawclaw/runtime-data-export.test.ts +249 -0
  191. package/src/runtime/clawclaw/runtime-data-export.ts +402 -0
  192. package/src/runtime/clawclaw/runtime-state.ts +98 -0
  193. package/src/runtime/clawclaw/runtime.ts +133 -0
  194. package/src/runtime/clawclaw-event-catalog.test.ts +74 -0
  195. package/src/runtime/clawclaw-event-catalog.ts +266 -0
  196. package/src/runtime/clawclaw-position.ts +4 -0
  197. package/src/runtime/clawclaw-room-state.ts +51 -0
  198. package/src/runtime/framework/action-diagnostics.test.ts +81 -0
  199. package/src/runtime/framework/action-diagnostics.ts +146 -0
  200. package/src/runtime/framework/capability-registry.test.ts +282 -0
  201. package/src/runtime/framework/capability-registry.ts +283 -0
  202. package/src/runtime/framework/contracts.ts +118 -0
  203. package/src/runtime/framework/control/control-scheduler.ts +1260 -0
  204. package/src/runtime/framework/control/domain-set.ts +81 -0
  205. package/src/runtime/framework/control/index.ts +3 -0
  206. package/src/runtime/framework/control/types.ts +184 -0
  207. package/src/runtime/framework/control-coordinator.test.ts +660 -0
  208. package/src/runtime/framework/control-coordinator.ts +11 -0
  209. package/src/runtime/framework/events/event-catalog.ts +74 -0
  210. package/src/runtime/framework/events/event-delivery-service.test.ts +84 -0
  211. package/src/runtime/framework/events/event-delivery-service.ts +198 -0
  212. package/src/runtime/framework/events/event-ingress.test.ts +178 -0
  213. package/src/runtime/framework/events/event-ingress.ts +97 -0
  214. package/src/runtime/framework/events/event-repository.ts +59 -0
  215. package/src/runtime/framework/events/index.ts +7 -0
  216. package/src/runtime/framework/events/mailbox-event-repositories.test.ts +594 -0
  217. package/src/runtime/framework/events/memory-event-repository.ts +928 -0
  218. package/src/runtime/framework/events/sqlite-event-repository.test.ts +200 -0
  219. package/src/runtime/framework/events/sqlite-event-repository.ts +1681 -0
  220. package/src/runtime/framework/events/test-helpers.ts +78 -0
  221. package/src/runtime/framework/events/types.ts +286 -0
  222. package/src/runtime/framework/index.ts +7 -0
  223. package/src/runtime/framework/load-node-sqlite.ts +17 -0
  224. package/src/runtime/framework/mailbox/coalescer.test.ts +55 -0
  225. package/src/runtime/framework/mailbox/coalescer.ts +83 -0
  226. package/src/runtime/framework/mailbox/host-notification-sink.ts +44 -0
  227. package/src/runtime/framework/mailbox/identity.test.ts +38 -0
  228. package/src/runtime/framework/mailbox/identity.ts +38 -0
  229. package/src/runtime/framework/mailbox/index.ts +7 -0
  230. package/src/runtime/framework/mailbox/mailbox-dispatcher.test.ts +513 -0
  231. package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +282 -0
  232. package/src/runtime/framework/mailbox/mailbox-repository.ts +44 -0
  233. package/src/runtime/framework/mailbox/notification-projector.test.ts +77 -0
  234. package/src/runtime/framework/mailbox/notification-projector.ts +65 -0
  235. package/src/runtime/framework/mailbox/types.ts +139 -0
  236. package/src/runtime/framework/modules/runtime-module-loader-hooks.d.mts +19 -0
  237. package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +117 -0
  238. package/src/runtime/framework/modules/runtime-module-loader.test.ts +209 -0
  239. package/src/runtime/framework/modules/runtime-module-loader.ts +71 -0
  240. package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +23 -0
  241. package/src/runtime/framework/participation-manager.test.ts +108 -0
  242. package/src/runtime/framework/participation-manager.ts +244 -0
  243. package/src/runtime/framework/plugins/contracts.ts +382 -0
  244. package/src/runtime/framework/plugins/index.ts +4 -0
  245. package/src/runtime/framework/plugins/runtime-event-identity.ts +17 -0
  246. package/src/runtime/framework/plugins/runtime-input-journal.test.ts +179 -0
  247. package/src/runtime/framework/plugins/runtime-input-journal.ts +693 -0
  248. package/src/runtime/framework/plugins/runtime-plugin-scheduler.test.ts +1994 -0
  249. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +1860 -0
  250. package/src/runtime/framework/runtime.ts +1756 -0
  251. package/src/runtime/framework/serial-task-queue.ts +14 -0
  252. package/src/runtime/framework/state/contracts.ts +49 -0
  253. package/src/runtime/framework/state/current-state-store.ts +184 -0
  254. package/src/runtime/framework/state/durable-agent-state-snapshot.test.ts +144 -0
  255. package/src/runtime/framework/state/durable-agent-state-snapshot.ts +209 -0
  256. package/src/runtime/framework/state/freshness.ts +72 -0
  257. package/src/runtime/framework/state/history/contracts.ts +150 -0
  258. package/src/runtime/framework/state/history/history-writer.ts +194 -0
  259. package/src/runtime/framework/state/history/memory-state-history-repository.ts +178 -0
  260. package/src/runtime/framework/state/history/sqlite-state-history-repository.test.ts +157 -0
  261. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +629 -0
  262. package/src/runtime/framework/state/history/state-history.test.ts +251 -0
  263. package/src/runtime/framework/state/history/trajectory-projector.ts +209 -0
  264. package/src/runtime/framework/state/index.ts +13 -0
  265. package/src/runtime/framework/state/state-core.test.ts +197 -0
  266. package/src/runtime/framework/state/state-ingress.ts +95 -0
  267. package/src/runtime/framework/state/state-provider.ts +62 -0
  268. package/src/runtime/framework/state/types.ts +155 -0
  269. package/src/runtime/game-sync-protocol.test.ts +123 -0
  270. package/src/runtime/game-sync-protocol.ts +261 -0
  271. package/src/runtime/mailbox-host-relay.test.ts +248 -0
  272. package/src/runtime/mailbox-host-relay.ts +300 -0
  273. package/src/runtime/observability/factory.ts +188 -0
  274. package/src/runtime/observability/index.ts +6 -0
  275. package/src/runtime/observability/observability.test.ts +561 -0
  276. package/src/runtime/observability/recorder.ts +209 -0
  277. package/src/runtime/observability/redaction.ts +154 -0
  278. package/src/runtime/observability/reporter.ts +154 -0
  279. package/src/runtime/observability/sinks.ts +135 -0
  280. package/src/runtime/observability/types.ts +92 -0
  281. package/src/runtime/owner-control.test.ts +153 -0
  282. package/src/runtime/owner-control.ts +206 -42
  283. package/src/runtime/parent-process-watch.test.ts +27 -0
  284. package/src/runtime/parent-process-watch.ts +51 -0
  285. package/src/runtime/pending-event-handoff.test.ts +29 -0
  286. package/src/runtime/pending-event-handoff.ts +61 -0
  287. package/src/runtime/raw-ws-log.test.ts +86 -17
  288. package/src/runtime/raw-ws-log.ts +230 -21
  289. package/src/runtime/runtime-logger.test.ts +58 -0
  290. package/src/runtime/runtime-logger.ts +10 -13
  291. package/src/runtime/runtime-persistence.test.ts +26 -0
  292. package/src/runtime/runtime.test.ts +1704 -0
  293. package/src/runtime/ws-client.test.ts +496 -103
  294. package/src/runtime/ws-client.ts +546 -166
  295. package/src/sdk/action.ts +3 -1
  296. package/src/sdk/index.ts +4 -19
  297. package/src/sdk/perception-plugin/index.test.ts +22 -0
  298. package/src/sdk/perception-plugin/index.ts +285 -0
  299. package/src/sdk/strategy-plugin/index.test.ts +952 -0
  300. package/src/sdk/strategy-plugin/index.ts +1324 -0
  301. package/src/sdk/types.ts +3 -1
  302. package/src/short-command/classifier.test.ts +107 -0
  303. package/src/short-command/classifier.ts +169 -0
  304. package/src/short-command/index.ts +7 -0
  305. package/src/short-command/presenter.test.ts +119 -0
  306. package/src/short-command/presenter.ts +308 -0
  307. package/src/short-command/process-io.ts +13 -0
  308. package/src/short-command/response-contract.ts +58 -0
  309. package/src/short-command/runner.test.ts +78 -0
  310. package/src/short-command/runner.ts +164 -0
  311. package/src/short-command/sensitive-data-filter.test.ts +56 -0
  312. package/src/short-command/sensitive-data-filter.ts +123 -0
  313. package/src/short-command/transport-response.test.ts +39 -0
  314. package/src/short-command/transport-response.ts +89 -0
  315. package/src/short-command/types.ts +92 -0
  316. package/src/strategies/avoid-lone.ts +18 -11
  317. package/src/strategies/avoid-players.ts +29 -13
  318. package/src/strategies/corpse-patrol.ts +29 -11
  319. package/src/strategies/crab-sabotage.ts +31 -18
  320. package/src/strategies/custom-module.test.ts +3 -5
  321. package/src/strategies/find-player.ts +34 -15
  322. package/src/strategies/game-utils.test.ts +42 -0
  323. package/src/strategies/game-utils.ts +143 -53
  324. package/src/strategies/goals/avoid-lone-top.ts +22 -1
  325. package/src/strategies/goals/avoid-players-top.test.ts +13 -0
  326. package/src/strategies/goals/avoid-players-top.ts +6 -5
  327. package/src/strategies/goals/corpse-patrol-top.ts +9 -2
  328. package/src/strategies/goals/crab-octopus-reflexes.ts +6 -2
  329. package/src/strategies/goals/crab-sabotage-top.ts +7 -1
  330. package/src/strategies/goals/emergency-hunt-goal.ts +15 -3
  331. package/src/strategies/goals/find-player-top.ts +47 -3
  332. package/src/strategies/goals/flee-players-goal.ts +2 -0
  333. package/src/strategies/goals/follow-companion-goal.ts +27 -3
  334. package/src/strategies/goals/hide-top.ts +47 -5
  335. package/src/strategies/goals/keep-away-goal.ts +24 -2
  336. package/src/strategies/goals/kill-frenzy-top.ts +12 -2
  337. package/src/strategies/goals/kill-lone-top.test.ts +72 -0
  338. package/src/strategies/goals/kill-lone-top.ts +8 -6
  339. package/src/strategies/goals/kill-target-goal.ts +16 -7
  340. package/src/strategies/goals/kill-target-top.ts +16 -2
  341. package/src/strategies/goals/linger-corpse-goal.ts +11 -3
  342. package/src/strategies/goals/lone-kill-core.ts +4 -2
  343. package/src/strategies/goals/move-room-goal.ts +46 -4
  344. package/src/strategies/goals/normal-shrimp-top.test.ts +16 -0
  345. package/src/strategies/goals/normal-shrimp-top.ts +18 -18
  346. package/src/strategies/goals/paradise-fish-top.test.ts +78 -0
  347. package/src/strategies/goals/paradise-fish-top.ts +16 -6
  348. package/src/strategies/goals/patrol-top.ts +14 -3
  349. package/src/strategies/goals/report-patrol-top.ts +14 -3
  350. package/src/strategies/goals/safe-task-goal.ts +32 -4
  351. package/src/strategies/goals/social-task-top.ts +39 -8
  352. package/src/strategies/goals/task-kill-report-top.ts +33 -10
  353. package/src/strategies/goals/task-only-top.test.ts +89 -0
  354. package/src/strategies/goals/task-only-top.ts +9 -2
  355. package/src/strategies/goals/task-or-patrol-goal.ts +21 -3
  356. package/src/strategies/goals/warrior-shrimp-top.test.ts +75 -23
  357. package/src/strategies/goals/warrior-shrimp-top.ts +34 -13
  358. package/src/strategies/greeting.ts +10 -3
  359. package/src/strategies/hide-spots.ts +4 -0
  360. package/src/strategies/hide.ts +35 -20
  361. package/src/strategies/kill-frenzy.ts +18 -12
  362. package/src/strategies/kill-lone.ts +43 -12
  363. package/src/strategies/kill-target.ts +34 -17
  364. package/src/strategies/lone-kill-task.ts +31 -18
  365. package/src/strategies/move-room.ts +32 -15
  366. package/src/strategies/off-route-points.ts +12 -4
  367. package/src/strategies/paradise-fish.ts +49 -14
  368. package/src/strategies/pathfind/astar-path.test.ts +73 -0
  369. package/src/strategies/pathfind/astar-path.ts +196 -0
  370. package/src/strategies/pathfind/escape-planner.test.ts +27 -1
  371. package/src/strategies/pathfind/escape-planner.ts +108 -0
  372. package/src/strategies/patrol.ts +18 -11
  373. package/src/strategies/report-patrol.ts +18 -11
  374. package/src/strategies/shrimp-memory.ts +66 -14
  375. package/src/strategies/social-task.ts +49 -45
  376. package/src/strategies/task-kill-report.ts +34 -16
  377. package/src/strategies/task-only.test.ts +124 -0
  378. package/src/strategies/task-only.ts +20 -11
  379. package/src/strategies/task-report.ts +29 -11
  380. package/src/strategies/types.ts +29 -62
  381. package/src/strategies/warrior-memory.ts +44 -14
  382. package/scripts/check_monitor.test.mjs +0 -212
  383. package/skills/clawclaw/references/KNOWLEDGE.md +0 -42
  384. package/src/assets/clawclaw-ascii-map.txt +0 -40
  385. package/src/commands/do.test.ts +0 -117
  386. package/src/commands/do.ts +0 -195
  387. package/src/commands/game-monitor-status.test.ts +0 -58
  388. package/src/commands/game-start-plan.test.ts +0 -356
  389. package/src/commands/game.ts +0 -2046
  390. package/src/commands/history-player.test.ts +0 -105
  391. package/src/commands/history.ts +0 -573
  392. package/src/commands/knowledge.test.ts +0 -13
  393. package/src/commands/knowledge.ts +0 -176
  394. package/src/commands/meeting-history.test.ts +0 -106
  395. package/src/commands/state.ts +0 -46
  396. package/src/commands/watch.test.ts +0 -1313
  397. package/src/commands/watch.ts +0 -824
  398. package/src/lib/knowledge-store.test.ts +0 -170
  399. package/src/lib/knowledge-store.ts +0 -369
  400. package/src/perception/player-history-store.test.ts +0 -177
  401. package/src/perception/player-history-store.ts +0 -262
  402. package/src/pipeline/event-store.test.ts +0 -28
  403. package/src/pipeline/event-store.ts +0 -193
  404. package/src/pipeline/pipeline.ts +0 -35
  405. package/src/runtime/event-daemon.test.ts +0 -268
  406. package/src/runtime/event-daemon.ts +0 -531
  407. package/src/runtime/room-lobby-runtime.test.ts +0 -95
  408. package/src/runtime/room-lobby-runtime.ts +0 -367
  409. package/src/strategies/avoid-players.knowledge.md +0 -19
  410. package/src/strategies/kill-lone.knowledge.md +0 -17
  411. package/src/strategies/knowledge-contract.ts +0 -85
  412. package/src/strategies/loader.test.ts +0 -710
  413. package/src/strategies/loader.ts +0 -183
  414. package/src/strategies/new-events-backfill.ts +0 -98
  415. package/src/strategies/paradise-fish.knowledge.md +0 -19
  416. package/src/strategies/scanner.ts +0 -238
  417. package/src/strategies/shrimp-memory.knowledge.md +0 -19
  418. package/src/strategies/social-task.test.ts +0 -28
  419. package/src/strategies/spawn.ts +0 -82
  420. package/src/strategies/strategy-loop.test.ts +0 -15
  421. package/src/strategies/strategy-loop.ts +0 -748
  422. package/src/strategies/warrior-memory.knowledge.md +0 -21
@@ -0,0 +1,1704 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { Runtime } from './framework/runtime.js';
3
+ import {
4
+ CLAWCLAW_GAME_WS_SOURCE,
5
+ CLAWCLAW_ROOM_WS_SOURCE,
6
+ } from './clawclaw/plugins/source/source-transports.js';
7
+ import type {
8
+ RuntimeInputBatch,
9
+ RuntimeSourceContext,
10
+ RuntimeSourcePlugin,
11
+ } from './framework/plugins/index.js';
12
+ import { MemoryRuntimeInputJournal } from './framework/plugins/index.js';
13
+ import { MemoryEventRepository } from './framework/events/index.js';
14
+ import {
15
+ MemoryStateHistoryRepository,
16
+ type StateHistoryRepository,
17
+ type TrajectoryRecord,
18
+ } from './framework/state/index.js';
19
+ import type { ClawclawPosition } from './clawclaw-position.js';
20
+ import { createClawclawEventCatalog } from './clawclaw-event-catalog.js';
21
+ import {
22
+ CLAWCLAW_GAME_LIVENESS_SILENCE_MS,
23
+ createClawclawRuntime,
24
+ } from './clawclaw/runtime.js';
25
+ import { projectClawclawCurrentState } from './clawclaw/runtime-state.js';
26
+ import { ClawclawMailboxService } from './clawclaw/plugins/mailbox/mailbox-service.js';
27
+
28
+ interface TestInputMeta {
29
+ connectionId: string;
30
+ receivedAt?: string;
31
+ sourceSeq?: number | string;
32
+ sourceEventId?: string;
33
+ delivery?: 'live' | 'replay';
34
+ observedAt?: string;
35
+ }
36
+
37
+ function testInputBatch(
38
+ scope: ReturnType<Runtime['scope']>,
39
+ source: { sourceId: string },
40
+ kind: 'state' | 'event',
41
+ payload: Record<string, any>,
42
+ meta: TestInputMeta,
43
+ ): RuntimeInputBatch<Record<string, any>, Record<string, unknown>> {
44
+ const receivedAt = meta.receivedAt ?? new Date().toISOString();
45
+ const sourceKey = meta.sourceEventId
46
+ ?? (meta.sourceSeq === undefined
47
+ ? `${kind}:${meta.connectionId}:${receivedAt}`
48
+ : `${kind}:${meta.connectionId}:${String(meta.sourceSeq)}`);
49
+ const { type, ...eventPayload } = payload;
50
+ return {
51
+ scope,
52
+ sourceId: source.sourceId,
53
+ connectionId: meta.connectionId,
54
+ sourceKey,
55
+ sourceSeq: meta.sourceSeq,
56
+ domainTick: kind === 'state' && typeof payload.tick === 'number' ? payload.tick : undefined,
57
+ state: kind === 'state'
58
+ ? payload
59
+ : {
60
+ schema: 'clawclaw.runtime-state.v1',
61
+ stage: 'game',
62
+ connection: 'connected',
63
+ cause: 'backend_event',
64
+ game_snapshot: { status: 'not_updated' },
65
+ },
66
+ events: kind === 'event'
67
+ ? [{
68
+ type,
69
+ payload: eventPayload,
70
+ sourceEventId: meta.sourceEventId,
71
+ sourceSeq: meta.sourceSeq,
72
+ observedAt: meta.observedAt,
73
+ receivedAt,
74
+ replayed: meta.delivery === 'replay',
75
+ }]
76
+ : [],
77
+ completeness: meta.delivery === 'replay' ? 'best_effort' : 'complete',
78
+ observedAt: meta.observedAt,
79
+ receivedAt,
80
+ };
81
+ }
82
+
83
+ function localEventInputBatch(
84
+ scope: ReturnType<Runtime['scope']>,
85
+ type: string,
86
+ payload: Record<string, unknown>,
87
+ sourceSeq: number,
88
+ ): RuntimeInputBatch<Record<string, any>, Record<string, unknown>> {
89
+ const receivedAt = new Date(1_000 + sourceSeq).toISOString();
90
+ return {
91
+ scope,
92
+ sourceId: 'test.local-source',
93
+ connectionId: 'test-local',
94
+ sourceKey: `local:${sourceSeq}:${type}`,
95
+ sourceSeq,
96
+ state: {
97
+ schema: 'clawclaw.runtime-state.v1',
98
+ stage: 'matching',
99
+ connection: 'disconnected',
100
+ cause: 'local_event',
101
+ game_snapshot: { status: 'unavailable' },
102
+ },
103
+ events: [{
104
+ type,
105
+ producer: 'local_synth',
106
+ payload,
107
+ sourceEventId: `local:${sourceSeq}:${type}`,
108
+ sourceSeq,
109
+ receivedAt,
110
+ }],
111
+ completeness: 'complete',
112
+ receivedAt,
113
+ };
114
+ }
115
+
116
+ async function submitTestInput(
117
+ runtime: Runtime,
118
+ batch: RuntimeInputBatch<Record<string, any>, Record<string, unknown>>,
119
+ ): Promise<void> {
120
+ await runtime.acceptInputBatch(batch);
121
+ await runtime.flush();
122
+ }
123
+
124
+ function createRuntime() {
125
+ const events = new MemoryEventRepository();
126
+ const history = new MemoryStateHistoryRepository<ClawclawPosition>();
127
+ const runtime = new Runtime({
128
+ adapterId: 'clawclaw',
129
+ accountId: 'account-1',
130
+ eventCatalog: createClawclawEventCatalog(),
131
+ eventRepository: events,
132
+ stateHistoryRepository: history,
133
+ currentStateFromRuntimeState: projectClawclawCurrentState,
134
+ initialSegment: { kind: 'queue' },
135
+ });
136
+ return { runtime, events, history };
137
+ }
138
+
139
+ class FailingStateHistoryRepository implements StateHistoryRepository<ClawclawPosition> {
140
+ readonly inner = new MemoryStateHistoryRepository<ClawclawPosition>();
141
+ fail = true;
142
+
143
+ openScope = this.inner.openScope.bind(this.inner);
144
+ sealScope = this.inner.sealScope.bind(this.inner);
145
+ markScopeIncomplete = this.inner.markScopeIncomplete.bind(this.inner);
146
+ getScope = this.inner.getScope.bind(this.inner);
147
+ appendStateFrame = this.inner.appendStateFrame.bind(this.inner);
148
+ queryStateFrames = this.inner.queryStateFrames.bind(this.inner);
149
+ latestStateFrame = this.inner.latestStateFrame.bind(this.inner);
150
+ query = this.inner.query.bind(this.inner);
151
+
152
+ append(records: TrajectoryRecord<ClawclawPosition>[]) {
153
+ if (this.fail) throw new Error('disk unavailable');
154
+ return this.inner.append(records);
155
+ }
156
+ }
157
+
158
+ describe('Runtime', () => {
159
+ it('loads Source and Epoch plugins through the two game-neutral plugin boundaries', async () => {
160
+ const processedEpochs: number[] = [];
161
+ let sourceContext: RuntimeSourceContext | null = null;
162
+ let sourceStops = 0;
163
+ const runtime = new Runtime({
164
+ adapterId: 'test-game',
165
+ accountId: 'test-account',
166
+ eventCatalog: createClawclawEventCatalog(),
167
+ eventRepository: new MemoryEventRepository(),
168
+ stateHistoryRepository: new MemoryStateHistoryRepository(),
169
+ runtimeEpochPlugins: [{
170
+ kind: 'epoch',
171
+ id: 'test.epoch',
172
+ version: '1',
173
+ update(input) {
174
+ processedEpochs.push(input.epoch.epochSeq);
175
+ return { outcome: 'noop', reason: 'framework_test' };
176
+ },
177
+ }],
178
+ initialSegment: { kind: 'test' },
179
+ });
180
+ const source: RuntimeSourcePlugin = {
181
+ kind: 'source',
182
+ id: 'test.source',
183
+ version: '1',
184
+ start(context) {
185
+ sourceContext = context;
186
+ return { stop: () => { sourceStops += 1; } };
187
+ },
188
+ };
189
+
190
+ await runtime.startSourcePlugin(source);
191
+ expect(runtime.runtimePluginDescriptors()).toEqual([
192
+ { kind: 'source', id: 'test.source', version: '1' },
193
+ expect.objectContaining({ kind: 'epoch', id: 'test.epoch', version: '1' }),
194
+ ]);
195
+ await expect(runtime.startSourcePlugin(source)).rejects.toThrow(
196
+ 'Duplicate Runtime Source Plugin id: test.source',
197
+ );
198
+ await sourceContext!.acceptInputBatch({
199
+ scope: runtime.scope(),
200
+ sourceId: 'test.source',
201
+ connectionId: 'test-input',
202
+ sourceKey: 'message-1',
203
+ state: { stage: 'test' },
204
+ events: [],
205
+ completeness: 'complete',
206
+ receivedAt: new Date(100).toISOString(),
207
+ });
208
+ await runtime.flush();
209
+
210
+ expect(processedEpochs).toEqual([1]);
211
+ await runtime.close();
212
+ expect(sourceStops).toBe(1);
213
+ });
214
+
215
+ it('drains a Source terminal InputBatch as its own epoch before shutdown', async () => {
216
+ const events = new MemoryEventRepository();
217
+ let lifecycleFlushes = 0;
218
+ const runtime = new Runtime({
219
+ adapterId: 'test-game',
220
+ accountId: 'terminal-account',
221
+ eventCatalog: createClawclawEventCatalog(),
222
+ eventRepository: events,
223
+ stateHistoryRepository: new MemoryStateHistoryRepository(),
224
+ runtimeEpochPlugins: [{
225
+ kind: 'epoch',
226
+ id: 'test.terminal-producer',
227
+ version: '1',
228
+ produces: { states: ['terminal.state'], events: ['strategy_alert'] },
229
+ update(input) {
230
+ if (input.epoch.state.stage !== 'ended') return { outcome: 'noop' };
231
+ return {
232
+ outcome: 'processed',
233
+ states: [{ topic: 'terminal.state', value: { closed: true } }],
234
+ events: [{
235
+ type: 'strategy_alert',
236
+ dedupeKey: 'terminal',
237
+ payload: { closed: true },
238
+ }],
239
+ };
240
+ },
241
+ flush() {
242
+ lifecycleFlushes += 1;
243
+ },
244
+ }],
245
+ initialSegment: { kind: 'test' },
246
+ });
247
+ let sourceContext: RuntimeSourceContext | null = null;
248
+ await runtime.startSourcePlugin({
249
+ kind: 'source',
250
+ id: 'test.source',
251
+ version: '1',
252
+ start(context) {
253
+ sourceContext = context;
254
+ return {
255
+ stop: async () => {
256
+ await context.acceptInputBatch({
257
+ scope: context.currentSegment().scope,
258
+ sourceId: 'test.source',
259
+ connectionId: 'terminal-control',
260
+ sourceKey: 'terminal-message',
261
+ state: { stage: 'ended' },
262
+ events: [],
263
+ completeness: 'complete',
264
+ receivedAt: new Date(100).toISOString(),
265
+ });
266
+ },
267
+ };
268
+ },
269
+ });
270
+ const scope = runtime.scope();
271
+
272
+ await runtime.close();
273
+
274
+ expect(runtime.inputJournal.epoch(1)?.state).toEqual({ stage: 'ended' });
275
+ expect(runtime.inputJournal.pluginRecords(1)).toMatchObject([{
276
+ epochSeq: 1,
277
+ pluginId: 'test.terminal-producer',
278
+ outcome: 'processed',
279
+ stateCount: 1,
280
+ eventCount: 1,
281
+ }]);
282
+ expect(runtime.inputJournal.states(1)).toMatchObject([{
283
+ epochSeq: 1,
284
+ pluginId: 'test.terminal-producer',
285
+ topic: 'terminal.state',
286
+ }]);
287
+ expect(events.listCommittedEvents({
288
+ sessionId: scope.sessionId,
289
+ segmentId: scope.segmentId,
290
+ types: ['strategy_alert'],
291
+ })).toMatchObject([{
292
+ epochSeq: 1,
293
+ producerPluginId: 'test.terminal-producer',
294
+ producerOutputIndex: 0,
295
+ }]);
296
+ expect(lifecycleFlushes).toBe(1);
297
+ await expect(sourceContext!.acceptInputBatch({
298
+ scope,
299
+ sourceId: 'test.source',
300
+ connectionId: 'late',
301
+ sourceKey: 'late-message',
302
+ state: { stage: 'late' },
303
+ events: [],
304
+ completeness: 'complete',
305
+ receivedAt: new Date(200).toISOString(),
306
+ })).rejects.toThrow('Runtime input is closed.');
307
+ });
308
+
309
+ it('stays idle until a Source submits another InputBatch', async () => {
310
+ const events = new MemoryEventRepository();
311
+ let lifecycleFlushes = 0;
312
+ const runtime = new Runtime({
313
+ adapterId: 'clawclaw',
314
+ accountId: 'account-1',
315
+ eventCatalog: createClawclawEventCatalog(),
316
+ eventRepository: events,
317
+ stateHistoryRepository: new MemoryStateHistoryRepository(),
318
+ runtimeEpochPlugins: [{
319
+ kind: 'epoch',
320
+ id: 'periodic-test',
321
+ version: '1',
322
+ produces: { events: ['visual.player_moved'] },
323
+ update(input) {
324
+ if (input.epoch.state.cause !== 'max_latency') {
325
+ return { outcome: 'noop', reason: 'waiting_for_source_input' };
326
+ }
327
+ return {
328
+ outcome: 'processed',
329
+ events: [{
330
+ type: 'visual.player_moved',
331
+ dedupeKey: 'source-timer:1',
332
+ payload: { from_tick: 1, to_tick: 2, status: 'ongoing', text: 'moving' },
333
+ }],
334
+ };
335
+ },
336
+ flush() {
337
+ lifecycleFlushes += 1;
338
+ },
339
+ }],
340
+ initialSegment: { kind: 'game', identity: 'game-1' },
341
+ });
342
+ const scope = runtime.scope();
343
+ await runtime.acceptInputBatch({
344
+ scope,
345
+ sourceId: 'test.source',
346
+ connectionId: 'test-connection',
347
+ sourceKey: 'test-input-1',
348
+ state: { phase: 'wandering' },
349
+ events: [],
350
+ completeness: 'complete',
351
+ receivedAt: new Date(100).toISOString(),
352
+ });
353
+ await runtime.flush();
354
+ await new Promise((resolve) => setTimeout(resolve, 20));
355
+ expect(lifecycleFlushes).toBe(0);
356
+ expect(events.listCommittedEvents({
357
+ sessionId: scope.sessionId,
358
+ segmentId: scope.segmentId,
359
+ types: ['visual.player_moved'],
360
+ })).toHaveLength(0);
361
+
362
+ await runtime.acceptInputBatch({
363
+ scope,
364
+ sourceId: 'test.source',
365
+ connectionId: 'test-connection',
366
+ sourceKey: 'source-timer-1',
367
+ state: { cause: 'max_latency' },
368
+ events: [],
369
+ completeness: 'complete',
370
+ receivedAt: new Date(200).toISOString(),
371
+ });
372
+ await runtime.flush();
373
+ expect(events.listCommittedEvents({
374
+ sessionId: scope.sessionId,
375
+ segmentId: scope.segmentId,
376
+ types: ['visual.player_moved'],
377
+ })).toHaveLength(1);
378
+ await runtime.close();
379
+ });
380
+
381
+ it('exposes active history writer degradation and logs only health transitions', async () => {
382
+ const history = new FailingStateHistoryRepository();
383
+ const log = vi.fn();
384
+ const runtime = new Runtime<ClawclawPosition>({
385
+ adapterId: 'clawclaw',
386
+ accountId: 'account-1',
387
+ eventCatalog: createClawclawEventCatalog(),
388
+ eventRepository: new MemoryEventRepository(),
389
+ stateHistoryRepository: history,
390
+ historyObserverFactory: (writer) => ({
391
+ onFrameAccepted(frame) {
392
+ writer.enqueue([{
393
+ recordId: `position-${frame.sourceKey}`,
394
+ scope: frame.scope,
395
+ connectionId: frame.connectionId,
396
+ subjectId: 'self',
397
+ subjectKind: 'self',
398
+ kind: 'position',
399
+ sourceType: 'backend_state',
400
+ sourceKey: frame.sourceKey,
401
+ receivedAtMs: frame.receivedAtMs,
402
+ position: { x: 1, y: 2 },
403
+ }]);
404
+ },
405
+ }),
406
+ observability: {
407
+ log,
408
+ error: vi.fn(),
409
+ flushWithin: vi.fn(async () => true),
410
+ } as any,
411
+ initialSegment: { kind: 'game', identity: 'game-1' },
412
+ });
413
+ const scope = runtime.scope();
414
+ runtime.bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, 'history-ws');
415
+ const ingest = (tick: number) => submitTestInput(runtime, testInputBatch(
416
+ scope,
417
+ CLAWCLAW_GAME_WS_SOURCE,
418
+ 'state',
419
+ { tick },
420
+ { connectionId: 'history-ws', sourceSeq: tick },
421
+ ));
422
+
423
+ await ingest(1);
424
+ await runtime.flush();
425
+ expect(runtime.persistence.historyWriter).toMatchObject({
426
+ status: 'degraded',
427
+ queueDepth: 1,
428
+ degradedScopes: [{
429
+ scope: {
430
+ adapterId: 'clawclaw',
431
+ sessionId: scope.sessionId,
432
+ segmentId: scope.segmentId,
433
+ },
434
+ queueDepth: 1,
435
+ droppedRecordCount: 0,
436
+ reason: 'disk unavailable',
437
+ }],
438
+ });
439
+ expect(JSON.stringify(runtime.persistence.historyWriter)).not.toContain('account-1');
440
+ const healthLogs = () => log.mock.calls.filter(
441
+ (call) => call[1] === 'runtime.state_history.writer_health_changed',
442
+ );
443
+ expect(healthLogs()).toHaveLength(1);
444
+ expect(healthLogs()[0][0]).toBe('warn');
445
+ expect(healthLogs()[0][2]).toMatchObject({ status: 'degraded', queue_depth: 1 });
446
+
447
+ await ingest(2);
448
+ await runtime.flush();
449
+ expect(healthLogs()).toHaveLength(1);
450
+
451
+ history.fail = false;
452
+ await runtime.flush();
453
+ expect(runtime.persistence.historyWriter).toMatchObject({
454
+ status: 'healthy',
455
+ queueDepth: 0,
456
+ degradedScopes: [],
457
+ });
458
+ expect(healthLogs()).toHaveLength(2);
459
+ expect(healthLogs()[1][0]).toBe('info');
460
+ expect(healthLogs()[1][2]).toMatchObject({ status: 'healthy', queue_depth: 0 });
461
+ await runtime.close();
462
+ });
463
+
464
+ it('routes State and backend Events into separate planes', async () => {
465
+ const { runtime, events } = createRuntime();
466
+ const scope = runtime.scope();
467
+ const connectionId = 'game-ws-1';
468
+ runtime.bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, connectionId, 1_000);
469
+
470
+ await submitTestInput(runtime, testInputBatch(
471
+ scope,
472
+ CLAWCLAW_GAME_WS_SOURCE,
473
+ 'state',
474
+ { tick: 7, phase: 'wandering', you: { name: 'A', x: 1, y: 2, is_alive: true } },
475
+ { connectionId, sourceSeq: 7, receivedAt: new Date(1_100).toISOString() },
476
+ ));
477
+ await submitTestInput(runtime, testInputBatch(
478
+ scope,
479
+ CLAWCLAW_GAME_WS_SOURCE,
480
+ 'event',
481
+ { type: 'task_completed', task_name: 'wires', hint: 'backend hint', next_step: 'backend step' },
482
+ { connectionId, sourceSeq: 8, receivedAt: new Date(1_200).toISOString() },
483
+ ));
484
+
485
+ expect(runtime.readState(1_300)).toMatchObject({
486
+ state: { tick: 7, phase: 'wandering', you: { name: 'A', is_alive: true } },
487
+ stateStatus: { status: 'fresh', semantics: 'latest_received' },
488
+ });
489
+ const current = events.currentScope({ adapterId: 'clawclaw', accountId: 'account-1' });
490
+ expect(current).not.toBeNull();
491
+ const row = events.latestEventByType(current!.session.sessionId, 'task_completed');
492
+ expect(row?.payload).toEqual({ task_name: 'wires' });
493
+ await runtime.close();
494
+ });
495
+
496
+ it('seals durable Event and State scopes whenever the local Owner Runtime closes', async () => {
497
+ const { runtime, events, history } = createRuntime();
498
+ const scope = runtime.scope();
499
+
500
+ expect(events.currentScope({ adapterId: 'clawclaw', accountId: 'account-1' }))
501
+ .toMatchObject({
502
+ session: { status: 'open', isCurrent: true },
503
+ segment: { status: 'open', isCurrent: true },
504
+ });
505
+ expect(history.getScope(scope)).toMatchObject({ status: 'OPEN', sealedAtMs: null });
506
+
507
+ await runtime.close();
508
+
509
+ expect(events.currentScope({ adapterId: 'clawclaw', accountId: 'account-1' })).toBeNull();
510
+ expect(events.latestScope({ adapterId: 'clawclaw', accountId: 'account-1' }))
511
+ .toMatchObject({
512
+ session: { status: 'sealed', isCurrent: false },
513
+ segment: { status: 'closed', isCurrent: false },
514
+ });
515
+ expect(history.getScope(scope)).toMatchObject({ status: 'SEALED' });
516
+ });
517
+
518
+ it('starts a new local session when backend status resumes the same game after Owner shutdown', async () => {
519
+ const events = new MemoryEventRepository();
520
+ const history = new MemoryStateHistoryRepository<ClawclawPosition>();
521
+ const options = {
522
+ adapterId: 'clawclaw',
523
+ accountId: 'account-1',
524
+ eventCatalog: createClawclawEventCatalog(),
525
+ eventRepository: events,
526
+ stateHistoryRepository: history,
527
+ currentStateFromRuntimeState: projectClawclawCurrentState,
528
+ initialSegment: { kind: 'game', identity: 'game-1' },
529
+ resume: true,
530
+ resumeKey: 'game-1',
531
+ } as const;
532
+ const first = new Runtime(options);
533
+ const firstScope = first.scope();
534
+
535
+ await first.close();
536
+
537
+ expect(events.latestScope({ adapterId: 'clawclaw', accountId: 'account-1' }))
538
+ .toMatchObject({
539
+ session: { sessionId: firstScope.sessionId, status: 'sealed', isCurrent: false },
540
+ segment: { segmentId: firstScope.segmentId, status: 'closed', isCurrent: false },
541
+ });
542
+ const resumed = new Runtime(options);
543
+ const resumedScope = resumed.scope();
544
+
545
+ expect(resumedScope.sessionId).not.toBe(firstScope.sessionId);
546
+ expect(resumedScope.segmentId).not.toBe(firstScope.segmentId);
547
+ expect(events.currentScope({ adapterId: 'clawclaw', accountId: 'account-1' }))
548
+ .toMatchObject({
549
+ session: { sessionId: resumedScope.sessionId, resumeKey: 'game-1', status: 'open' },
550
+ segment: { segmentId: resumedScope.segmentId, scopeRef: 'game-1', status: 'open' },
551
+ });
552
+
553
+ await resumed.close();
554
+ });
555
+
556
+ it('still seals the local participation when another shutdown operation fails', async () => {
557
+ const { runtime, events, history } = createRuntime();
558
+ const scope = runtime.scope();
559
+ await runtime.startSourcePlugin({
560
+ kind: 'source',
561
+ id: 'test.failing-stop-source',
562
+ version: '1',
563
+ start: () => ({
564
+ stop: () => { throw new Error('source stop failed'); },
565
+ }),
566
+ });
567
+ await expect(runtime.close()).rejects.toThrow('Runtime shutdown operation');
568
+ expect(events.currentScope({ adapterId: 'clawclaw', accountId: 'account-1' })).toBeNull();
569
+ expect(events.latestScope({ adapterId: 'clawclaw', accountId: 'account-1' }))
570
+ .toMatchObject({
571
+ session: { status: 'sealed', isCurrent: false },
572
+ segment: { status: 'closed', isCurrent: false },
573
+ });
574
+ expect(history.getScope(scope)).toMatchObject({ status: 'SEALED' });
575
+ });
576
+
577
+ it('reads a bounded incremental strategy feed in the repository', async () => {
578
+ const { runtime, events } = createRuntime();
579
+ const scope = runtime.scope();
580
+ await submitTestInput(runtime, localEventInputBatch(scope, 'joined', { ordinal: 1 }, 1));
581
+ await submitTestInput(runtime, localEventInputBatch(scope, 'joined', { ordinal: 2 }, 2));
582
+ await submitTestInput(runtime, localEventInputBatch(scope, 'joined', { ordinal: 3 }, 3));
583
+ const list = vi.spyOn(events, 'listCommittedEvents');
584
+
585
+ const feed = runtime.readReadyView(1, 1);
586
+
587
+ expect(feed.events.map((event) => event.payload.ordinal)).toEqual([2]);
588
+ expect(feed.throughCommitSeq).toBe(2);
589
+ expect(feed.hasMore).toBe(true);
590
+ expect(list).toHaveBeenCalledWith(expect.objectContaining({
591
+ afterCommitSeq: 1,
592
+ limit: 2,
593
+ order: 'asc',
594
+ }));
595
+ await runtime.close();
596
+ });
597
+
598
+ it('publishes a finalized State and Event watermark only after its plugin epoch', async () => {
599
+ let release!: () => void;
600
+ const gate = new Promise<void>((resolve) => { release = resolve; });
601
+ const events = new MemoryEventRepository();
602
+ const runtime = new Runtime({
603
+ adapterId: 'clawclaw',
604
+ accountId: 'account-1',
605
+ eventCatalog: createClawclawEventCatalog(),
606
+ eventRepository: events,
607
+ stateHistoryRepository: new MemoryStateHistoryRepository(),
608
+ runtimeEpochPlugins: [{
609
+ kind: 'epoch',
610
+ id: 'delayed',
611
+ version: '1',
612
+ produces: { events: ['strategy_alert'] },
613
+ async update(input) {
614
+ await gate;
615
+ return {
616
+ outcome: 'processed',
617
+ events: [{
618
+ type: 'strategy_alert',
619
+ dedupeKey: input.frame.sourceKey,
620
+ payload: { tick: input.frame.backendTick },
621
+ }],
622
+ };
623
+ },
624
+ }],
625
+ currentStateFromRuntimeState: (state) => state,
626
+ initialSegment: { kind: 'game', identity: 'game-1' },
627
+ });
628
+ const scope = runtime.scope();
629
+ const ingest = runtime.acceptInputBatch({
630
+ scope,
631
+ sourceId: CLAWCLAW_GAME_WS_SOURCE.sourceId,
632
+ connectionId: 'ws',
633
+ sourceKey: 'state:1',
634
+ sourceSeq: 1,
635
+ domainTick: 1,
636
+ state: { tick: 1, phase: 'wandering' },
637
+ events: [],
638
+ completeness: 'complete',
639
+ receivedAt: new Date(100).toISOString(),
640
+ });
641
+
642
+ expect(runtime.readReadyView()).toMatchObject({
643
+ frameSeq: 0,
644
+ eventWatermark: 0,
645
+ state: { state: null },
646
+ events: [],
647
+ });
648
+ release();
649
+ await ingest;
650
+ await runtime.flush();
651
+ expect(runtime.readReadyView()).toMatchObject({
652
+ frameSeq: 1,
653
+ eventWatermark: 1,
654
+ state: { state: { tick: 1 } },
655
+ events: [{ type: 'strategy_alert', payload: { tick: 1 } }],
656
+ });
657
+ await runtime.close();
658
+ });
659
+
660
+ it('returns the immutable Ready View for one exact closed epoch', async () => {
661
+ const runtime = new Runtime({
662
+ adapterId: 'clawclaw',
663
+ accountId: 'account-1',
664
+ eventCatalog: createClawclawEventCatalog(),
665
+ eventRepository: new MemoryEventRepository(),
666
+ stateHistoryRepository: new MemoryStateHistoryRepository(),
667
+ currentStateFromRuntimeState: (state) => state,
668
+ initialSegment: { kind: 'game', identity: 'game-1' },
669
+ });
670
+ const scope = runtime.scope();
671
+ const first = await runtime.acceptInputBatch({
672
+ scope,
673
+ sourceId: CLAWCLAW_GAME_WS_SOURCE.sourceId,
674
+ connectionId: 'ws',
675
+ sourceKey: 'exact:1',
676
+ state: { tick: 1 },
677
+ events: [{ type: 'role_assigned', payload: { role: 'shrimp_generic' } }],
678
+ completeness: 'complete',
679
+ receivedAt: new Date(100).toISOString(),
680
+ });
681
+ await runtime.acceptInputBatch({
682
+ scope,
683
+ sourceId: CLAWCLAW_GAME_WS_SOURCE.sourceId,
684
+ connectionId: 'ws',
685
+ sourceKey: 'exact:2',
686
+ state: { tick: 2 },
687
+ events: [{ type: 'speech', payload: { actor_name: '2', text: 'later' } }],
688
+ completeness: 'complete',
689
+ receivedAt: new Date(200).toISOString(),
690
+ });
691
+
692
+ const exact = await runtime.waitForEpochReadyView(first.epoch.epochSeq);
693
+ await runtime.flush();
694
+ expect(exact).toMatchObject({
695
+ epochSeq: first.epoch.epochSeq,
696
+ state: { state: { tick: 1 } },
697
+ events: [{ type: 'role_assigned' }],
698
+ eventWatermark: 1,
699
+ });
700
+ expect(runtime.readReadyView()).toMatchObject({
701
+ epochSeq: 2,
702
+ state: { state: { tick: 2 } },
703
+ events: [{ type: 'role_assigned' }, { type: 'speech' }],
704
+ eventWatermark: 2,
705
+ });
706
+ await runtime.close();
707
+ });
708
+
709
+ it('carries the latest plugin State across noop epochs within one Ready View scope', async () => {
710
+ let updateCount = 0;
711
+ const runtime = new Runtime({
712
+ adapterId: 'clawclaw',
713
+ accountId: 'account-1',
714
+ eventCatalog: createClawclawEventCatalog(),
715
+ eventRepository: new MemoryEventRepository(),
716
+ stateHistoryRepository: new MemoryStateHistoryRepository(),
717
+ currentStateFromRuntimeState: (state) => state,
718
+ runtimeEpochPlugins: [{
719
+ kind: 'epoch',
720
+ id: 'clawclaw.strategy',
721
+ version: '1',
722
+ produces: { states: ['strategy.status'] },
723
+ update() {
724
+ updateCount += 1;
725
+ if (updateCount > 1) {
726
+ return { outcome: 'noop', reason: 'strategy_update_interval' };
727
+ }
728
+ return {
729
+ outcome: 'processed',
730
+ states: [{
731
+ topic: 'strategy.status',
732
+ value: { activity: 'moving', summary: 'Going to engine.' },
733
+ }],
734
+ };
735
+ },
736
+ }],
737
+ initialSegment: { kind: 'game', identity: 'game-1' },
738
+ });
739
+ const scope = runtime.scope();
740
+ const first = await runtime.acceptInputBatch({
741
+ scope,
742
+ sourceId: CLAWCLAW_GAME_WS_SOURCE.sourceId,
743
+ connectionId: 'ws',
744
+ sourceKey: 'plugin-state:1',
745
+ sourceSeq: 1,
746
+ domainTick: 100,
747
+ state: { tick: 100, phase: 'wandering' },
748
+ events: [],
749
+ completeness: 'complete',
750
+ receivedAt: new Date(100).toISOString(),
751
+ });
752
+ await runtime.acceptInputBatch({
753
+ scope,
754
+ sourceId: CLAWCLAW_GAME_WS_SOURCE.sourceId,
755
+ connectionId: 'ws',
756
+ sourceKey: 'plugin-state:2',
757
+ sourceSeq: 2,
758
+ domainTick: 105,
759
+ state: { tick: 105, phase: 'wandering' },
760
+ events: [],
761
+ completeness: 'complete',
762
+ receivedAt: new Date(200).toISOString(),
763
+ });
764
+ await runtime.flush();
765
+
766
+ const firstReady = await runtime.waitForEpochReadyView(first.epoch.epochSeq);
767
+ expect(firstReady.pluginStates['strategy.status']).toMatchObject({
768
+ pluginId: 'clawclaw.strategy',
769
+ value: { activity: 'moving', summary: 'Going to engine.' },
770
+ updatedEpochSeq: 1,
771
+ updatedDomainTick: 100,
772
+ });
773
+ expect(firstReady.pluginOutcomes['clawclaw.strategy']).toMatchObject({
774
+ epochSeq: 1,
775
+ domainTick: 100,
776
+ outcome: 'processed',
777
+ });
778
+
779
+ const current = runtime.readReadyView();
780
+ expect(current.pluginStates['strategy.status']).toMatchObject({
781
+ updatedEpochSeq: 1,
782
+ updatedDomainTick: 100,
783
+ value: { activity: 'moving' },
784
+ });
785
+ expect(current.pluginOutcomes['clawclaw.strategy']).toMatchObject({
786
+ epochSeq: 2,
787
+ domainTick: 105,
788
+ outcome: 'noop',
789
+ reason: 'strategy_update_interval',
790
+ });
791
+ await runtime.activateSegment('game', 'game-2');
792
+ expect(runtime.readReadyView()).toMatchObject({
793
+ epochSeq: 0,
794
+ pluginStates: {},
795
+ pluginOutcomes: {},
796
+ });
797
+ await runtime.close();
798
+ });
799
+
800
+ it('never exposes an older segment as the Ready View of a newly activated segment', async () => {
801
+ let release!: () => void;
802
+ const gate = new Promise<void>((resolve) => { release = resolve; });
803
+ const runtime = new Runtime({
804
+ adapterId: 'clawclaw',
805
+ accountId: 'account-1',
806
+ eventCatalog: createClawclawEventCatalog(),
807
+ eventRepository: new MemoryEventRepository(),
808
+ stateHistoryRepository: new MemoryStateHistoryRepository(),
809
+ runtimeEpochPlugins: [{
810
+ kind: 'epoch',
811
+ id: 'delayed-segment-plugin',
812
+ version: '1',
813
+ async update() {
814
+ await gate;
815
+ return { outcome: 'noop' };
816
+ },
817
+ }],
818
+ currentStateFromRuntimeState: (state) => state,
819
+ initialSegment: { kind: 'game', identity: 'game-1' },
820
+ });
821
+ const firstScope = runtime.scope();
822
+ await runtime.acceptInputBatch({
823
+ scope: firstScope,
824
+ sourceId: CLAWCLAW_GAME_WS_SOURCE.sourceId,
825
+ connectionId: 'ws-1',
826
+ sourceKey: 'first-segment',
827
+ sourceSeq: 1,
828
+ state: { marker: 'first' },
829
+ events: [{
830
+ type: 'speech',
831
+ payload: { actor_name: '2号', text: 'first' },
832
+ sourceEventId: 'first-segment-event',
833
+ sourceSeq: 1,
834
+ }],
835
+ completeness: 'complete',
836
+ receivedAt: new Date(100).toISOString(),
837
+ });
838
+
839
+ release();
840
+ const secondScope = await runtime.activateSegment('game', 'game-2');
841
+ await runtime.acceptInputBatch({
842
+ scope: secondScope,
843
+ sourceId: CLAWCLAW_GAME_WS_SOURCE.sourceId,
844
+ connectionId: 'ws-2',
845
+ sourceKey: 'second-segment',
846
+ sourceSeq: 1,
847
+ state: { marker: 'second' },
848
+ events: [{
849
+ type: 'role_assigned',
850
+ payload: { role: 'shrimp_generic' },
851
+ sourceEventId: 'second-segment-event',
852
+ sourceSeq: 1,
853
+ }],
854
+ completeness: 'complete',
855
+ receivedAt: new Date(200).toISOString(),
856
+ });
857
+
858
+ expect(runtime.readReadyView()).toMatchObject({
859
+ scope: { segmentId: secondScope.segmentId },
860
+ epochSeq: 0,
861
+ frameSeq: 0,
862
+ state: { state: null },
863
+ events: [],
864
+ });
865
+ await runtime.flush();
866
+ expect(runtime.readReadyView()).toMatchObject({
867
+ scope: { segmentId: secondScope.segmentId },
868
+ epochSeq: 2,
869
+ eventWatermark: 2,
870
+ state: { state: { marker: 'second' } },
871
+ });
872
+ await runtime.close();
873
+ });
874
+
875
+ it('keeps an unknown backend fact but raises a catalog coverage alarm', async () => {
876
+ const events = new MemoryEventRepository();
877
+ const log = vi.fn();
878
+ const runtime = new Runtime({
879
+ adapterId: 'clawclaw',
880
+ accountId: 'account-1',
881
+ eventCatalog: createClawclawEventCatalog(),
882
+ eventRepository: events,
883
+ stateHistoryRepository: new MemoryStateHistoryRepository<ClawclawPosition>(),
884
+ initialSegment: { kind: 'game', identity: 'game-1' },
885
+ observability: {
886
+ log,
887
+ error: vi.fn(),
888
+ flushWithin: vi.fn(async () => true),
889
+ } as any,
890
+ });
891
+ const scope = runtime.scope();
892
+ runtime.bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, 'unknown-event-ws');
893
+
894
+ await submitTestInput(runtime, testInputBatch(
895
+ scope,
896
+ CLAWCLAW_GAME_WS_SOURCE,
897
+ 'event',
898
+ { type: 'future_backend_fact', value: 7 },
899
+ { connectionId: 'unknown-event-ws', sourceEventId: 'future-1' },
900
+ ));
901
+
902
+ expect(events.latestEventByType(scope.sessionId, 'future_backend_fact', scope.segmentId))
903
+ .toMatchObject({ producer: 'backend_push', deliveryClass: 'internal_only' });
904
+ expect(log).toHaveBeenCalledWith(
905
+ 'warn',
906
+ 'runtime.backend_event.unregistered',
907
+ expect.objectContaining({
908
+ event_type: 'future_backend_fact',
909
+ source_id: CLAWCLAW_GAME_WS_SOURCE.sourceId,
910
+ }),
911
+ expect.objectContaining({ component: 'runtime.event-catalog' }),
912
+ );
913
+ await runtime.close();
914
+ });
915
+
916
+ it('runs an Event-consuming Epoch Plugin only after its input Event commits', async () => {
917
+ const events = new MemoryEventRepository();
918
+ const runtime = new Runtime({
919
+ adapterId: 'clawclaw',
920
+ accountId: 'account-1',
921
+ eventCatalog: createClawclawEventCatalog(),
922
+ eventRepository: events,
923
+ stateHistoryRepository: new MemoryStateHistoryRepository<ClawclawPosition>(),
924
+ runtimeEpochPlugins: [{
925
+ kind: 'epoch',
926
+ id: 'test.task-followup',
927
+ version: '1',
928
+ consumes: { events: ['task_completed'] },
929
+ produces: { events: ['strategy_alert'] },
930
+ update(input) {
931
+ const event = input.epochEvents.find((candidate) => candidate.type === 'task_completed');
932
+ if (!event) return { outcome: 'noop', reason: 'no_task_completed' };
933
+ return {
934
+ outcome: 'processed',
935
+ events: [{
936
+ type: 'strategy_alert',
937
+ dedupeKey: `task:${event.eventId}`,
938
+ payload: { input_commit_seq: event.commitSeq },
939
+ }],
940
+ consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)?.commitSeq,
941
+ };
942
+ },
943
+ }],
944
+ initialSegment: { kind: 'game', identity: 'game-1' },
945
+ });
946
+ const scope = runtime.scope();
947
+ runtime.bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, 'game-ws-1');
948
+
949
+ await submitTestInput(runtime, testInputBatch(
950
+ scope,
951
+ CLAWCLAW_GAME_WS_SOURCE,
952
+ 'event',
953
+ { type: 'task_completed', task_name: 'wires' },
954
+ {
955
+ connectionId: 'game-ws-1',
956
+ sourceSeq: 1,
957
+ sourceEventId: 'backend-task-1',
958
+ },
959
+ ));
960
+
961
+ expect(events.listCommittedEvents({
962
+ sessionId: scope.sessionId,
963
+ segmentId: scope.segmentId,
964
+ order: 'asc',
965
+ }).map((event) => [event.type, event.commitSeq])).toEqual([
966
+ ['task_completed', 1],
967
+ ['strategy_alert', 2],
968
+ ]);
969
+ expect(runtime.runtimeEpochPluginDescriptors()).toMatchObject([{
970
+ id: 'test.task-followup',
971
+ produces: { events: ['strategy_alert'] },
972
+ }]);
973
+ await runtime.close();
974
+ });
975
+
976
+ it('allows multiple Epoch Plugins to produce the same Event topic', async () => {
977
+ const events = new MemoryEventRepository();
978
+ const runtime = new Runtime({
979
+ adapterId: 'clawclaw',
980
+ accountId: 'account-1',
981
+ eventCatalog: createClawclawEventCatalog(),
982
+ eventRepository: events,
983
+ stateHistoryRepository: new MemoryStateHistoryRepository<ClawclawPosition>(),
984
+ runtimeEpochPlugins: ['first', 'second'].map((id) => ({
985
+ kind: 'epoch' as const,
986
+ id: `test.${id}`,
987
+ version: '1',
988
+ produces: { events: ['strategy_alert'] },
989
+ update: (input: any) => ({
990
+ outcome: 'processed' as const,
991
+ events: [{
992
+ type: 'strategy_alert',
993
+ dedupeKey: `${id}:${input.epoch.epochSeq}`,
994
+ payload: { producer: id },
995
+ }],
996
+ }),
997
+ })),
998
+ initialSegment: { kind: 'game', identity: 'game-1' },
999
+ });
1000
+
1001
+ await submitTestInput(runtime, testInputBatch(
1002
+ runtime.scope(),
1003
+ CLAWCLAW_GAME_WS_SOURCE,
1004
+ 'state',
1005
+ { tick: 1, phase: 'wandering' },
1006
+ { connectionId: 'same-topic', sourceSeq: 1 },
1007
+ ));
1008
+
1009
+ const produced = events.listCommittedEvents({
1010
+ sessionId: runtime.scope().sessionId,
1011
+ segmentId: runtime.scope().segmentId,
1012
+ types: ['strategy_alert'],
1013
+ order: 'asc',
1014
+ });
1015
+ expect(produced.map((event) => event.payload.producer)).toEqual(['first', 'second']);
1016
+ expect(produced.map((event) => [event.producerPluginId, event.producerOutputIndex]))
1017
+ .toEqual([['test.first', 0], ['test.second', 0]]);
1018
+ await runtime.close();
1019
+ });
1020
+
1021
+ it('passes the invocation epoch through plugin capability calls', async () => {
1022
+ const inputJournal = new MemoryRuntimeInputJournal();
1023
+ let releaseConsumer!: () => void;
1024
+ let markConsumerStarted!: () => void;
1025
+ const consumerGate = new Promise<void>((resolve) => { releaseConsumer = resolve; });
1026
+ const consumerStarted = new Promise<void>((resolve) => { markConsumerStarted = resolve; });
1027
+ const seen: Array<{ invocationEpoch: number; capabilityEpoch: number | undefined }> = [];
1028
+ let unregister: (() => void) | undefined;
1029
+ const runtime = new Runtime({
1030
+ adapterId: 'clawclaw',
1031
+ accountId: 'account-capability-epoch',
1032
+ eventCatalog: createClawclawEventCatalog(),
1033
+ eventRepository: new MemoryEventRepository(),
1034
+ stateHistoryRepository: new MemoryStateHistoryRepository<ClawclawPosition>(),
1035
+ inputJournal,
1036
+ runtimeEpochPlugins: [{
1037
+ kind: 'epoch',
1038
+ id: 'test.capability-provider',
1039
+ version: '1',
1040
+ capabilities: { provides: ['test.epoch'] },
1041
+ start(context) {
1042
+ unregister = context.capabilities.provideObservation({
1043
+ capability: 'test.epoch',
1044
+ query: async (_request, queryScope, queryContext) => ({
1045
+ scope: queryScope,
1046
+ capability: 'test.epoch',
1047
+ receivedAt: new Date().toISOString(),
1048
+ freshness: 'fresh',
1049
+ value: { epochSeq: queryContext.epochSeq },
1050
+ }),
1051
+ });
1052
+ },
1053
+ update: () => ({ outcome: 'noop' }),
1054
+ stop: () => unregister?.(),
1055
+ }, {
1056
+ kind: 'epoch',
1057
+ id: 'test.capability-consumer',
1058
+ version: '1',
1059
+ after: ['test.capability-provider'],
1060
+ capabilities: { uses: ['test.epoch'] },
1061
+ async update(input, context) {
1062
+ if (input.epoch.epochSeq === 1) {
1063
+ markConsumerStarted();
1064
+ await consumerGate;
1065
+ }
1066
+ const observed = await context.capabilities.queryObservation<unknown, { epochSeq?: number }>(
1067
+ 'test.epoch',
1068
+ {},
1069
+ );
1070
+ seen.push({
1071
+ invocationEpoch: input.epoch.epochSeq,
1072
+ capabilityEpoch: observed.value.epochSeq,
1073
+ });
1074
+ return { outcome: 'noop' };
1075
+ },
1076
+ }],
1077
+ initialSegment: { kind: 'game', identity: 'capability-epoch' },
1078
+ });
1079
+ const scope = runtime.scope();
1080
+
1081
+ await runtime.acceptInputBatch(testInputBatch(
1082
+ scope,
1083
+ CLAWCLAW_GAME_WS_SOURCE,
1084
+ 'state',
1085
+ { tick: 1, phase: 'wandering' },
1086
+ { connectionId: 'capability-ws', sourceSeq: 1 },
1087
+ ));
1088
+ await consumerStarted;
1089
+ await runtime.acceptInputBatch(testInputBatch(
1090
+ scope,
1091
+ CLAWCLAW_GAME_WS_SOURCE,
1092
+ 'state',
1093
+ { tick: 2, phase: 'wandering' },
1094
+ { connectionId: 'capability-ws', sourceSeq: 2 },
1095
+ ));
1096
+ await vi.waitFor(() => expect(
1097
+ inputJournal.pluginProgress('test.capability-provider', scope).completedThroughEpochSeq,
1098
+ ).toBe(2));
1099
+ releaseConsumer();
1100
+ await runtime.flush();
1101
+
1102
+ expect(seen).toEqual([
1103
+ { invocationEpoch: 1, capabilityEpoch: 1 },
1104
+ { invocationEpoch: 2, capabilityEpoch: 2 },
1105
+ ]);
1106
+ await runtime.close();
1107
+ });
1108
+
1109
+ it('serializes concurrent backend ingress so derived facts follow commit order', async () => {
1110
+ const events = new MemoryEventRepository();
1111
+ let releaseFirst!: () => void;
1112
+ let markFirstObserved!: () => void;
1113
+ const firstBlocked = new Promise<void>((resolve) => { releaseFirst = resolve; });
1114
+ const firstObserved = new Promise<void>((resolve) => { markFirstObserved = resolve; });
1115
+ const runtime = new Runtime({
1116
+ adapterId: 'clawclaw',
1117
+ accountId: 'account-1',
1118
+ eventCatalog: createClawclawEventCatalog(),
1119
+ eventRepository: events,
1120
+ stateHistoryRepository: new MemoryStateHistoryRepository<ClawclawPosition>(),
1121
+ runtimeEpochPlugins: [{
1122
+ kind: 'epoch',
1123
+ id: 'test.concurrent-task-followup',
1124
+ version: '1',
1125
+ consumes: { events: ['task_completed'] },
1126
+ produces: { events: ['strategy_alert'] },
1127
+ async update(input) {
1128
+ const event = input.epochEvents.find((candidate) => candidate.type === 'task_completed');
1129
+ if (!event) return { outcome: 'noop', reason: 'no_task_completed' };
1130
+ if (event.payload.order === 1) {
1131
+ markFirstObserved();
1132
+ await firstBlocked;
1133
+ }
1134
+ return {
1135
+ outcome: 'processed',
1136
+ events: [{
1137
+ type: 'strategy_alert',
1138
+ dedupeKey: `task:${event.eventId}`,
1139
+ payload: { input_order: event.payload.order },
1140
+ }],
1141
+ consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)?.commitSeq,
1142
+ };
1143
+ },
1144
+ }],
1145
+ initialSegment: { kind: 'game', identity: 'game-concurrent' },
1146
+ });
1147
+ const scope = runtime.scope();
1148
+ runtime.bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, 'concurrent-ws');
1149
+ const first = submitTestInput(runtime, testInputBatch(
1150
+ scope,
1151
+ CLAWCLAW_GAME_WS_SOURCE,
1152
+ 'event',
1153
+ { type: 'task_completed', order: 1 },
1154
+ { connectionId: 'concurrent-ws', sourceSeq: 1, sourceEventId: 'task-1' },
1155
+ ));
1156
+ await firstObserved;
1157
+ const second = submitTestInput(runtime, testInputBatch(
1158
+ scope,
1159
+ CLAWCLAW_GAME_WS_SOURCE,
1160
+ 'event',
1161
+ { type: 'task_completed', order: 2 },
1162
+ { connectionId: 'concurrent-ws', sourceSeq: 2, sourceEventId: 'task-2' },
1163
+ ));
1164
+
1165
+ expect(events.listCommittedEvents({
1166
+ sessionId: scope.sessionId,
1167
+ segmentId: scope.segmentId,
1168
+ order: 'asc',
1169
+ }).map((event) => [event.type, event.payload.order ?? event.payload.input_order]))
1170
+ .toEqual([
1171
+ ['task_completed', 1],
1172
+ ]);
1173
+ releaseFirst();
1174
+ await Promise.all([first, second]);
1175
+
1176
+ expect(events.listCommittedEvents({
1177
+ sessionId: scope.sessionId,
1178
+ segmentId: scope.segmentId,
1179
+ order: 'asc',
1180
+ }).map((event) => [event.type, event.payload.order ?? event.payload.input_order]))
1181
+ .toEqual([
1182
+ ['task_completed', 1],
1183
+ ['strategy_alert', 1],
1184
+ ['task_completed', 2],
1185
+ ['strategy_alert', 2],
1186
+ ]);
1187
+ await runtime.close();
1188
+ });
1189
+
1190
+ it('lets a plugin consume durable pending Events on the next epoch after restart', async () => {
1191
+ const events = new MemoryEventRepository();
1192
+ const history = new MemoryStateHistoryRepository<ClawclawPosition>();
1193
+ const baseOptions = {
1194
+ adapterId: 'clawclaw',
1195
+ accountId: 'account-1',
1196
+ eventCatalog: createClawclawEventCatalog(),
1197
+ eventRepository: events,
1198
+ stateHistoryRepository: history,
1199
+ resumeKey: 'game-recovery-1',
1200
+ initialSegment: { kind: 'game', identity: 'game-recovery-1' },
1201
+ } as const;
1202
+ const crashedOwner = new Runtime(baseOptions);
1203
+ const originalScope = crashedOwner.scope();
1204
+ crashedOwner.bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, 'before-crash');
1205
+ await submitTestInput(crashedOwner, testInputBatch(
1206
+ originalScope,
1207
+ CLAWCLAW_GAME_WS_SOURCE,
1208
+ 'event',
1209
+ { type: 'task_completed', task_name: 'wires' },
1210
+ {
1211
+ connectionId: 'before-crash',
1212
+ sourceSeq: 7,
1213
+ sourceEventId: 'backend-before-crash',
1214
+ },
1215
+ ));
1216
+
1217
+ const resumed = new Runtime({
1218
+ ...baseOptions,
1219
+ resume: true,
1220
+ runtimeEpochPlugins: [{
1221
+ kind: 'epoch',
1222
+ id: 'test.recovered-task-followup',
1223
+ version: '1',
1224
+ consumes: { events: ['task_completed'] },
1225
+ produces: { events: ['strategy_alert'] },
1226
+ update(input) {
1227
+ const proposals = input.pendingEvents.map((event) => ({
1228
+ type: 'strategy_alert',
1229
+ dedupeKey: `task:${event.eventId}`,
1230
+ payload: { recovered_input_commit_seq: event.commitSeq },
1231
+ }));
1232
+ return proposals.length === 0
1233
+ ? { outcome: 'noop', reason: 'no_pending_task' }
1234
+ : {
1235
+ outcome: 'processed',
1236
+ events: proposals,
1237
+ consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq,
1238
+ };
1239
+ },
1240
+ }],
1241
+ });
1242
+ expect(resumed.scope()).toMatchObject(originalScope);
1243
+
1244
+ resumed.bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, 'after-crash');
1245
+ await submitTestInput(resumed, testInputBatch(
1246
+ resumed.scope(),
1247
+ CLAWCLAW_GAME_WS_SOURCE,
1248
+ 'event',
1249
+ { type: 'task_completed', task_name: 'wires' },
1250
+ {
1251
+ connectionId: 'after-crash',
1252
+ sourceSeq: 7,
1253
+ sourceEventId: 'backend-before-crash',
1254
+ delivery: 'replay',
1255
+ },
1256
+ ));
1257
+ expect(events.listCommittedEvents({
1258
+ sessionId: originalScope.sessionId,
1259
+ segmentId: originalScope.segmentId,
1260
+ types: ['task_completed'],
1261
+ })).toHaveLength(1);
1262
+ expect(events.listCommittedEvents({
1263
+ sessionId: originalScope.sessionId,
1264
+ segmentId: originalScope.segmentId,
1265
+ types: ['strategy_alert'],
1266
+ })).toHaveLength(1);
1267
+
1268
+ await resumed.close();
1269
+ await crashedOwner.close();
1270
+ });
1271
+
1272
+ it('requeues accepted but unclosed epochs through the normal bounded scheduler on startup', async () => {
1273
+ const events = new MemoryEventRepository();
1274
+ const history = new MemoryStateHistoryRepository<ClawclawPosition>();
1275
+ const inputJournal = new MemoryRuntimeInputJournal();
1276
+ const baseOptions = {
1277
+ adapterId: 'clawclaw',
1278
+ accountId: 'account-recover-open',
1279
+ eventCatalog: createClawclawEventCatalog(),
1280
+ eventRepository: events,
1281
+ stateHistoryRepository: history,
1282
+ inputJournal,
1283
+ resumeKey: 'game-open-epoch',
1284
+ initialSegment: { kind: 'game', identity: 'game-open-epoch' },
1285
+ } as const;
1286
+ const interrupted = new Runtime(baseOptions);
1287
+ const scope = interrupted.scope();
1288
+ const accepted = inputJournal.accept({
1289
+ scope,
1290
+ sourceId: 'test.source',
1291
+ connectionId: 'connection-before-crash',
1292
+ sourceKey: 'accepted-before-crash',
1293
+ sourceSeq: 1,
1294
+ state: { marker: 'recover-me' },
1295
+ events: [],
1296
+ completeness: 'complete',
1297
+ receivedAt: '2026-07-22T00:00:00.000Z',
1298
+ }).epoch;
1299
+ history.appendStateFrame({
1300
+ epochSeq: accepted.epochSeq,
1301
+ scope,
1302
+ sourceId: accepted.sourceId,
1303
+ connectionId: accepted.connectionId,
1304
+ sourceKey: `runtime-epoch:${accepted.epochSeq}`,
1305
+ sourceSeq: accepted.sourceSeq,
1306
+ receivedAtMs: Date.parse(accepted.receivedAt),
1307
+ state: accepted.state,
1308
+ });
1309
+ const processed: number[] = [];
1310
+ const resumed = new Runtime({
1311
+ ...baseOptions,
1312
+ resume: true,
1313
+ runtimeEpochPlugins: [{
1314
+ kind: 'epoch',
1315
+ id: 'test.recover-open-epoch',
1316
+ version: '1',
1317
+ update(input) {
1318
+ processed.push(input.epoch.epochSeq);
1319
+ return { outcome: 'noop', reason: 'recovered' };
1320
+ },
1321
+ }],
1322
+ });
1323
+
1324
+ await resumed.start();
1325
+
1326
+ expect(processed).toEqual([accepted.epochSeq]);
1327
+ expect(inputJournal.listOpen(scope)).toEqual([]);
1328
+ expect(inputJournal.pluginProgress('test.recover-open-epoch', scope)).toMatchObject({
1329
+ completedThroughEpochSeq: accepted.epochSeq,
1330
+ });
1331
+ expect(resumed.readReadyView()).toMatchObject({
1332
+ epochSeq: accepted.epochSeq,
1333
+ state: { state: { marker: 'recover-me' } },
1334
+ });
1335
+ await resumed.close();
1336
+ await interrupted.close();
1337
+ });
1338
+
1339
+ it('retries unconsumed pending Events when a later epoch runs after plugin failure', async () => {
1340
+ const events = new MemoryEventRepository();
1341
+ let failFirst = true;
1342
+ const runtime = new Runtime({
1343
+ adapterId: 'clawclaw',
1344
+ accountId: 'account-1',
1345
+ eventCatalog: createClawclawEventCatalog(),
1346
+ eventRepository: events,
1347
+ stateHistoryRepository: new MemoryStateHistoryRepository<ClawclawPosition>(),
1348
+ initialSegment: { kind: 'game', identity: 'game-retry' },
1349
+ runtimeEpochPlugins: [{
1350
+ kind: 'epoch',
1351
+ id: 'test.retry-pending-events',
1352
+ version: '1',
1353
+ consumes: { events: ['task_completed'] },
1354
+ produces: { events: ['strategy_alert'] },
1355
+ update(input) {
1356
+ if (input.pendingEvents.length === 0) return { outcome: 'noop', reason: 'no_pending_task' };
1357
+ if (failFirst) {
1358
+ failFirst = false;
1359
+ throw new Error('temporary plugin failure');
1360
+ }
1361
+ return {
1362
+ outcome: 'processed',
1363
+ events: input.pendingEvents.map((event) => ({
1364
+ type: 'strategy_alert',
1365
+ dedupeKey: `task:${event.eventId}`,
1366
+ payload: { input_order: event.payload.order },
1367
+ })),
1368
+ consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq,
1369
+ };
1370
+ },
1371
+ }],
1372
+ });
1373
+ const scope = runtime.scope();
1374
+ const connectionId = 'plugin-retry-ws';
1375
+ runtime.bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, connectionId);
1376
+
1377
+ await submitTestInput(runtime, testInputBatch(
1378
+ scope,
1379
+ CLAWCLAW_GAME_WS_SOURCE,
1380
+ 'event',
1381
+ { type: 'task_completed', order: 1 },
1382
+ { connectionId, sourceEventId: 'retry-input-1', sourceSeq: 1 },
1383
+ ));
1384
+ expect(events.listCommittedEvents({
1385
+ sessionId: scope.sessionId,
1386
+ segmentId: scope.segmentId,
1387
+ types: ['strategy_alert'],
1388
+ })).toEqual([]);
1389
+
1390
+ await submitTestInput(runtime, testInputBatch(
1391
+ scope,
1392
+ CLAWCLAW_GAME_WS_SOURCE,
1393
+ 'event',
1394
+ { type: 'task_completed', order: 2 },
1395
+ { connectionId, sourceEventId: 'retry-input-2', sourceSeq: 2 },
1396
+ ));
1397
+ expect(events.listCommittedEvents({
1398
+ sessionId: scope.sessionId,
1399
+ segmentId: scope.segmentId,
1400
+ types: ['strategy_alert'],
1401
+ order: 'asc',
1402
+ }).map((event) => event.payload.input_order)).toEqual([1, 2]);
1403
+ await runtime.close();
1404
+ });
1405
+
1406
+ it('does not infer or load ClawClaw business plugins in the runtime factory', async () => {
1407
+ const events = new MemoryEventRepository();
1408
+ const runtime = createClawclawRuntime({
1409
+ apiKey: 'producer-key',
1410
+ runtimeAccountId: 'acct_bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
1411
+ }, {
1412
+ eventRepository: events,
1413
+ stateHistoryRepository: new MemoryStateHistoryRepository<ClawclawPosition>(),
1414
+ durableStateSnapshot: false,
1415
+ initialSegment: { kind: 'room_lobby', identity: 'R2' },
1416
+ });
1417
+ expect(runtime.runtimeEpochPluginDescriptors()).toEqual([]);
1418
+ expect(runtime.runtimePluginDescriptors()).toEqual([]);
1419
+ expect(events.latestEventByType(runtime.scope().sessionId, 'room_ready_to_start'))
1420
+ .toBeNull();
1421
+
1422
+ await runtime.close();
1423
+ });
1424
+
1425
+ it('resumes logical participation without restoring a physical connection', async () => {
1426
+ const events = new MemoryEventRepository();
1427
+ const history = new MemoryStateHistoryRepository<ClawclawPosition>();
1428
+ const first = new Runtime({
1429
+ adapterId: 'clawclaw',
1430
+ accountId: 'account-1',
1431
+ eventCatalog: createClawclawEventCatalog(),
1432
+ eventRepository: events,
1433
+ stateHistoryRepository: history,
1434
+ resumeKey: 'room-A',
1435
+ initialSegment: { kind: 'room_lobby', identity: 'room-A' },
1436
+ });
1437
+ const firstScope = first.scope();
1438
+ first.bindConnection('clawclaw.room-ws', 'old-connection');
1439
+ await first.flush();
1440
+
1441
+ const resumed = new Runtime({
1442
+ adapterId: 'clawclaw',
1443
+ accountId: 'account-1',
1444
+ eventCatalog: createClawclawEventCatalog(),
1445
+ eventRepository: events,
1446
+ stateHistoryRepository: history,
1447
+ resume: true,
1448
+ resumeKey: 'room-A',
1449
+ initialSegment: { kind: 'room_lobby', identity: 'room-A' },
1450
+ });
1451
+ expect(resumed.scope()).toMatchObject({
1452
+ sessionId: firstScope.sessionId,
1453
+ segmentId: firstScope.segmentId,
1454
+ });
1455
+ expect(resumed.readState().stateStatus).toMatchObject({
1456
+ status: 'unavailable',
1457
+ connectionId: null,
1458
+ });
1459
+ expect(history.getScope(resumed.scope())?.historyComplete).toBe(false);
1460
+ resumed.bindConnection('clawclaw.room-ws', 'new-connection');
1461
+ await resumed.flush();
1462
+ expect(history.query({ scope: resumed.scope(), limit: 20 }).records).toMatchObject([
1463
+ { kind: 'stream_gap_started', attributes: { reason: 'owner_restart' } },
1464
+ { kind: 'stream_gap_ended', connectionId: 'new-connection', attributes: { reason: 'owner_restart' } },
1465
+ ]);
1466
+ await first.close();
1467
+ await resumed.close();
1468
+ });
1469
+
1470
+ it('resumes an unsealed room game by current game id and keeps unread Events queryable', async () => {
1471
+ const events = new MemoryEventRepository();
1472
+ const history = new MemoryStateHistoryRepository<ClawclawPosition>();
1473
+ const first = new Runtime({
1474
+ adapterId: 'clawclaw',
1475
+ accountId: 'account-room-game-restart',
1476
+ eventCatalog: createClawclawEventCatalog(),
1477
+ eventRepository: events,
1478
+ stateHistoryRepository: history,
1479
+ resumeKey: 'room-A',
1480
+ initialSegment: { kind: 'room', identity: 'room-A' },
1481
+ });
1482
+ await first.activateSegment('game', 'game-A1');
1483
+ const originalScope = first.scope();
1484
+ first.bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, 'before-owner-restart');
1485
+ await submitTestInput(first, testInputBatch(
1486
+ originalScope,
1487
+ CLAWCLAW_GAME_WS_SOURCE,
1488
+ 'event',
1489
+ { type: 'task_completed', task_name: 'wires' },
1490
+ {
1491
+ connectionId: 'before-owner-restart',
1492
+ sourceSeq: 1,
1493
+ sourceEventId: 'unread-before-owner-restart',
1494
+ },
1495
+ ));
1496
+ const resumed = new Runtime({
1497
+ adapterId: 'clawclaw',
1498
+ accountId: 'account-room-game-restart',
1499
+ eventCatalog: createClawclawEventCatalog(),
1500
+ eventRepository: events,
1501
+ stateHistoryRepository: history,
1502
+ resume: true,
1503
+ // Lobby /queue/status omits room_code while a room game is allocated.
1504
+ // The authoritative game id therefore matches the current game segment.
1505
+ initialSegment: { kind: 'game', identity: 'game-A1' },
1506
+ });
1507
+ expect(resumed.scope()).toMatchObject(originalScope);
1508
+
1509
+ resumed.bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, 'after-owner-restart');
1510
+ await submitTestInput(resumed, testInputBatch(
1511
+ resumed.scope(),
1512
+ CLAWCLAW_GAME_WS_SOURCE,
1513
+ 'state',
1514
+ { tick: 2, phase: 'wandering' },
1515
+ { connectionId: 'after-owner-restart', sourceSeq: 2 },
1516
+ ));
1517
+ const mailbox = new ClawclawMailboxService({
1518
+ repository: events,
1519
+ readyView: () => resumed.readReadyView(),
1520
+ });
1521
+ expect(mailbox.prepareEvents({ eventType: 'task_completed' }).output.event)
1522
+ .toMatchObject({ type: 'task_completed', task_name: 'wires' });
1523
+
1524
+ await first.close();
1525
+ await resumed.close();
1526
+ });
1527
+
1528
+ it('persists an adopted authoritative resume key and mode, then resumes only an exact match', async () => {
1529
+ const events = new MemoryEventRepository();
1530
+ const history = new MemoryStateHistoryRepository<ClawclawPosition>();
1531
+ const first = new Runtime({
1532
+ adapterId: 'clawclaw',
1533
+ accountId: 'account-1',
1534
+ eventCatalog: createClawclawEventCatalog(),
1535
+ eventRepository: events,
1536
+ stateHistoryRepository: history,
1537
+ mode: 'match',
1538
+ initialSegment: { kind: 'queue' },
1539
+ });
1540
+ first.adoptResumeKey('game-1');
1541
+ await first.activateSegment('game', 'game-1');
1542
+
1543
+ expect(events.currentScope({ adapterId: 'clawclaw', accountId: 'account-1' })?.session)
1544
+ .toMatchObject({ resumeKey: 'game-1', mode: 'match' });
1545
+
1546
+ const resumed = new Runtime({
1547
+ adapterId: 'clawclaw',
1548
+ accountId: 'account-1',
1549
+ eventCatalog: createClawclawEventCatalog(),
1550
+ eventRepository: events,
1551
+ stateHistoryRepository: history,
1552
+ resume: true,
1553
+ resumeKey: 'game-1',
1554
+ mode: 'match',
1555
+ initialSegment: { kind: 'game', identity: 'game-1' },
1556
+ });
1557
+ expect(resumed.scope().sessionId).toBe(first.scope().sessionId);
1558
+
1559
+ const mismatch = new Runtime({
1560
+ adapterId: 'clawclaw',
1561
+ accountId: 'account-1',
1562
+ eventCatalog: createClawclawEventCatalog(),
1563
+ eventRepository: events,
1564
+ stateHistoryRepository: history,
1565
+ resume: true,
1566
+ resumeKey: 'game-2',
1567
+ mode: 'match',
1568
+ initialSegment: { kind: 'game', identity: 'game-2' },
1569
+ });
1570
+ expect(mismatch.scope().sessionId).not.toBe(resumed.scope().sessionId);
1571
+
1572
+ await first.close();
1573
+ await resumed.close();
1574
+ await mismatch.close();
1575
+ });
1576
+
1577
+ it('does not attach a keyed resume request to an anonymous durable queue session', async () => {
1578
+ const events = new MemoryEventRepository();
1579
+ const history = new MemoryStateHistoryRepository<ClawclawPosition>();
1580
+ const anonymous = new Runtime({
1581
+ adapterId: 'clawclaw',
1582
+ accountId: 'account-1',
1583
+ eventCatalog: createClawclawEventCatalog(),
1584
+ eventRepository: events,
1585
+ stateHistoryRepository: history,
1586
+ initialSegment: { kind: 'queue' },
1587
+ });
1588
+ const keyed = new Runtime({
1589
+ adapterId: 'clawclaw',
1590
+ accountId: 'account-1',
1591
+ eventCatalog: createClawclawEventCatalog(),
1592
+ eventRepository: events,
1593
+ stateHistoryRepository: history,
1594
+ resume: true,
1595
+ resumeKey: 'game-1',
1596
+ initialSegment: { kind: 'game', identity: 'game-1' },
1597
+ });
1598
+
1599
+ expect(keyed.scope().sessionId).not.toBe(anonymous.scope().sessionId);
1600
+ expect(events.currentScope({ adapterId: 'clawclaw', accountId: 'account-1' })?.session.resumeKey)
1601
+ .toBe('game-1');
1602
+ await anonymous.close();
1603
+ await keyed.close();
1604
+ });
1605
+
1606
+ it('keeps on-change Game State fresh from connection liveness, not snapshot age', async () => {
1607
+ const events = new MemoryEventRepository();
1608
+ const history = new MemoryStateHistoryRepository<ClawclawPosition>();
1609
+ const runtime = createClawclawRuntime({
1610
+ apiKey: 'test-key',
1611
+ runtimeAccountId: 'acct_0123456789abcdef0123456789abcdef',
1612
+ }, {
1613
+ eventRepository: events,
1614
+ stateHistoryRepository: history,
1615
+ durableStateSnapshot: false,
1616
+ initialSegment: { kind: 'game', identity: 'game-1' },
1617
+ });
1618
+ const scope = runtime.scope();
1619
+ const connectionId = 'game-ws-1';
1620
+ const receivedAtMs = 1_000;
1621
+ runtime.bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, connectionId, receivedAtMs);
1622
+ await submitTestInput(runtime, testInputBatch(
1623
+ scope,
1624
+ CLAWCLAW_GAME_WS_SOURCE,
1625
+ 'state',
1626
+ { tick: 1 },
1627
+ { connectionId, receivedAt: new Date(receivedAtMs).toISOString() },
1628
+ ));
1629
+
1630
+ expect(runtime.readState(receivedAtMs + CLAWCLAW_GAME_LIVENESS_SILENCE_MS)).toMatchObject({
1631
+ stateStatus: { status: 'fresh' },
1632
+ });
1633
+ expect(runtime.readState(receivedAtMs + CLAWCLAW_GAME_LIVENESS_SILENCE_MS + 1)).toMatchObject({
1634
+ stateStatus: { status: 'stale', reason: 'liveness_timeout' },
1635
+ });
1636
+
1637
+ const muchLater = 100_000;
1638
+ expect(runtime.connectionLiveness(CLAWCLAW_GAME_WS_SOURCE.sourceId, connectionId, muchLater)).toBe(true);
1639
+ expect(runtime.readState(muchLater)).toMatchObject({
1640
+ stateStatus: { status: 'fresh' },
1641
+ });
1642
+ await runtime.close();
1643
+
1644
+ const custom = createClawclawRuntime({
1645
+ apiKey: 'custom-key',
1646
+ runtimeAccountId: 'acct_fedcba9876543210fedcba9876543210',
1647
+ }, {
1648
+ eventRepository: new MemoryEventRepository(),
1649
+ stateHistoryRepository: new MemoryStateHistoryRepository<ClawclawPosition>(),
1650
+ durableStateSnapshot: false,
1651
+ stateFreshnessPolicy: { maxStateSilenceMs: 5_000 },
1652
+ initialSegment: { kind: 'game', identity: 'game-2' },
1653
+ });
1654
+ const customScope = custom.scope();
1655
+ custom.bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, connectionId, receivedAtMs);
1656
+ await submitTestInput(custom, testInputBatch(
1657
+ customScope,
1658
+ CLAWCLAW_GAME_WS_SOURCE,
1659
+ 'state',
1660
+ { tick: 1 },
1661
+ { connectionId, receivedAt: new Date(receivedAtMs).toISOString() },
1662
+ ));
1663
+ expect(custom.readState(receivedAtMs + 5_001)).toMatchObject({
1664
+ stateStatus: { status: 'fresh' },
1665
+ });
1666
+ await custom.close();
1667
+ });
1668
+
1669
+ it('keeps on-change room State fresh from connection liveness, not snapshot age', async () => {
1670
+ const runtime = createClawclawRuntime({
1671
+ apiKey: 'room-key',
1672
+ runtimeAccountId: 'acct_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
1673
+ }, {
1674
+ eventRepository: new MemoryEventRepository(),
1675
+ stateHistoryRepository: new MemoryStateHistoryRepository<ClawclawPosition>(),
1676
+ durableStateSnapshot: false,
1677
+ initialSegment: { kind: 'room_lobby', identity: 'R1' },
1678
+ });
1679
+ const scope = runtime.scope();
1680
+ runtime.bindConnection(CLAWCLAW_ROOM_WS_SOURCE.sourceId, 'room-c1', 1_000);
1681
+ await submitTestInput(runtime, testInputBatch(
1682
+ scope,
1683
+ CLAWCLAW_ROOM_WS_SOURCE,
1684
+ 'state',
1685
+ { phase: 'room_waiting', room: { room_code: 'R1' } },
1686
+ { connectionId: 'room-c1', receivedAt: new Date(1_100).toISOString() },
1687
+ ));
1688
+
1689
+ const muchLater = 100_000;
1690
+ expect(muchLater - 1_100).toBeGreaterThan(CLAWCLAW_GAME_LIVENESS_SILENCE_MS);
1691
+ expect(runtime.connectionLiveness(CLAWCLAW_ROOM_WS_SOURCE.sourceId, 'room-c1', muchLater)).toBe(true);
1692
+ expect(runtime.readState(muchLater)).toMatchObject({
1693
+ state: { phase: 'room_waiting', room: { room_code: 'R1' } },
1694
+ stateStatus: { status: 'fresh' },
1695
+ });
1696
+
1697
+ runtime.connectionChanged(CLAWCLAW_ROOM_WS_SOURCE.sourceId, 'room-c1', 'reconnecting', muchLater + 1);
1698
+ expect(runtime.readState(muchLater + 2)).toMatchObject({
1699
+ stateStatus: { status: 'stale', reason: 'connection_reconnecting' },
1700
+ });
1701
+ expect(runtime.connectionScope(CLAWCLAW_ROOM_WS_SOURCE.sourceId, 'room-c1')).not.toBeNull();
1702
+ await runtime.close();
1703
+ });
1704
+ });