@myclaw163/clawclaw-cli 0.6.111 → 0.7.4

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 (418) 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 +24 -7
  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 +120 -64
  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 +18 -8
  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/cli.ts +21 -47
  39. package/src/commands/account.test.ts +229 -50
  40. package/src/commands/account.ts +456 -223
  41. package/src/commands/communication.test.ts +259 -0
  42. package/src/commands/communication.ts +391 -0
  43. package/src/commands/competition.test.ts +116 -0
  44. package/src/commands/competition.ts +50 -28
  45. package/src/commands/data.test.ts +57 -1
  46. package/src/commands/data.ts +79 -4
  47. package/src/commands/events-canonical-state.test.ts +187 -0
  48. package/src/commands/events.test.ts +50 -136
  49. package/src/commands/events.ts +175 -241
  50. package/src/commands/game/index.test.ts +510 -0
  51. package/src/commands/game/index.ts +556 -0
  52. package/src/commands/game-map.test.ts +40 -3
  53. package/src/commands/hub.ts +2 -9
  54. package/src/commands/load.test.ts +12 -2
  55. package/src/commands/load.ts +15 -2
  56. package/src/commands/peek.ts +2 -3
  57. package/src/commands/perception.test.ts +46 -0
  58. package/src/commands/perception.ts +92 -0
  59. package/src/commands/setup/codex.ts +0 -1
  60. package/src/commands/strategy.test.ts +139 -83
  61. package/src/commands/strategy.ts +175 -125
  62. package/src/commands/upgrade.ts +0 -21
  63. package/src/lib/auth.test.ts +35 -0
  64. package/src/lib/auth.ts +45 -6
  65. package/src/lib/diagnostics-config.test.ts +59 -0
  66. package/src/lib/diagnostics-config.ts +76 -0
  67. package/src/lib/game-client.test.ts +166 -0
  68. package/src/lib/game-client.ts +316 -87
  69. package/src/lib/game-context.ts +29 -0
  70. package/src/lib/gameplay-config.test.ts +66 -0
  71. package/src/lib/gameplay-config.ts +151 -0
  72. package/src/lib/http-transport.test.ts +63 -0
  73. package/src/lib/http-transport.ts +76 -10
  74. package/src/lib/init-command.test.ts +25 -1
  75. package/src/lib/init-command.ts +66 -1
  76. package/src/lib/participation-leave.ts +78 -0
  77. package/src/lib/perception-config.test.ts +138 -0
  78. package/src/lib/perception-config.ts +101 -0
  79. package/src/lib/room.test.ts +14 -0
  80. package/src/lib/room.ts +28 -2
  81. package/src/lib/server-registry.test.ts +15 -5
  82. package/src/lib/server-registry.ts +9 -10
  83. package/src/lib/strategy-export.test.ts +123 -44
  84. package/src/lib/strategy-export.ts +111 -101
  85. package/src/lib/user-data.test.ts +2 -0
  86. package/src/lib/user-data.ts +17 -16
  87. package/src/pipeline/canonical-event-presentation.test.ts +195 -0
  88. package/src/pipeline/canonical-event-presentation.ts +71 -0
  89. package/src/pipeline/event-format.test.ts +357 -59
  90. package/src/pipeline/event-format.ts +365 -80
  91. package/src/pipeline/event-hints.test.ts +241 -0
  92. package/src/pipeline/event-hints.ts +202 -51
  93. package/src/pipeline/game-sync-event-normalization.test.ts +239 -0
  94. package/src/pipeline/game-sync-event-normalization.ts +215 -0
  95. package/src/pipeline/player-projection.test.ts +164 -102
  96. package/src/pipeline/player-projection.ts +194 -235
  97. package/src/runtime/canonical-event-emitter.test.ts +70 -0
  98. package/src/runtime/canonical-event-emitter.ts +78 -0
  99. package/src/runtime/canonical-monitor.test.ts +575 -0
  100. package/src/runtime/canonical-monitor.ts +388 -0
  101. package/src/runtime/clawclaw/agent-event-policy.test.ts +27 -0
  102. package/src/runtime/clawclaw/agent-event-policy.ts +35 -0
  103. package/src/runtime/clawclaw/index.ts +4 -0
  104. package/src/runtime/clawclaw/notifications.test.ts +47 -0
  105. package/src/runtime/clawclaw/notifications.ts +65 -0
  106. package/src/runtime/clawclaw/owner-lock.test.ts +221 -0
  107. package/src/runtime/clawclaw/owner.ts +945 -0
  108. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +299 -0
  109. package/src/runtime/clawclaw/plugins/action/index.ts +1 -0
  110. package/src/runtime/clawclaw/plugins/assembly.test.ts +81 -0
  111. package/src/runtime/clawclaw/plugins/assembly.ts +116 -0
  112. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.test.ts +150 -0
  113. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +100 -0
  114. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +162 -0
  115. package/src/runtime/clawclaw/plugins/derived-event/index.ts +2 -0
  116. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.test.ts +223 -0
  117. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +236 -0
  118. package/src/runtime/clawclaw/plugins/game-query/index.ts +1 -0
  119. package/src/runtime/clawclaw/plugins/index.ts +7 -0
  120. package/src/runtime/clawclaw/plugins/mailbox/index.ts +3 -0
  121. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +77 -0
  122. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +91 -0
  123. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.test.ts +1008 -0
  124. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +475 -0
  125. package/src/runtime/clawclaw/plugins/perception/contracts.ts +32 -0
  126. package/src/runtime/clawclaw/plugins/perception/index.ts +8 -0
  127. package/src/runtime/clawclaw/plugins/perception/module-runner.test.ts +204 -0
  128. package/src/runtime/clawclaw/plugins/perception/module-runner.ts +290 -0
  129. package/src/runtime/clawclaw/plugins/perception/modules/co-movement-module.ts +324 -0
  130. package/src/runtime/clawclaw/plugins/perception/modules/follow-module.ts +365 -0
  131. package/src/runtime/clawclaw/plugins/perception/modules/index.ts +7 -0
  132. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.test.ts +341 -0
  133. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.ts +447 -0
  134. package/src/runtime/clawclaw/plugins/perception/modules/parallel-module-test-helpers.ts +30 -0
  135. package/src/runtime/clawclaw/plugins/perception/modules/relation-stability.test.ts +289 -0
  136. package/src/runtime/clawclaw/plugins/perception/modules/route-module.test.ts +180 -0
  137. package/src/runtime/clawclaw/plugins/perception/modules/route-module.ts +329 -0
  138. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.test.ts +82 -0
  139. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.ts +172 -0
  140. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.test.ts +212 -0
  141. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.ts +256 -0
  142. package/src/runtime/clawclaw/plugins/perception/modules/temporal-evidence.test.ts +121 -0
  143. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.test.ts +106 -0
  144. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.ts +225 -0
  145. package/src/runtime/clawclaw/plugins/perception/official-module-ids.ts +11 -0
  146. package/src/runtime/clawclaw/plugins/perception/official-modules.ts +31 -0
  147. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.test.ts +759 -0
  148. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +707 -0
  149. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +215 -0
  150. package/src/runtime/clawclaw/plugins/perception/perception-module-loader.ts +61 -0
  151. package/src/runtime/clawclaw/plugins/perception/perception-plugin.test.ts +1516 -0
  152. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1529 -0
  153. package/src/runtime/clawclaw/plugins/perception/perception-source.test.ts +119 -0
  154. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +244 -0
  155. package/src/runtime/clawclaw/plugins/perception/replay.test.ts +65 -0
  156. package/src/runtime/clawclaw/plugins/perception/replay.ts +86 -0
  157. package/src/runtime/clawclaw/plugins/perception/shared/math.ts +107 -0
  158. package/src/runtime/clawclaw/plugins/perception/spatial-facts.ts +114 -0
  159. package/src/runtime/clawclaw/plugins/perception/visual-state-projector.ts +98 -0
  160. package/src/runtime/clawclaw/plugins/runtime-plugins.test.ts +1019 -0
  161. package/src/runtime/clawclaw/plugins/source/game-transport.test.ts +287 -0
  162. package/src/runtime/clawclaw/plugins/source/game-transport.ts +281 -0
  163. package/src/runtime/clawclaw/plugins/source/index.ts +5 -0
  164. package/src/runtime/clawclaw/plugins/source/player-change-tracker.test.ts +270 -0
  165. package/src/runtime/clawclaw/plugins/source/player-change-tracker.ts +151 -0
  166. package/src/runtime/clawclaw/plugins/source/room-transport.test.ts +307 -0
  167. package/src/runtime/clawclaw/plugins/source/room-transport.ts +480 -0
  168. package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +1909 -0
  169. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +2055 -0
  170. package/src/runtime/clawclaw/plugins/source/source-transports.ts +30 -0
  171. package/src/runtime/clawclaw/plugins/source/types.ts +79 -0
  172. package/src/runtime/clawclaw/plugins/strategy/context-capabilities.ts +5 -0
  173. package/src/runtime/clawclaw/plugins/strategy/examples/task-only-strategy.test.ts +177 -0
  174. package/src/runtime/clawclaw/plugins/strategy/examples/task-only-strategy.ts +185 -0
  175. package/src/runtime/clawclaw/plugins/strategy/index.ts +8 -0
  176. package/src/runtime/clawclaw/plugins/strategy/local-strategy-executor.ts +412 -0
  177. package/src/runtime/clawclaw/plugins/strategy/strategy-action.ts +73 -0
  178. package/src/runtime/clawclaw/plugins/strategy/strategy-analysis-thread-host.ts +183 -0
  179. package/src/runtime/clawclaw/plugins/strategy/strategy-executor-types.ts +25 -0
  180. package/src/runtime/clawclaw/plugins/strategy/strategy-executor.test.ts +693 -0
  181. package/src/runtime/clawclaw/plugins/strategy/strategy-game-api.ts +57 -0
  182. package/src/runtime/clawclaw/plugins/strategy/strategy-module-loader.ts +164 -0
  183. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.test.ts +1936 -0
  184. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.ts +1557 -0
  185. package/src/runtime/clawclaw/plugins/strategy/strategy-source.test.ts +131 -0
  186. package/src/runtime/clawclaw/plugins/strategy/strategy-source.ts +413 -0
  187. package/src/runtime/clawclaw/plugins/strategy/thread-strategy-executor.ts +792 -0
  188. package/src/runtime/clawclaw/runtime-data-export.test.ts +249 -0
  189. package/src/runtime/clawclaw/runtime-data-export.ts +402 -0
  190. package/src/runtime/clawclaw/runtime-state.ts +98 -0
  191. package/src/runtime/clawclaw/runtime.ts +133 -0
  192. package/src/runtime/clawclaw-event-catalog.test.ts +74 -0
  193. package/src/runtime/clawclaw-event-catalog.ts +266 -0
  194. package/src/runtime/clawclaw-position.ts +4 -0
  195. package/src/runtime/clawclaw-room-state.ts +51 -0
  196. package/src/runtime/framework/action-diagnostics.test.ts +81 -0
  197. package/src/runtime/framework/action-diagnostics.ts +146 -0
  198. package/src/runtime/framework/capability-registry.test.ts +282 -0
  199. package/src/runtime/framework/capability-registry.ts +283 -0
  200. package/src/runtime/framework/contracts.ts +118 -0
  201. package/src/runtime/framework/control/control-scheduler.ts +1260 -0
  202. package/src/runtime/framework/control/domain-set.ts +81 -0
  203. package/src/runtime/framework/control/index.ts +3 -0
  204. package/src/runtime/framework/control/types.ts +184 -0
  205. package/src/runtime/framework/control-coordinator.test.ts +660 -0
  206. package/src/runtime/framework/control-coordinator.ts +11 -0
  207. package/src/runtime/framework/events/event-catalog.ts +74 -0
  208. package/src/runtime/framework/events/event-delivery-service.test.ts +84 -0
  209. package/src/runtime/framework/events/event-delivery-service.ts +198 -0
  210. package/src/runtime/framework/events/event-ingress.test.ts +178 -0
  211. package/src/runtime/framework/events/event-ingress.ts +97 -0
  212. package/src/runtime/framework/events/event-repository.ts +59 -0
  213. package/src/runtime/framework/events/index.ts +7 -0
  214. package/src/runtime/framework/events/mailbox-event-repositories.test.ts +594 -0
  215. package/src/runtime/framework/events/memory-event-repository.ts +928 -0
  216. package/src/runtime/framework/events/sqlite-event-repository.test.ts +200 -0
  217. package/src/runtime/framework/events/sqlite-event-repository.ts +1681 -0
  218. package/src/runtime/framework/events/test-helpers.ts +78 -0
  219. package/src/runtime/framework/events/types.ts +286 -0
  220. package/src/runtime/framework/index.ts +7 -0
  221. package/src/runtime/framework/load-node-sqlite.ts +17 -0
  222. package/src/runtime/framework/mailbox/coalescer.test.ts +55 -0
  223. package/src/runtime/framework/mailbox/coalescer.ts +83 -0
  224. package/src/runtime/framework/mailbox/host-notification-sink.ts +44 -0
  225. package/src/runtime/framework/mailbox/identity.test.ts +38 -0
  226. package/src/runtime/framework/mailbox/identity.ts +38 -0
  227. package/src/runtime/framework/mailbox/index.ts +7 -0
  228. package/src/runtime/framework/mailbox/mailbox-dispatcher.test.ts +513 -0
  229. package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +282 -0
  230. package/src/runtime/framework/mailbox/mailbox-repository.ts +44 -0
  231. package/src/runtime/framework/mailbox/notification-projector.test.ts +77 -0
  232. package/src/runtime/framework/mailbox/notification-projector.ts +65 -0
  233. package/src/runtime/framework/mailbox/types.ts +139 -0
  234. package/src/runtime/framework/modules/runtime-module-loader-hooks.d.mts +19 -0
  235. package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +117 -0
  236. package/src/runtime/framework/modules/runtime-module-loader.test.ts +209 -0
  237. package/src/runtime/framework/modules/runtime-module-loader.ts +71 -0
  238. package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +23 -0
  239. package/src/runtime/framework/participation-manager.test.ts +108 -0
  240. package/src/runtime/framework/participation-manager.ts +244 -0
  241. package/src/runtime/framework/plugins/contracts.ts +382 -0
  242. package/src/runtime/framework/plugins/index.ts +4 -0
  243. package/src/runtime/framework/plugins/runtime-event-identity.ts +17 -0
  244. package/src/runtime/framework/plugins/runtime-input-journal.test.ts +179 -0
  245. package/src/runtime/framework/plugins/runtime-input-journal.ts +693 -0
  246. package/src/runtime/framework/plugins/runtime-plugin-scheduler.test.ts +1994 -0
  247. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +1860 -0
  248. package/src/runtime/framework/runtime.ts +1756 -0
  249. package/src/runtime/framework/serial-task-queue.ts +14 -0
  250. package/src/runtime/framework/state/contracts.ts +49 -0
  251. package/src/runtime/framework/state/current-state-store.ts +184 -0
  252. package/src/runtime/framework/state/durable-agent-state-snapshot.test.ts +144 -0
  253. package/src/runtime/framework/state/durable-agent-state-snapshot.ts +209 -0
  254. package/src/runtime/framework/state/freshness.ts +72 -0
  255. package/src/runtime/framework/state/history/contracts.ts +150 -0
  256. package/src/runtime/framework/state/history/history-writer.ts +194 -0
  257. package/src/runtime/framework/state/history/memory-state-history-repository.ts +178 -0
  258. package/src/runtime/framework/state/history/sqlite-state-history-repository.test.ts +157 -0
  259. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +629 -0
  260. package/src/runtime/framework/state/history/state-history.test.ts +251 -0
  261. package/src/runtime/framework/state/history/trajectory-projector.ts +209 -0
  262. package/src/runtime/framework/state/index.ts +13 -0
  263. package/src/runtime/framework/state/state-core.test.ts +197 -0
  264. package/src/runtime/framework/state/state-ingress.ts +95 -0
  265. package/src/runtime/framework/state/state-provider.ts +62 -0
  266. package/src/runtime/framework/state/types.ts +155 -0
  267. package/src/runtime/game-sync-protocol.test.ts +123 -0
  268. package/src/runtime/game-sync-protocol.ts +261 -0
  269. package/src/runtime/mailbox-host-relay.test.ts +248 -0
  270. package/src/runtime/mailbox-host-relay.ts +300 -0
  271. package/src/runtime/observability/factory.ts +188 -0
  272. package/src/runtime/observability/index.ts +6 -0
  273. package/src/runtime/observability/observability.test.ts +561 -0
  274. package/src/runtime/observability/recorder.ts +209 -0
  275. package/src/runtime/observability/redaction.ts +154 -0
  276. package/src/runtime/observability/reporter.ts +154 -0
  277. package/src/runtime/observability/sinks.ts +135 -0
  278. package/src/runtime/observability/types.ts +92 -0
  279. package/src/runtime/owner-control.test.ts +153 -0
  280. package/src/runtime/owner-control.ts +206 -42
  281. package/src/runtime/parent-process-watch.test.ts +27 -0
  282. package/src/runtime/parent-process-watch.ts +51 -0
  283. package/src/runtime/pending-event-handoff.test.ts +29 -0
  284. package/src/runtime/pending-event-handoff.ts +61 -0
  285. package/src/runtime/raw-ws-log.test.ts +86 -17
  286. package/src/runtime/raw-ws-log.ts +230 -21
  287. package/src/runtime/runtime-logger.test.ts +58 -0
  288. package/src/runtime/runtime-logger.ts +10 -13
  289. package/src/runtime/runtime-persistence.test.ts +26 -0
  290. package/src/runtime/runtime.test.ts +1704 -0
  291. package/src/runtime/ws-client.test.ts +496 -103
  292. package/src/runtime/ws-client.ts +546 -166
  293. package/src/sdk/action.ts +3 -1
  294. package/src/sdk/index.ts +4 -19
  295. package/src/sdk/perception-plugin/index.test.ts +22 -0
  296. package/src/sdk/perception-plugin/index.ts +285 -0
  297. package/src/sdk/strategy-plugin/index.test.ts +952 -0
  298. package/src/sdk/strategy-plugin/index.ts +1324 -0
  299. package/src/sdk/types.ts +3 -1
  300. package/src/short-command/classifier.test.ts +107 -0
  301. package/src/short-command/classifier.ts +169 -0
  302. package/src/short-command/index.ts +7 -0
  303. package/src/short-command/presenter.test.ts +119 -0
  304. package/src/short-command/presenter.ts +308 -0
  305. package/src/short-command/process-io.ts +13 -0
  306. package/src/short-command/response-contract.ts +58 -0
  307. package/src/short-command/runner.test.ts +78 -0
  308. package/src/short-command/runner.ts +164 -0
  309. package/src/short-command/sensitive-data-filter.test.ts +56 -0
  310. package/src/short-command/sensitive-data-filter.ts +123 -0
  311. package/src/short-command/transport-response.test.ts +39 -0
  312. package/src/short-command/transport-response.ts +89 -0
  313. package/src/short-command/types.ts +92 -0
  314. package/src/strategies/avoid-lone.ts +18 -11
  315. package/src/strategies/avoid-players.ts +29 -13
  316. package/src/strategies/corpse-patrol.ts +29 -11
  317. package/src/strategies/crab-sabotage.ts +31 -18
  318. package/src/strategies/custom-module.test.ts +3 -5
  319. package/src/strategies/find-player.ts +34 -15
  320. package/src/strategies/game-utils.test.ts +42 -0
  321. package/src/strategies/game-utils.ts +143 -53
  322. package/src/strategies/goals/avoid-lone-top.ts +22 -1
  323. package/src/strategies/goals/avoid-players-top.test.ts +13 -0
  324. package/src/strategies/goals/avoid-players-top.ts +6 -5
  325. package/src/strategies/goals/corpse-patrol-top.ts +9 -2
  326. package/src/strategies/goals/crab-octopus-reflexes.ts +6 -2
  327. package/src/strategies/goals/crab-sabotage-top.ts +7 -1
  328. package/src/strategies/goals/emergency-hunt-goal.ts +15 -3
  329. package/src/strategies/goals/find-player-top.ts +47 -3
  330. package/src/strategies/goals/flee-players-goal.ts +2 -0
  331. package/src/strategies/goals/follow-companion-goal.ts +27 -3
  332. package/src/strategies/goals/hide-top.ts +47 -5
  333. package/src/strategies/goals/keep-away-goal.ts +24 -2
  334. package/src/strategies/goals/kill-frenzy-top.ts +12 -2
  335. package/src/strategies/goals/kill-lone-top.test.ts +72 -0
  336. package/src/strategies/goals/kill-lone-top.ts +8 -6
  337. package/src/strategies/goals/kill-target-goal.ts +16 -7
  338. package/src/strategies/goals/kill-target-top.ts +16 -2
  339. package/src/strategies/goals/linger-corpse-goal.ts +11 -3
  340. package/src/strategies/goals/lone-kill-core.ts +4 -2
  341. package/src/strategies/goals/move-room-goal.ts +46 -4
  342. package/src/strategies/goals/normal-shrimp-top.test.ts +16 -0
  343. package/src/strategies/goals/normal-shrimp-top.ts +18 -18
  344. package/src/strategies/goals/paradise-fish-top.test.ts +78 -0
  345. package/src/strategies/goals/paradise-fish-top.ts +16 -6
  346. package/src/strategies/goals/patrol-top.ts +14 -3
  347. package/src/strategies/goals/report-patrol-top.ts +14 -3
  348. package/src/strategies/goals/safe-task-goal.ts +32 -4
  349. package/src/strategies/goals/social-task-top.ts +39 -8
  350. package/src/strategies/goals/task-kill-report-top.ts +33 -10
  351. package/src/strategies/goals/task-only-top.test.ts +89 -0
  352. package/src/strategies/goals/task-only-top.ts +9 -2
  353. package/src/strategies/goals/task-or-patrol-goal.ts +21 -3
  354. package/src/strategies/goals/warrior-shrimp-top.test.ts +75 -23
  355. package/src/strategies/goals/warrior-shrimp-top.ts +34 -13
  356. package/src/strategies/greeting.ts +10 -3
  357. package/src/strategies/hide-spots.ts +4 -0
  358. package/src/strategies/hide.ts +35 -20
  359. package/src/strategies/kill-frenzy.ts +18 -12
  360. package/src/strategies/kill-lone.ts +43 -12
  361. package/src/strategies/kill-target.ts +34 -17
  362. package/src/strategies/lone-kill-task.ts +31 -18
  363. package/src/strategies/move-room.ts +32 -15
  364. package/src/strategies/off-route-points.ts +12 -4
  365. package/src/strategies/paradise-fish.ts +49 -14
  366. package/src/strategies/pathfind/astar-path.test.ts +73 -0
  367. package/src/strategies/pathfind/astar-path.ts +196 -0
  368. package/src/strategies/pathfind/escape-planner.test.ts +27 -1
  369. package/src/strategies/pathfind/escape-planner.ts +108 -0
  370. package/src/strategies/patrol.ts +18 -11
  371. package/src/strategies/report-patrol.ts +18 -11
  372. package/src/strategies/shrimp-memory.ts +66 -14
  373. package/src/strategies/social-task.ts +49 -45
  374. package/src/strategies/task-kill-report.ts +34 -16
  375. package/src/strategies/task-only.test.ts +124 -0
  376. package/src/strategies/task-only.ts +20 -11
  377. package/src/strategies/task-report.ts +29 -11
  378. package/src/strategies/types.ts +29 -62
  379. package/src/strategies/warrior-memory.ts +44 -14
  380. package/scripts/check_monitor.test.mjs +0 -212
  381. package/skills/clawclaw/references/KNOWLEDGE.md +0 -42
  382. package/src/commands/do.test.ts +0 -117
  383. package/src/commands/do.ts +0 -195
  384. package/src/commands/game-monitor-status.test.ts +0 -58
  385. package/src/commands/game-start-plan.test.ts +0 -356
  386. package/src/commands/game.ts +0 -2046
  387. package/src/commands/history-player.test.ts +0 -105
  388. package/src/commands/history.ts +0 -573
  389. package/src/commands/knowledge.test.ts +0 -13
  390. package/src/commands/knowledge.ts +0 -176
  391. package/src/commands/meeting-history.test.ts +0 -106
  392. package/src/commands/state.ts +0 -46
  393. package/src/commands/watch.test.ts +0 -1313
  394. package/src/commands/watch.ts +0 -824
  395. package/src/lib/knowledge-store.test.ts +0 -170
  396. package/src/lib/knowledge-store.ts +0 -369
  397. package/src/perception/player-history-store.test.ts +0 -177
  398. package/src/perception/player-history-store.ts +0 -262
  399. package/src/pipeline/event-store.test.ts +0 -28
  400. package/src/pipeline/event-store.ts +0 -193
  401. package/src/pipeline/pipeline.ts +0 -35
  402. package/src/runtime/event-daemon.test.ts +0 -268
  403. package/src/runtime/event-daemon.ts +0 -531
  404. package/src/runtime/room-lobby-runtime.test.ts +0 -95
  405. package/src/runtime/room-lobby-runtime.ts +0 -367
  406. package/src/strategies/avoid-players.knowledge.md +0 -19
  407. package/src/strategies/kill-lone.knowledge.md +0 -17
  408. package/src/strategies/knowledge-contract.ts +0 -85
  409. package/src/strategies/loader.test.ts +0 -678
  410. package/src/strategies/loader.ts +0 -212
  411. package/src/strategies/new-events-backfill.ts +0 -98
  412. package/src/strategies/paradise-fish.knowledge.md +0 -19
  413. package/src/strategies/shrimp-memory.knowledge.md +0 -19
  414. package/src/strategies/social-task.test.ts +0 -28
  415. package/src/strategies/spawn.ts +0 -82
  416. package/src/strategies/strategy-loop.test.ts +0 -15
  417. package/src/strategies/strategy-loop.ts +0 -748
  418. package/src/strategies/warrior-memory.knowledge.md +0 -21
@@ -0,0 +1,1756 @@
1
+ import {
2
+ ActionRegistry,
3
+ ObservationRegistry,
4
+ type ActionAdmissionOptions,
5
+ type RegisteredActionService,
6
+ } from './capability-registry.js';
7
+ import {
8
+ actionFailureDiagnosticSeverity,
9
+ summarizeActionError,
10
+ } from './action-diagnostics.js';
11
+ import type {
12
+ ActionCaller,
13
+ ActionResult,
14
+ ObservationProvider,
15
+ ObservationResult,
16
+ ScopeRef,
17
+ } from './contracts.js';
18
+ import {
19
+ EventIngress,
20
+ type EventCatalog,
21
+ MemoryEventRepository,
22
+ SqliteEventRepository,
23
+ type CanonicalEvent,
24
+ type CurrentEventScope,
25
+ type EventRepository,
26
+ type EventSegmentRecord,
27
+ type PlaySessionRecord,
28
+ type PublishEventInput,
29
+ } from './events/index.js';
30
+ import {
31
+ MemoryRuntimeInputJournal,
32
+ RuntimePluginScheduler,
33
+ SqliteRuntimeInputJournal,
34
+ assertRuntimeInputBatch,
35
+ runtimeSourceEventId,
36
+ type RuntimeEpoch,
37
+ type RuntimeEpochExecutionResult,
38
+ type RuntimePersistenceStore,
39
+ type RuntimeEpochPlugin,
40
+ type RuntimeEpochWork,
41
+ type RuntimeInputAcceptance,
42
+ type RuntimeInputBatch,
43
+ type RuntimePluginCapabilityAccess,
44
+ type RuntimePluginDescriptor,
45
+ type RuntimeEventProposal,
46
+ type RuntimeSourceContext,
47
+ type RuntimeSourceEvent,
48
+ type RuntimeSourcePlugin,
49
+ type RuntimeSourceStopHandle,
50
+ } from './plugins/index.js';
51
+ import {
52
+ ParticipationManager,
53
+ type ParticipationSnapshot,
54
+ type ParticipationTransition,
55
+ } from './participation-manager.js';
56
+ import {
57
+ CurrentStateStore,
58
+ HistoryWriter,
59
+ type HistoryWriterDegradedScopeHealth,
60
+ type HistoryWriterHealth,
61
+ MemoryStateHistoryRepository,
62
+ SqliteStateHistoryRepository,
63
+ StateFreshnessEvaluator,
64
+ StateIngress,
65
+ type FlushableStateIngressObserver,
66
+ type StateIngressObserver,
67
+ StateProvider,
68
+ type RuntimeConnectionState,
69
+ type RuntimeScope,
70
+ type StateHistoryRepository,
71
+ type StateFreshnessPolicy,
72
+ type StateFreshnessPolicyResolver,
73
+ type StateProviderResult,
74
+ type TrajectoryRecord,
75
+ } from './state/index.js';
76
+ import { randomUUID } from 'crypto';
77
+ import type { TelemetryRecorder } from '../observability/index.js';
78
+
79
+ export interface RuntimePersistenceStatus {
80
+ events: 'sqlite' | 'memory';
81
+ stateHistory: 'sqlite' | 'memory';
82
+ inputJournal: 'sqlite' | 'memory';
83
+ warnings: string[];
84
+ historyWriter: PublicHistoryWriterHealth;
85
+ }
86
+
87
+ /** Durable Event/session store used by the fixed Runtime loop. */
88
+ export type RuntimeRepository = EventRepository;
89
+
90
+ export interface RuntimeOptions<TPosition = unknown> {
91
+ adapterId: string;
92
+ accountId: string;
93
+ eventCatalog: EventCatalog;
94
+ eventLedgerPath?: string;
95
+ stateHistoryPath?: string;
96
+ inputJournalPath?: string;
97
+ eventRepository?: RuntimeRepository;
98
+ stateHistoryRepository?: StateHistoryRepository<TPosition>;
99
+ inputJournal?: RuntimePersistenceStore<Record<string, any>, Record<string, unknown>>;
100
+ historyObserverFactory?: (
101
+ writer: HistoryWriter<TPosition>,
102
+ ) => StateIngressObserver<Record<string, any>>;
103
+ stateObservers?: FlushableStateIngressObserver<Record<string, any>>[];
104
+ resume?: boolean;
105
+ resumeKey?: string;
106
+ mode?: string;
107
+ stateFreshnessPolicy?: StateFreshnessPolicy;
108
+ /** Optional per-source override for transports with different State cadence. */
109
+ stateFreshnessPolicyResolver?: StateFreshnessPolicyResolver;
110
+ /** Owner-side operational telemetry. It is never part of Event or State. */
111
+ observability?: TelemetryRecorder;
112
+ /** Static per-epoch plugin graph used by the Runtime loop. */
113
+ runtimeEpochPlugins?: RuntimeEpochPlugin<Record<string, any>, Record<string, unknown>>[];
114
+ /** Projects a game-neutral Runtime State into the current game-facing view. */
115
+ currentStateFromRuntimeState?: (
116
+ state: Readonly<Record<string, any>>,
117
+ ) => Record<string, any> | null;
118
+ initialSegment: {
119
+ kind: string;
120
+ identity?: string;
121
+ };
122
+ }
123
+
124
+ export type PublicRuntimeScope = Omit<RuntimeScope, 'accountId'>;
125
+
126
+ export interface PublicHistoryWriterDegradedScopeHealth
127
+ extends Omit<HistoryWriterDegradedScopeHealth, 'scope'> {
128
+ scope: PublicRuntimeScope;
129
+ }
130
+
131
+ export interface PublicHistoryWriterHealth extends HistoryWriterHealth {
132
+ degradedScopes: PublicHistoryWriterDegradedScopeHealth[];
133
+ }
134
+
135
+ export interface ExpectedRuntimeScope {
136
+ sessionId: string;
137
+ segmentId: string;
138
+ }
139
+
140
+ /** Latest durable value of one plugin-owned State topic at a Ready boundary. */
141
+ export interface RuntimeReadyPluginState {
142
+ pluginId: string;
143
+ topic: string;
144
+ value: unknown;
145
+ updatedEpochSeq: number;
146
+ updatedDomainTick?: number;
147
+ }
148
+
149
+ /** Result of a plugin's invocation for the Ready View's closing epoch. */
150
+ export interface RuntimeReadyPluginOutcome {
151
+ pluginId: string;
152
+ epochSeq: number;
153
+ domainTick?: number;
154
+ outcome: RuntimeEpochExecutionResult['outcomes'][number]['outcome'];
155
+ reason?: string;
156
+ }
157
+
158
+ /** One coherent, non-consuming view at the latest fully closed epoch. */
159
+ export interface RuntimeReadyView<TState = Record<string, any> | null> {
160
+ scope: PublicRuntimeScope;
161
+ state: StateProviderResult<TState>;
162
+ /** Topic-keyed latest values, carried only within the same Runtime segment. */
163
+ pluginStates: Record<string, RuntimeReadyPluginState>;
164
+ /** Plugin-keyed outcomes for this exact closing epoch. */
165
+ pluginOutcomes: Record<string, RuntimeReadyPluginOutcome>;
166
+ events: CanonicalEvent[];
167
+ throughCommitSeq: number;
168
+ frameSeq: number;
169
+ eventWatermark: number;
170
+ epochSeq: number;
171
+ hasMore: boolean;
172
+ }
173
+
174
+ interface RuntimeReadyAnchor<TState = Record<string, any> | null> {
175
+ scope: RuntimeScope;
176
+ state: StateProviderResult<TState>;
177
+ pluginStates: Record<string, RuntimeReadyPluginState>;
178
+ pluginOutcomes: Record<string, RuntimeReadyPluginOutcome>;
179
+ frameSeq: number;
180
+ eventWatermark: number;
181
+ epochSeq: number;
182
+ }
183
+
184
+ const CLOSED_READY_ANCHOR_LIMIT = 256;
185
+
186
+ function runtimeScope(snapshot: ParticipationSnapshot): RuntimeScope {
187
+ return {
188
+ adapterId: snapshot.session.adapterId,
189
+ accountId: snapshot.session.accountId,
190
+ sessionId: snapshot.session.id,
191
+ segmentId: snapshot.segment.id,
192
+ segmentSeq: snapshot.segment.ordinal,
193
+ };
194
+ }
195
+
196
+ function eventSession(snapshot: ParticipationSnapshot, current: boolean): PlaySessionRecord {
197
+ return {
198
+ sessionId: snapshot.session.id,
199
+ adapterId: snapshot.session.adapterId,
200
+ accountId: snapshot.session.accountId,
201
+ resumeKey: snapshot.session.resumeKey,
202
+ mode: snapshot.session.mode,
203
+ status: snapshot.session.endedAt ? 'sealed' : 'open',
204
+ isCurrent: current,
205
+ openedAt: snapshot.session.startedAt,
206
+ sealedAt: snapshot.session.endedAt,
207
+ };
208
+ }
209
+
210
+ function eventSegment(
211
+ segment: ParticipationSnapshot['segment'],
212
+ current: boolean,
213
+ ): EventSegmentRecord {
214
+ return {
215
+ segmentId: segment.id,
216
+ sessionId: segment.sessionId,
217
+ sequence: segment.ordinal,
218
+ kind: segment.kind,
219
+ scopeRef: segment.identity,
220
+ status: segment.endedAt ? 'closed' : 'open',
221
+ isCurrent: current,
222
+ openedAt: segment.startedAt,
223
+ closedAt: segment.endedAt,
224
+ };
225
+ }
226
+
227
+ function participationFromCurrent(scope: CurrentEventScope): ParticipationSnapshot {
228
+ return {
229
+ session: {
230
+ id: scope.session.sessionId,
231
+ adapterId: scope.session.adapterId,
232
+ accountId: scope.session.accountId,
233
+ resumeKey: scope.session.resumeKey,
234
+ mode: scope.session.mode,
235
+ startedAt: scope.session.openedAt,
236
+ endedAt: scope.session.sealedAt,
237
+ },
238
+ segment: {
239
+ id: scope.segment.segmentId,
240
+ sessionId: scope.segment.sessionId,
241
+ kind: scope.segment.kind,
242
+ identity: scope.segment.scopeRef,
243
+ ordinal: scope.segment.sequence,
244
+ startedAt: scope.segment.openedAt,
245
+ endedAt: scope.segment.closedAt,
246
+ },
247
+ // A process restart always creates new physical connections. Never restore
248
+ // a connection id from durable logical participation state.
249
+ connections: {},
250
+ };
251
+ }
252
+
253
+ function sameScope(envelope: ScopeRef, scope: ScopeRef): boolean {
254
+ return envelope.adapterId === scope.adapterId
255
+ && envelope.accountId === scope.accountId
256
+ && envelope.sessionId === scope.sessionId
257
+ && envelope.segmentId === scope.segmentId;
258
+ }
259
+
260
+ function milliseconds(value: string | undefined): number | undefined {
261
+ if (!value) return undefined;
262
+ const parsed = Date.parse(value);
263
+ return Number.isFinite(parsed) ? parsed : undefined;
264
+ }
265
+
266
+ /**
267
+ * Game-neutral coordinator for one participation. Source Plugins submit
268
+ * complete InputBatch values; Runtime persists them, assigns epoch_seq and
269
+ * drives the static Epoch Plugin graph.
270
+ */
271
+ export class Runtime<TPosition = unknown>
272
+ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
273
+ readonly adapterId: string;
274
+ readonly accountId: string;
275
+ readonly repository: RuntimeRepository;
276
+ readonly stateHistoryRepository: StateHistoryRepository<TPosition>;
277
+ readonly inputJournal: RuntimePersistenceStore<Record<string, any>, Record<string, unknown>>;
278
+ readonly observations = new ObservationRegistry();
279
+ readonly actions = new ActionRegistry();
280
+
281
+ private readonly eventCatalog: EventCatalog;
282
+ private readonly eventIngress: EventIngress;
283
+ private readonly stateStore = new CurrentStateStore<Record<string, any>>();
284
+ private readonly stateIngress: StateIngress<Record<string, any>>;
285
+ private readonly stateProvider: StateProvider<Record<string, any>, Record<string, any> | null>;
286
+ private readonly historyWriter: HistoryWriter<TPosition>;
287
+ private readonly stateObservers: FlushableStateIngressObserver<Record<string, any>>[];
288
+ private readonly participation: ParticipationManager;
289
+ private readonly pluginScheduler: RuntimePluginScheduler<Record<string, any>, Record<string, unknown>>;
290
+ private readonly connectionScopes = new Map<string, RuntimeScope>();
291
+ private readonly sourcePlugins = new Map<
292
+ string,
293
+ { plugin: RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>>; handle: RuntimeSourceStopHandle }
294
+ >();
295
+ private readonly observability?: TelemetryRecorder;
296
+ private readonly currentStateFromRuntimeState: (
297
+ state: Readonly<Record<string, any>>,
298
+ ) => Record<string, any> | null;
299
+ private readonly persistenceBase: Omit<RuntimePersistenceStatus, 'historyWriter'>;
300
+ private lastHistoryWriterHealthSignature: string | null = null;
301
+ private closed = false;
302
+ private closing = false;
303
+ private sourceInputOpen = true;
304
+ private closePromise?: Promise<void>;
305
+ private fatalError: Error | null = null;
306
+ private ownerRestartGapOpen = false;
307
+ private readyState: StateProviderResult<Record<string, any> | null> | null = null;
308
+ private readyScope: RuntimeScope | null = null;
309
+ private readyFrameSeq = 0;
310
+ private readyEventWatermark = 0;
311
+ private readyEpochSeq = 0;
312
+ private readyPluginStates: Record<string, RuntimeReadyPluginState> = {};
313
+ private readyPluginOutcomes: Record<string, RuntimeReadyPluginOutcome> = {};
314
+ private latestAcceptedEpochSeq = 0;
315
+ private readonly acceptedAgentStateByEpoch = new Map<
316
+ number,
317
+ StateProviderResult<Record<string, any> | null>
318
+ >();
319
+ private readonly epochCompletions = new Map<number, Promise<RuntimeEpochExecutionResult>>();
320
+ private readonly closedReadyAnchors = new Map<
321
+ number,
322
+ RuntimeReadyAnchor<Record<string, any> | null>
323
+ >();
324
+ private startPromise?: Promise<void>;
325
+
326
+ constructor(options: RuntimeOptions<TPosition>) {
327
+ this.adapterId = options.adapterId;
328
+ this.accountId = options.accountId;
329
+ this.observability = options.observability;
330
+ const warnings: string[] = [];
331
+
332
+ if (options.eventRepository) {
333
+ this.repository = options.eventRepository;
334
+ } else if (options.eventLedgerPath) {
335
+ const opened = SqliteEventRepository.open(options.eventLedgerPath);
336
+ if (opened.ok) {
337
+ this.repository = opened.repository;
338
+ } else {
339
+ const cause = opened.unavailable.cause
340
+ ? ` Cause: ${opened.unavailable.cause}`
341
+ : '';
342
+ throw new Error(
343
+ `EVENT_LEDGER_${opened.unavailable.code}: ${opened.unavailable.message}${cause}`,
344
+ );
345
+ }
346
+ } else {
347
+ // Pathless instances are useful to tests and embedded hosts that own
348
+ // both the runtime and every consumer. Production adapters should pass
349
+ // a durable repository or ledger path.
350
+ this.repository = new MemoryEventRepository();
351
+ }
352
+
353
+ let historyPersistence: RuntimePersistenceStatus['stateHistory'] = 'memory';
354
+ if (options.stateHistoryRepository) {
355
+ this.stateHistoryRepository = options.stateHistoryRepository;
356
+ historyPersistence = options.stateHistoryRepository instanceof SqliteStateHistoryRepository
357
+ ? 'sqlite'
358
+ : 'memory';
359
+ } else if (options.stateHistoryPath) {
360
+ try {
361
+ this.stateHistoryRepository = new SqliteStateHistoryRepository<TPosition>(options.stateHistoryPath);
362
+ historyPersistence = 'sqlite';
363
+ } catch (error) {
364
+ this.stateHistoryRepository = new MemoryStateHistoryRepository<TPosition>();
365
+ warnings.push(`STATE_HISTORY_SQLITE_UNAVAILABLE: ${error instanceof Error ? error.message : String(error)}`);
366
+ }
367
+ } else {
368
+ this.stateHistoryRepository = new MemoryStateHistoryRepository<TPosition>();
369
+ }
370
+ let inputJournalPersistence: RuntimePersistenceStatus['inputJournal'] = 'memory';
371
+ if (options.inputJournal) {
372
+ this.inputJournal = options.inputJournal;
373
+ inputJournalPersistence = options.inputJournal instanceof SqliteRuntimeInputJournal
374
+ ? 'sqlite'
375
+ : 'memory';
376
+ } else if (options.inputJournalPath) {
377
+ this.inputJournal = new SqliteRuntimeInputJournal(options.inputJournalPath);
378
+ inputJournalPersistence = 'sqlite';
379
+ } else {
380
+ this.inputJournal = new MemoryRuntimeInputJournal();
381
+ }
382
+ const eventPersistence = this.repository instanceof SqliteEventRepository ? 'sqlite' : 'memory';
383
+ this.persistenceBase = {
384
+ events: eventPersistence,
385
+ stateHistory: historyPersistence,
386
+ inputJournal: inputJournalPersistence,
387
+ warnings,
388
+ };
389
+ this.currentStateFromRuntimeState = options.currentStateFromRuntimeState
390
+ ?? ((state) => structuredClone(state));
391
+
392
+ this.historyWriter = new HistoryWriter(this.stateHistoryRepository, {
393
+ onHealthChanged: (health) => this.onHistoryWriterHealthChanged(health),
394
+ });
395
+ const historyObserver = options.historyObserverFactory?.(this.historyWriter);
396
+ this.stateObservers = [...(options.stateObservers ?? [])];
397
+ this.stateIngress = new StateIngress(this.stateStore, [
398
+ ...(historyObserver ? [historyObserver] : []),
399
+ ...this.stateObservers,
400
+ ]);
401
+ this.stateProvider = new StateProvider(
402
+ this.stateStore,
403
+ new StateFreshnessEvaluator(
404
+ options.stateFreshnessPolicy,
405
+ options.stateFreshnessPolicyResolver,
406
+ ),
407
+ (snapshot) => snapshot.backendState,
408
+ );
409
+ this.eventCatalog = options.eventCatalog;
410
+ this.eventIngress = new EventIngress(this.repository, this.eventCatalog);
411
+ for (const plugin of options.runtimeEpochPlugins ?? []) {
412
+ for (const output of plugin.produces?.events ?? []) {
413
+ const catalogEntry = options.eventCatalog.get(output);
414
+ if (!catalogEntry) {
415
+ throw new Error(
416
+ `Runtime Epoch Plugin "${plugin.id}" output "${output}" `
417
+ + 'is not registered in the Event Catalog.',
418
+ );
419
+ }
420
+ if (catalogEntry.producer !== 'local_synth') {
421
+ throw new Error(
422
+ `Runtime Epoch Plugin "${plugin.id}" cannot own backend Event "${output}".`,
423
+ );
424
+ }
425
+ }
426
+ }
427
+ this.pluginScheduler = new RuntimePluginScheduler({
428
+ plugins: options.runtimeEpochPlugins,
429
+ inputJournal: this.inputJournal,
430
+ pluginStore: this.inputJournal,
431
+ stateHistory: this.stateHistoryRepository,
432
+ commitInputEvents: (work) => this.commitInputEvents(work),
433
+ listEvents: ({ scope, ...filter }) => this.repository.listCommittedEvents({
434
+ sessionId: scope.sessionId,
435
+ segmentId: scope.segmentId,
436
+ afterCommitSeq: filter.afterCommitSeq,
437
+ maxCommitSeq: filter.maxCommitSeq,
438
+ ...(filter.epochSeq === undefined ? {} : { epochSeq: filter.epochSeq }),
439
+ ...(filter.maxEpochSeq === undefined ? {} : { maxEpochSeq: filter.maxEpochSeq }),
440
+ ...(filter.types ? { types: [...filter.types] } : {}),
441
+ order: 'asc',
442
+ }),
443
+ publishEvent: (pluginId, epoch, proposal, proposalIndex) => this.eventIngress.publish(
444
+ this.pluginEventInput(pluginId, epoch, proposal, proposalIndex),
445
+ ),
446
+ highWaterCommitSeq: (scope) => this.repository.highWaterCommitSeq(
447
+ scope.sessionId,
448
+ ),
449
+ currentSegment: () => {
450
+ const segment = this.currentSegment();
451
+ return {
452
+ kind: segment.kind,
453
+ ...(segment.identity === undefined ? {} : { identity: segment.identity }),
454
+ };
455
+ },
456
+ capabilitiesFor: (plugin, scope, signal, epochSeq) => this.pluginCapabilityAccess(
457
+ plugin,
458
+ scope,
459
+ signal,
460
+ epochSeq,
461
+ ),
462
+ onEpochClosed: (work, result) => this.onEpochClosed(work.epoch, work.frame.frameSeq, result),
463
+ onFatalError: (error, pluginId, scope) => {
464
+ this.fatalError = error instanceof Error ? error : new Error(String(error));
465
+ this.actions.beginStopping('runtime_plugin_fatal');
466
+ this.observability?.error('runtime.plugin.fatal', this.fatalError, {
467
+ plugin_id: pluginId,
468
+ }, { component: 'runtime.epoch', scope });
469
+ },
470
+ onDiagnostic: (name, attributes, scope, severity = 'debug') => {
471
+ this.observability?.log(
472
+ severity,
473
+ name,
474
+ attributes,
475
+ { component: 'runtime.epoch', scope },
476
+ );
477
+ },
478
+ });
479
+
480
+ const accountScope = { adapterId: this.adapterId, accountId: this.accountId };
481
+ const durableCurrent = this.repository.currentScope(accountScope);
482
+ const resumesBySessionKey = options.resumeKey !== undefined
483
+ && durableCurrent?.session.resumeKey === options.resumeKey;
484
+ const resumesByCurrentSegment = options.initialSegment.identity !== undefined
485
+ && durableCurrent?.segment.kind === options.initialSegment.kind
486
+ && durableCurrent.segment.scopeRef === options.initialSegment.identity;
487
+ const canResume = !!options.resume
488
+ && !!durableCurrent
489
+ && durableCurrent.session.status === 'open'
490
+ && (resumesBySessionKey || resumesByCurrentSegment);
491
+ if (!canResume && durableCurrent) this.sealDurableScope(durableCurrent);
492
+
493
+ this.participation = new ParticipationManager({
494
+ initial: canResume && durableCurrent ? participationFromCurrent(durableCurrent) : undefined,
495
+ onTransition: (transition) => this.persistTransition(transition),
496
+ });
497
+ if (!canResume) {
498
+ this.participation.openSession({
499
+ adapterId: this.adapterId,
500
+ accountId: this.accountId,
501
+ resumeKey: options.resumeKey,
502
+ mode: options.mode,
503
+ initialSegment: options.initialSegment,
504
+ });
505
+ } else {
506
+ if (options.mode) this.participation.updateMode(options.mode);
507
+ const restoredSegmentId = this.participation.requireSnapshot().segment.id;
508
+ const activated = this.participation.activateSegment(
509
+ options.initialSegment.kind,
510
+ options.initialSegment.identity,
511
+ );
512
+ if (activated.segment.id === restoredSegmentId) {
513
+ // A live-only source may have advanced while the owner was down. The
514
+ // logical segment resumes, but its history completeness cannot.
515
+ this.openStateScope(activated, false);
516
+ this.ownerRestartGapOpen = true;
517
+ this.enqueueOwnerRestartGap('stream_gap_started');
518
+ }
519
+ }
520
+ this.actions.activateScope(this.scope());
521
+ this.readyScope = this.scope();
522
+ this.readyState = this.readAgentState();
523
+ this.readyEventWatermark = this.repository.highWaterCommitSeq(
524
+ this.scope().sessionId,
525
+ );
526
+
527
+ const scope = this.scope();
528
+ this.observability?.log('info', 'runtime.owner.started', {
529
+ adapter_id: this.adapterId,
530
+ persistence: this.persistence,
531
+ resumed: canResume,
532
+ resume_match: canResume
533
+ ? resumesBySessionKey ? 'session_key' : 'current_segment'
534
+ : 'none',
535
+ }, { component: 'runtime', scope });
536
+ for (const warning of warnings) {
537
+ this.observability?.log('warn', 'runtime.persistence.degraded', {
538
+ warning,
539
+ event_repository: eventPersistence,
540
+ state_history_repository: historyPersistence,
541
+ }, { component: 'runtime.persistence', scope });
542
+ }
543
+ }
544
+
545
+ /** Dynamic owner health; unlike the repository choice, writer health can change at runtime. */
546
+ get persistence(): RuntimePersistenceStatus {
547
+ return {
548
+ ...this.persistenceBase,
549
+ warnings: [...this.persistenceBase.warnings],
550
+ historyWriter: this.historyWriterHealth(),
551
+ };
552
+ }
553
+
554
+ historyWriterHealth(): PublicHistoryWriterHealth {
555
+ return {
556
+ ...this.historyWriter.health(),
557
+ degradedScopes: this.historyWriter.degradedScopeHealth().map((entry) => {
558
+ const { accountId: _accountId, ...scope } = entry.scope;
559
+ return { ...entry, scope };
560
+ }),
561
+ };
562
+ }
563
+
564
+ scope(): RuntimeScope {
565
+ return runtimeScope(this.participation.requireSnapshot());
566
+ }
567
+
568
+ currentSegment(): { scope: RuntimeScope; kind: string; identity?: string } {
569
+ const snapshot = this.participation.requireSnapshot();
570
+ return {
571
+ scope: runtimeScope(snapshot),
572
+ kind: snapshot.segment.kind,
573
+ ...(snapshot.segment.identity === undefined ? {} : { identity: snapshot.segment.identity }),
574
+ };
575
+ }
576
+
577
+ publicScope(): PublicRuntimeScope {
578
+ return this.publicScopeFor(this.scope());
579
+ }
580
+
581
+ private publicScopeFor(runtimeScope: RuntimeScope): PublicRuntimeScope {
582
+ const { accountId: _accountId, ...scope } = runtimeScope;
583
+ return scope;
584
+ }
585
+
586
+ runtimeEpochPluginDescriptors(): ReturnType<RuntimePluginScheduler['descriptors']> {
587
+ return this.pluginScheduler.descriptors();
588
+ }
589
+
590
+ runtimePluginDescriptors(): RuntimePluginDescriptor[] {
591
+ return [
592
+ ...[...this.sourcePlugins.values()].map(({ plugin }) => ({
593
+ kind: 'source' as const,
594
+ id: plugin.id,
595
+ version: plugin.version,
596
+ })),
597
+ ...this.pluginScheduler.descriptors(),
598
+ ];
599
+ }
600
+
601
+ /** Start the current scope's Epoch Plugin graph before external input arrives. */
602
+ async start(): Promise<void> {
603
+ this.assertOpen();
604
+ if (!this.startPromise) {
605
+ const attempt = (async () => {
606
+ await this.pluginScheduler.activateScope(this.scope());
607
+ await this.recoverOpenEpochs();
608
+ })();
609
+ this.startPromise = attempt.catch((error) => {
610
+ this.startPromise = undefined;
611
+ throw error;
612
+ });
613
+ }
614
+ await this.startPromise;
615
+ }
616
+
617
+ async startSourcePlugin(
618
+ plugin: RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>>,
619
+ ): Promise<void> {
620
+ this.assertOpen();
621
+ if (plugin.kind !== 'source') throw new TypeError(`Runtime Source Plugin ${plugin.id} has invalid kind.`);
622
+ if (!plugin.id?.trim()) throw new TypeError('Runtime Source Plugin id must not be empty.');
623
+ if (!plugin.version?.trim()) throw new TypeError(`Runtime Source Plugin ${plugin.id} version must not be empty.`);
624
+ if (this.sourcePlugins.has(plugin.id)) throw new Error(`Duplicate Runtime Source Plugin id: ${plugin.id}`);
625
+ if (this.pluginScheduler.descriptors().some((candidate) => candidate.id === plugin.id)) {
626
+ throw new Error(`Runtime Plugin id is shared by Source and Epoch Plugin: ${plugin.id}`);
627
+ }
628
+ await this.start();
629
+ const handle = await plugin.start(this);
630
+ if (!handle || typeof handle.stop !== 'function') {
631
+ throw new TypeError(`Runtime Source Plugin ${plugin.id} did not return a stop handle.`);
632
+ }
633
+ this.sourcePlugins.set(plugin.id, { plugin, handle });
634
+ }
635
+
636
+ async activateSegment(kind: string, identity?: string): Promise<RuntimeScope> {
637
+ this.assertOpen();
638
+ const previous = this.scope();
639
+ const current = this.participation.requireSnapshot().segment;
640
+ const changesSegment = current.kind !== kind
641
+ || (
642
+ identity !== undefined
643
+ && current.identity !== undefined
644
+ && current.identity !== identity
645
+ );
646
+ if (changesSegment) await this.pluginScheduler.flush('segment_ending');
647
+ const next = runtimeScope(this.participation.activateSegment(kind, identity));
648
+ if (previous.segmentId !== next.segmentId) {
649
+ this.resetReadyView(next);
650
+ this.observability?.log('info', 'runtime.scope.switched', {
651
+ previous_segment_id: previous.segmentId,
652
+ previous_segment_seq: previous.segmentSeq,
653
+ segment_kind: kind,
654
+ has_identity: !!identity,
655
+ }, { component: 'runtime', scope: next });
656
+ }
657
+ return next;
658
+ }
659
+
660
+ adoptResumeKey(resumeKey: string): RuntimeScope {
661
+ this.assertOpen();
662
+ return runtimeScope(this.participation.adoptResumeKey(resumeKey));
663
+ }
664
+
665
+ updateMode(mode: string): RuntimeScope {
666
+ this.assertOpen();
667
+ return runtimeScope(this.participation.updateMode(mode));
668
+ }
669
+
670
+ bindConnection(sourceId: string, connectionId: string, atMs = Date.now()): RuntimeScope {
671
+ this.assertOpen();
672
+ const key = this.connectionKey(sourceId, connectionId);
673
+ const current = this.scope();
674
+ const existing = this.connectionScopes.get(key);
675
+ if (existing) {
676
+ if (!sameScope(existing, current)) {
677
+ throw new Error('Connection is already frozen to a different runtime scope.');
678
+ }
679
+ if (this.participation.connectionId(sourceId) !== connectionId) {
680
+ throw new Error('Connection has already been superseded by a newer connection.');
681
+ }
682
+ return structuredClone(existing);
683
+ }
684
+ const snapshot = this.participation.bindConnection(sourceId, connectionId);
685
+ this.stateIngress.openScope(runtimeScope(snapshot), atMs);
686
+ this.stateIngress.connectionOpened(connectionId, atMs);
687
+ if (this.ownerRestartGapOpen) {
688
+ this.ownerRestartGapOpen = false;
689
+ this.enqueueOwnerRestartGap('stream_gap_ended', connectionId, atMs);
690
+ }
691
+ const scope = runtimeScope(snapshot);
692
+ this.connectionScopes.set(key, structuredClone(scope));
693
+ this.observability?.log('info', 'runtime.connection.bound', {
694
+ source_id: sourceId,
695
+ }, { component: 'runtime.transport', scope: { ...scope, connectionId } });
696
+ return scope;
697
+ }
698
+
699
+ /** Explicitly move a still-live physical connection to a new logical segment. */
700
+ rebindConnectionScope(sourceId: string, connectionId: string, atMs = Date.now()): RuntimeScope {
701
+ this.assertOpen();
702
+ if (this.participation.connectionId(sourceId) !== connectionId) {
703
+ throw new Error('Only the active connection can be rebound to a new runtime scope.');
704
+ }
705
+ const scope = this.scope();
706
+ const key = this.connectionKey(sourceId, connectionId);
707
+ const existing = this.connectionScopes.get(key);
708
+ if (existing && sameScope(existing, scope)) return structuredClone(scope);
709
+ this.connectionScopes.set(key, structuredClone(scope));
710
+ this.stateIngress.openScope(scope, atMs);
711
+ this.stateIngress.connectionOpened(connectionId, atMs);
712
+ this.observability?.log('info', 'runtime.connection.scope_rebound', {
713
+ source_id: sourceId,
714
+ }, { component: 'runtime.transport', scope: { ...scope, connectionId } });
715
+ return structuredClone(scope);
716
+ }
717
+
718
+ connectionScope(sourceId: string, connectionId: string): RuntimeScope | null {
719
+ const scope = this.connectionScopes.get(this.connectionKey(sourceId, connectionId));
720
+ return scope ? structuredClone(scope) : null;
721
+ }
722
+
723
+ isActiveConnection(sourceId: string, connectionId: string): boolean {
724
+ return this.participation.connectionId(sourceId) === connectionId;
725
+ }
726
+
727
+ connectionChanged(
728
+ sourceId: string,
729
+ connectionId: string,
730
+ state: RuntimeConnectionState,
731
+ atMs = Date.now(),
732
+ ): void {
733
+ if (this.closed || this.participation.connectionId(sourceId) !== connectionId) return;
734
+ this.stateIngress.connectionChanged(connectionId, state, atMs);
735
+ const scope = this.scope();
736
+ this.observability?.log(
737
+ state === 'connected' ? 'info' : 'warn',
738
+ `runtime.connection.${state}`,
739
+ { source_id: sourceId },
740
+ { component: 'runtime.transport', scope: { ...scope, connectionId } },
741
+ );
742
+ }
743
+
744
+ connectionLiveness(sourceId: string, connectionId: string, atMs = Date.now()): boolean {
745
+ if (this.closed || this.participation.connectionId(sourceId) !== connectionId) return false;
746
+ return this.stateIngress.livenessReceived(connectionId, atMs);
747
+ }
748
+
749
+ diagnostic(
750
+ name: string,
751
+ attributes: Readonly<Record<string, unknown>> = {},
752
+ severity: 'debug' | 'info' | 'warn' | 'error' = 'debug',
753
+ ): void {
754
+ this.observability?.log(severity, name, { ...attributes }, {
755
+ component: 'runtime.source',
756
+ scope: this.publicScope(),
757
+ });
758
+ }
759
+
760
+ /**
761
+ * The fixed Runtime intake boundary. Acceptance persists the complete input
762
+ * immediately; plugin work is queued independently so Source intake never
763
+ * waits for a slow perception or strategy invocation.
764
+ */
765
+ async acceptInputBatch(
766
+ batch: RuntimeInputBatch<Record<string, any>, Record<string, unknown>>,
767
+ ): Promise<RuntimeInputAcceptance<Record<string, any>, Record<string, unknown>>> {
768
+ this.assertSourceInputOpen();
769
+ let acceptance: RuntimeInputAcceptance<Record<string, any>, Record<string, unknown>>;
770
+ try {
771
+ assertRuntimeInputBatch(batch);
772
+ if (!sameScope(batch.scope, this.scope())) {
773
+ throw new Error('Runtime InputBatch scope does not match the active participation segment.');
774
+ }
775
+ acceptance = this.inputJournal.accept(batch);
776
+ } catch (error) {
777
+ this.observability?.error('runtime.input.rejected', error, {
778
+ source_id: batch?.sourceId,
779
+ source_key: batch?.sourceKey,
780
+ reason: error instanceof Error ? error.name : 'invalid_input',
781
+ }, { component: 'runtime.input', scope: this.publicScope() });
782
+ throw error;
783
+ }
784
+ if (!acceptance.inserted) {
785
+ this.observability?.log('debug', 'runtime.input.duplicate', {
786
+ source_id: batch.sourceId,
787
+ source_key: batch.sourceKey,
788
+ epoch_seq: acceptance.epoch.epochSeq,
789
+ }, { component: 'runtime.input', scope: this.publicScope() });
790
+ return acceptance;
791
+ }
792
+
793
+ const epoch = acceptance.epoch;
794
+ this.latestAcceptedEpochSeq = Math.max(this.latestAcceptedEpochSeq, epoch.epochSeq);
795
+ const previousFrame = this.stateHistoryRepository.latestStateFrame(epoch.scope);
796
+ const frame = this.stateHistoryRepository.appendStateFrame({
797
+ epochSeq: epoch.epochSeq,
798
+ scope: epoch.scope,
799
+ sourceId: epoch.sourceId,
800
+ connectionId: epoch.connectionId,
801
+ sourceKey: `runtime-epoch:${epoch.epochSeq}`,
802
+ sourceSeq: epoch.sourceSeq,
803
+ backendTick: typeof epoch.domainTick === 'number' ? epoch.domainTick : undefined,
804
+ observedAtMs: milliseconds(epoch.observedAt),
805
+ receivedAtMs: milliseconds(epoch.receivedAt) ?? Date.now(),
806
+ state: epoch.state,
807
+ }).frame;
808
+
809
+ const projectedState = this.currentStateFromRuntimeState(epoch.state);
810
+ if (projectedState !== null) {
811
+ const current = this.stateIngress.snapshot();
812
+ if (current.meta.connectionId !== epoch.connectionId) {
813
+ this.stateIngress.connectionOpened(
814
+ epoch.connectionId,
815
+ milliseconds(epoch.receivedAt) ?? Date.now(),
816
+ );
817
+ }
818
+ const applied = this.stateIngress.accept({
819
+ scope: epoch.scope,
820
+ sourceId: epoch.sourceId,
821
+ connectionId: epoch.connectionId,
822
+ payload: projectedState,
823
+ sourceKey: `runtime-epoch:${epoch.epochSeq}`,
824
+ sourceSeq: epoch.epochSeq,
825
+ backendTick: typeof epoch.domainTick === 'number' ? epoch.domainTick : undefined,
826
+ observedAtMs: milliseconds(epoch.observedAt),
827
+ receivedAtMs: milliseconds(epoch.receivedAt) ?? Date.now(),
828
+ });
829
+ if (!applied.accepted) {
830
+ throw new Error(`Runtime current-State projection was rejected: ${applied.reason}.`);
831
+ }
832
+ }
833
+ const currentState = this.readAgentState();
834
+ this.acceptedAgentStateByEpoch.set(epoch.epochSeq, structuredClone(currentState));
835
+
836
+ this.observability?.log('debug', 'runtime.input.accepted', {
837
+ source_id: epoch.sourceId,
838
+ source_seq: epoch.sourceSeq,
839
+ source_key: epoch.sourceKey,
840
+ epoch_seq: epoch.epochSeq,
841
+ domain_tick: epoch.domainTick,
842
+ event_count: epoch.events.length,
843
+ completeness: epoch.completeness,
844
+ coalescing: epoch.coalescing ?? 'allowed',
845
+ stage: typeof epoch.state.stage === 'string' ? epoch.state.stage : undefined,
846
+ cause: typeof epoch.state.cause === 'string' ? epoch.state.cause : undefined,
847
+ connection: typeof epoch.state.connection === 'string' ? epoch.state.connection : undefined,
848
+ game_snapshot_status: epoch.state.game_snapshot?.status,
849
+ }, { component: 'runtime.input', scope: this.publicScope() });
850
+
851
+ const completion = this.pluginScheduler.enqueue({
852
+ epoch,
853
+ frame,
854
+ currentState,
855
+ previousState: previousFrame?.state ?? null,
856
+ epochEvents: [],
857
+ });
858
+ this.trackEpochCompletion(epoch.epochSeq, completion);
859
+ void completion.catch((error) => {
860
+ this.observability?.error('runtime.epoch.processing_failed', error, {
861
+ epoch_seq: epoch.epochSeq,
862
+ source_id: epoch.sourceId,
863
+ }, { component: 'runtime.epoch', scope: this.publicScope() });
864
+ });
865
+ return acceptance;
866
+ }
867
+
868
+ readState(nowMs = Date.now()): StateProviderResult<Record<string, any> | null> {
869
+ return this.stateProvider.read(this.scope(), nowMs);
870
+ }
871
+
872
+ /** Agent-safe State view. Internal account identity never crosses owner IPC. */
873
+ readAgentState(nowMs = Date.now()): StateProviderResult<Record<string, any> | null> {
874
+ const result = this.readState(nowMs);
875
+ const scope = result.stateStatus.scope;
876
+ return {
877
+ ...result,
878
+ stateStatus: {
879
+ ...result.stateStatus,
880
+ scope: scope ? this.publicScope() as any : null,
881
+ },
882
+ };
883
+ }
884
+
885
+ async queryObservation<Q, R>(
886
+ capability: string,
887
+ request: Q,
888
+ expectedScope: ExpectedRuntimeScope,
889
+ ): Promise<ObservationResult<R>> {
890
+ const scope = this.assertExpectedScope(expectedScope);
891
+ return this.observations.query<Q, R>(capability, request, scope);
892
+ }
893
+
894
+ async performAction<A, R>(
895
+ capability: string,
896
+ action: A,
897
+ expectedScope: ExpectedRuntimeScope,
898
+ caller: ActionCaller,
899
+ admission: ActionAdmissionOptions = {},
900
+ ): Promise<ActionResult<R>> {
901
+ const scope = this.assertExpectedScope(expectedScope);
902
+ const startedAt = Date.now();
903
+ try {
904
+ const result = await this.actions.perform<A, R>(capability, action, scope, caller, {
905
+ ...admission,
906
+ latestAcceptedState: () => this.latestAcceptedActionState(scope),
907
+ });
908
+ const attributes = {
909
+ capability,
910
+ caller_kind: caller.kind,
911
+ status: result.status,
912
+ ...(result.source ? { action_source: result.source } : {}),
913
+ ...(result.actionOutcome ? { action_outcome: result.actionOutcome } : {}),
914
+ duration_ms: Date.now() - startedAt,
915
+ };
916
+ const context = {
917
+ component: 'runtime.actions',
918
+ scope,
919
+ correlation: {
920
+ actionId: result.actionId,
921
+ ...(caller.kind === 'strategy' ? { strategyRunId: caller.id } : {}),
922
+ ...(caller.kind === 'task' ? { taskId: caller.id } : {}),
923
+ },
924
+ };
925
+ if (result.status === 'failure') {
926
+ const summary = summarizeActionError(result.error);
927
+ const severity = actionFailureDiagnosticSeverity(result);
928
+ if (severity === 'warn') {
929
+ this.observability?.log('warn', 'runtime.action.failed', {
930
+ ...attributes,
931
+ error_code: summary.code,
932
+ http_status: summary.httpStatus,
933
+ error_message_present: summary.messagePresent,
934
+ error_message_length: summary.messageLength,
935
+ }, context);
936
+ } else {
937
+ this.observability?.error('runtime.action.failed', {
938
+ name: 'ActionFailure',
939
+ ...(summary.code ? { code: summary.code } : {}),
940
+ }, {
941
+ ...attributes,
942
+ error_code: summary.code,
943
+ http_status: summary.httpStatus,
944
+ error_message_present: summary.messagePresent,
945
+ error_message_length: summary.messageLength,
946
+ }, context);
947
+ }
948
+ } else if (result.status === 'deferred') {
949
+ const summary = summarizeActionError(result.error);
950
+ this.observability?.log('info', 'runtime.action.deferred', {
951
+ ...attributes,
952
+ control_code: summary.code ?? 'CONTROL_DEFERRED',
953
+ }, context);
954
+ } else {
955
+ this.observability?.log(
956
+ result.status === 'partial' ? 'warn' : 'info',
957
+ 'runtime.action.completed',
958
+ attributes,
959
+ context,
960
+ );
961
+ }
962
+ return result;
963
+ } catch (error) {
964
+ const summary = summarizeActionError(error);
965
+ this.observability?.error('runtime.action.failed', {
966
+ name: error instanceof Error ? error.name : 'ActionFailure',
967
+ ...(summary.code ? { code: summary.code } : {}),
968
+ }, {
969
+ capability,
970
+ caller_kind: caller.kind,
971
+ duration_ms: Date.now() - startedAt,
972
+ error_message_present: summary.messagePresent,
973
+ error_message_length: summary.messageLength,
974
+ }, {
975
+ component: 'runtime.actions',
976
+ scope,
977
+ correlation: caller.kind === 'strategy'
978
+ ? { strategyRunId: caller.id }
979
+ : caller.kind === 'task'
980
+ ? { taskId: caller.id }
981
+ : undefined,
982
+ });
983
+ throw error;
984
+ }
985
+ }
986
+
987
+ /**
988
+ * Non-consuming view bounded by the latest fully closed epoch. Consumers
989
+ * get one State/Event position without changing any delivery cursor.
990
+ */
991
+ readReadyView(afterCommitSeq = 0, limit = 100): RuntimeReadyView {
992
+ const scope = this.scope();
993
+ const readyForCurrentScope = !!this.readyScope && sameScope(this.readyScope, scope);
994
+ const boundedLimit = Math.max(1, Math.min(500, Math.trunc(limit) || 100));
995
+ const pending = this.repository.listCommittedEvents({
996
+ sessionId: scope.sessionId,
997
+ segmentId: scope.segmentId,
998
+ afterCommitSeq,
999
+ maxCommitSeq: readyForCurrentScope ? this.readyEventWatermark : 0,
1000
+ maxEpochSeq: readyForCurrentScope ? this.readyEpochSeq : 0,
1001
+ order: 'asc',
1002
+ limit: boundedLimit + 1,
1003
+ });
1004
+ const events = pending.slice(0, boundedLimit);
1005
+ return {
1006
+ scope: this.publicScope(),
1007
+ state: structuredClone(
1008
+ readyForCurrentScope ? this.readyState ?? this.readAgentState() : this.readAgentState(),
1009
+ ),
1010
+ pluginStates: structuredClone(readyForCurrentScope ? this.readyPluginStates : {}),
1011
+ pluginOutcomes: structuredClone(readyForCurrentScope ? this.readyPluginOutcomes : {}),
1012
+ events,
1013
+ throughCommitSeq: events.at(-1)?.commitSeq ?? afterCommitSeq,
1014
+ frameSeq: readyForCurrentScope ? this.readyFrameSeq : 0,
1015
+ eventWatermark: readyForCurrentScope ? this.readyEventWatermark : 0,
1016
+ epochSeq: readyForCurrentScope ? this.readyEpochSeq : 0,
1017
+ hasMore: pending.length > events.length,
1018
+ };
1019
+ }
1020
+
1021
+ /** Waits for one exact epoch and returns the immutable State/Event view closed at it. */
1022
+ async waitForEpochReadyView(
1023
+ epochSeq: number,
1024
+ afterCommitSeq = 0,
1025
+ limit = 100,
1026
+ ): Promise<RuntimeReadyView> {
1027
+ if (!Number.isInteger(epochSeq) || epochSeq <= 0) {
1028
+ throw new TypeError('Runtime epochSeq must be a positive integer.');
1029
+ }
1030
+ let anchor = this.closedReadyAnchors.get(epochSeq);
1031
+ if (!anchor) {
1032
+ const completion = this.epochCompletions.get(epochSeq);
1033
+ if (!completion) throw new Error(`Runtime epoch ${epochSeq} is not pending in this Runtime.`);
1034
+ await completion;
1035
+ anchor = this.closedReadyAnchors.get(epochSeq);
1036
+ }
1037
+ if (!anchor) throw new Error(`Runtime epoch ${epochSeq} closed without a Ready View.`);
1038
+ return this.readyViewFromAnchor(anchor, afterCommitSeq, limit);
1039
+ }
1040
+
1041
+ async flush(): Promise<void> {
1042
+ await this.pluginScheduler.waitForIdle();
1043
+ await this.historyWriter.flush();
1044
+ await Promise.all(this.stateObservers.map((observer) => observer.flush?.()));
1045
+ }
1046
+
1047
+ close(): Promise<void> {
1048
+ if (!this.closePromise) this.closePromise = this.closeInternal();
1049
+ return this.closePromise;
1050
+ }
1051
+
1052
+ private async closeInternal(): Promise<void> {
1053
+ if (this.closed) return;
1054
+ this.closing = true;
1055
+ const closingScope = this.scope();
1056
+ const failures: unknown[] = [];
1057
+ this.observability?.log('info', 'runtime.shutdown.started', {
1058
+ latest_accepted_epoch_seq: this.latestAcceptedEpochSeq,
1059
+ ready_epoch_seq: this.readyEpochSeq,
1060
+ ready_event_watermark: this.readyEventWatermark,
1061
+ }, { component: 'runtime.shutdown', scope: closingScope });
1062
+ // Fence new side effects first. Already-admitted Actions may still return
1063
+ // Source input, so Sources remain active until those Actions settle.
1064
+ this.actions.beginStopping('runtime_closed');
1065
+ const sources = [...this.sourcePlugins.values()].reverse();
1066
+ try {
1067
+ try {
1068
+ await this.actions.waitForIdle();
1069
+ } catch (error) {
1070
+ failures.push(error);
1071
+ }
1072
+ const sourceStops = await Promise.allSettled(
1073
+ sources.map(({ handle }) => Promise.resolve().then(() => handle.stop('shutdown'))),
1074
+ );
1075
+ for (const settlement of sourceStops) {
1076
+ if (settlement.status === 'rejected') failures.push(settlement.reason);
1077
+ }
1078
+ this.sourcePlugins.clear();
1079
+ this.sourceInputOpen = false;
1080
+ const terminalEpochSeq = this.latestAcceptedEpochSeq;
1081
+ this.observability?.log('info', 'runtime.shutdown.drain_started', {
1082
+ terminal_epoch_seq: terminalEpochSeq,
1083
+ ready_epoch_seq: this.readyEpochSeq,
1084
+ ready_event_watermark: this.readyEventWatermark,
1085
+ }, { component: 'runtime.shutdown', scope: closingScope });
1086
+ try {
1087
+ await this.pluginScheduler.close();
1088
+ } catch (error) {
1089
+ failures.push(error);
1090
+ }
1091
+ try {
1092
+ await this.historyWriter.flush();
1093
+ await Promise.all(this.stateObservers.map((observer) => observer.flush?.()));
1094
+ await Promise.all(this.stateObservers.map((observer) => observer.close?.()));
1095
+ } catch (error) {
1096
+ failures.push(error);
1097
+ }
1098
+ // A Runtime session is the lifetime of one local Owner, not the lifetime
1099
+ // of the backend participation. A later Owner may recover the same room,
1100
+ // queue, or game from authoritative backend status, but it must not leave
1101
+ // this process's durable session/segment marked current after shutdown.
1102
+ try {
1103
+ this.participation.closeSession('owner_stopped');
1104
+ } catch (error) {
1105
+ failures.push(error);
1106
+ }
1107
+ if (failures.length > 0) {
1108
+ throw new AggregateError(failures, `${failures.length} Runtime shutdown operation(s) failed.`);
1109
+ }
1110
+ this.observability?.log('info', 'runtime.shutdown.drain_completed', {
1111
+ terminal_epoch_seq: terminalEpochSeq,
1112
+ ready_epoch_seq: this.readyEpochSeq,
1113
+ ready_event_watermark: this.readyEventWatermark,
1114
+ event_watermark: this.repository.highWaterCommitSeq(
1115
+ closingScope.sessionId,
1116
+ closingScope.segmentId,
1117
+ ),
1118
+ }, { component: 'runtime.shutdown', scope: closingScope });
1119
+ } catch (error) {
1120
+ this.observability?.error('runtime.shutdown.drain_incomplete', error, {
1121
+ terminal_epoch_seq: this.latestAcceptedEpochSeq,
1122
+ ready_epoch_seq: this.readyEpochSeq,
1123
+ }, { component: 'runtime.shutdown', scope: closingScope });
1124
+ throw error;
1125
+ } finally {
1126
+ this.sourceInputOpen = false;
1127
+ this.closing = false;
1128
+ this.closed = true;
1129
+ this.stateHistoryRepository.close?.();
1130
+ this.inputJournal.close?.();
1131
+ this.repository.close?.();
1132
+ this.observability?.log('info', 'runtime.owner.stopped', {
1133
+ event_repository: this.persistence.events,
1134
+ state_history_repository: this.persistence.stateHistory,
1135
+ }, { component: 'runtime', scope: closingScope });
1136
+ if (this.observability) await this.observability.flushWithin(2_000).catch(() => false);
1137
+ }
1138
+ }
1139
+
1140
+ private sourceEventInput(
1141
+ epoch: RuntimeEpoch<Record<string, any>, Record<string, unknown>>,
1142
+ sourceEvent: RuntimeSourceEvent<Record<string, unknown>>,
1143
+ index: number,
1144
+ ): PublishEventInput {
1145
+ if (typeof sourceEvent.type !== 'string' || !sourceEvent.type.trim()) {
1146
+ throw new TypeError(`Runtime InputBatch Event ${index} requires type.`);
1147
+ }
1148
+ return {
1149
+ epochSeq: epoch.epochSeq,
1150
+ type: sourceEvent.type,
1151
+ producer: sourceEvent.producer ?? 'backend_push',
1152
+ sessionId: epoch.scope.sessionId,
1153
+ segmentId: epoch.scope.segmentId,
1154
+ payload: sourceEvent.payload,
1155
+ occurredAt: sourceEvent.observedAt ?? epoch.observedAt,
1156
+ receivedAt: sourceEvent.receivedAt ?? epoch.receivedAt,
1157
+ eventId: runtimeSourceEventId(epoch, sourceEvent, index),
1158
+ source: {
1159
+ sourceId: epoch.sourceId,
1160
+ eventId: sourceEvent.sourceEventId,
1161
+ sequence: sourceEvent.sourceSeq,
1162
+ connectionId: epoch.connectionId,
1163
+ replayed: sourceEvent.replayed,
1164
+ checkpoint: sourceEvent.checkpoint,
1165
+ },
1166
+ };
1167
+ }
1168
+
1169
+ private pluginEventInput(
1170
+ pluginId: string,
1171
+ epoch: RuntimeEpoch<Record<string, any>, Record<string, unknown>>,
1172
+ proposal: RuntimeEventProposal,
1173
+ proposalIndex: number,
1174
+ ): PublishEventInput {
1175
+ const eventId = this.epochEventId(epoch, pluginId, proposal, proposalIndex);
1176
+ return {
1177
+ epochSeq: epoch.epochSeq,
1178
+ type: proposal.type,
1179
+ producer: 'local_synth',
1180
+ producerPluginId: pluginId,
1181
+ producerOutputIndex: proposalIndex,
1182
+ sessionId: epoch.scope.sessionId,
1183
+ segmentId: epoch.scope.segmentId,
1184
+ payload: proposal.payload,
1185
+ occurredAt: proposal.occurredAt,
1186
+ receivedAt: new Date().toISOString(),
1187
+ eventId,
1188
+ source: {
1189
+ sourceId: `runtime-plugin:${pluginId}`,
1190
+ eventId,
1191
+ connectionId: epoch.connectionId,
1192
+ },
1193
+ };
1194
+ }
1195
+
1196
+ private async commitInputEvents(
1197
+ work: RuntimeEpochWork<Record<string, any>, Record<string, unknown>>,
1198
+ ): Promise<CanonicalEvent[]> {
1199
+ const { epoch } = work;
1200
+ const committedEvents: CanonicalEvent[] = [];
1201
+ for (const [index, sourceEvent] of epoch.events.entries()) {
1202
+ if (!this.eventCatalog.get(sourceEvent.type)) {
1203
+ this.observability?.log('warn', 'runtime.backend_event.unregistered', {
1204
+ event_type: sourceEvent.type,
1205
+ source_id: epoch.sourceId,
1206
+ epoch_seq: epoch.epochSeq,
1207
+ }, { component: 'runtime.event-catalog', scope: this.publicScope() });
1208
+ }
1209
+ const committed = await this.eventIngress.publish(this.sourceEventInput(epoch, sourceEvent, index));
1210
+ if (committed.inserted) committedEvents.push(committed.event);
1211
+ }
1212
+ return committedEvents;
1213
+ }
1214
+
1215
+ private async recoverOpenEpochs(): Promise<void> {
1216
+ const scope = this.scope();
1217
+ const openEpochs: RuntimeEpoch<Record<string, any>, Record<string, unknown>>[] = [];
1218
+ let afterEpochSeq = 0;
1219
+ while (true) {
1220
+ const page = this.inputJournal.listOpen(scope, afterEpochSeq, 10_000);
1221
+ if (page.length === 0) break;
1222
+ openEpochs.push(...page);
1223
+ afterEpochSeq = page.at(-1)!.epochSeq;
1224
+ if (page.length < 10_000) break;
1225
+ }
1226
+ if (openEpochs.length === 0) return;
1227
+
1228
+ const wanted = new Set(openEpochs.map((epoch) => epoch.epochSeq));
1229
+ const frameByEpoch = new Map<number, ReturnType<
1230
+ StateHistoryRepository<TPosition>['latestStateFrame']
1231
+ >>();
1232
+ let afterFrameSeq = 0;
1233
+ while (wanted.size > 0) {
1234
+ const page = this.stateHistoryRepository.queryStateFrames({
1235
+ scope,
1236
+ afterFrameSeq,
1237
+ order: 'asc',
1238
+ limit: 10_000,
1239
+ });
1240
+ if (page.frames.length === 0) break;
1241
+ for (const frame of page.frames) {
1242
+ if (frame.epochSeq !== undefined && wanted.delete(frame.epochSeq)) {
1243
+ frameByEpoch.set(frame.epochSeq, frame);
1244
+ }
1245
+ }
1246
+ afterFrameSeq = page.frames.at(-1)!.frameSeq;
1247
+ if (!page.page.hasMore) break;
1248
+ }
1249
+
1250
+ this.observability?.log('info', 'runtime.recovery.started', {
1251
+ open_epoch_count: openEpochs.length,
1252
+ first_epoch_seq: openEpochs[0].epochSeq,
1253
+ latest_epoch_seq: openEpochs.at(-1)!.epochSeq,
1254
+ }, { component: 'runtime.recovery', scope });
1255
+ const completions = openEpochs.map((epoch) => {
1256
+ this.latestAcceptedEpochSeq = Math.max(this.latestAcceptedEpochSeq, epoch.epochSeq);
1257
+ const existing = frameByEpoch.get(epoch.epochSeq);
1258
+ const frame = existing ?? this.stateHistoryRepository.appendStateFrame({
1259
+ epochSeq: epoch.epochSeq,
1260
+ scope: epoch.scope,
1261
+ sourceId: epoch.sourceId,
1262
+ connectionId: epoch.connectionId,
1263
+ sourceKey: `runtime-epoch:${epoch.epochSeq}`,
1264
+ sourceSeq: epoch.sourceSeq,
1265
+ backendTick: typeof epoch.domainTick === 'number' ? epoch.domainTick : undefined,
1266
+ observedAtMs: milliseconds(epoch.observedAt),
1267
+ receivedAtMs: milliseconds(epoch.receivedAt) ?? Date.now(),
1268
+ state: epoch.state,
1269
+ }).frame;
1270
+ const previousState = this.stateHistoryRepository.queryStateFrames({
1271
+ scope,
1272
+ beforeFrameSeq: frame.frameSeq,
1273
+ order: 'desc',
1274
+ limit: 1,
1275
+ }).frames[0]?.state ?? null;
1276
+ const currentState = this.recoveredAgentState(epoch);
1277
+ this.acceptedAgentStateByEpoch.set(epoch.epochSeq, structuredClone(currentState));
1278
+ const completion = this.pluginScheduler.enqueue({
1279
+ epoch,
1280
+ frame,
1281
+ currentState,
1282
+ previousState,
1283
+ epochEvents: [],
1284
+ });
1285
+ this.trackEpochCompletion(epoch.epochSeq, completion);
1286
+ return completion;
1287
+ });
1288
+ await Promise.all(completions);
1289
+ this.observability?.log('info', 'runtime.recovery.completed', {
1290
+ recovered_epoch_count: openEpochs.length,
1291
+ ready_epoch_seq: this.readyEpochSeq,
1292
+ }, { component: 'runtime.recovery', scope });
1293
+ }
1294
+
1295
+ private epochEventId(
1296
+ epoch: RuntimeEpoch<Record<string, any>, Record<string, unknown>>,
1297
+ pluginId: string,
1298
+ proposal: RuntimeEventProposal,
1299
+ proposalIndex: number,
1300
+ ): string {
1301
+ const scope = proposal.dedupeScope === 'session'
1302
+ ? ['session', epoch.scope.sessionId]
1303
+ : ['segment', epoch.scope.sessionId, epoch.scope.segmentId];
1304
+ return JSON.stringify([
1305
+ 'runtime-epoch-plugin',
1306
+ pluginId,
1307
+ epoch.epochSeq,
1308
+ proposalIndex,
1309
+ ...scope,
1310
+ proposal.type,
1311
+ proposal.dedupeKey,
1312
+ ]);
1313
+ }
1314
+
1315
+ private recoveredAgentState(
1316
+ epoch: RuntimeEpoch<Record<string, any>, Record<string, unknown>>,
1317
+ ): StateProviderResult<Record<string, any> | null> {
1318
+ let afterFrameSeq: number | undefined;
1319
+ let projected: Record<string, any> | null = null;
1320
+ while (projected === null) {
1321
+ const page = this.stateHistoryRepository.queryStateFrames({
1322
+ scope: epoch.scope,
1323
+ toEpochSeq: epoch.epochSeq,
1324
+ ...(afterFrameSeq === undefined ? {} : { beforeFrameSeq: afterFrameSeq }),
1325
+ order: 'desc',
1326
+ limit: 1_000,
1327
+ });
1328
+ for (const candidate of page.frames) {
1329
+ projected = this.currentStateFromRuntimeState(candidate.state);
1330
+ if (projected !== null) break;
1331
+ }
1332
+ if (projected !== null || !page.page.hasMore || page.frames.length === 0) break;
1333
+ afterFrameSeq = page.frames.at(-1)!.frameSeq;
1334
+ }
1335
+ const receivedAtMs = milliseconds(epoch.receivedAt) ?? Date.now();
1336
+ return {
1337
+ state: projected === null ? null : structuredClone(projected),
1338
+ stateStatus: {
1339
+ status: projected === null ? 'unavailable' : 'fresh',
1340
+ semantics: 'latest_received',
1341
+ source: projected === null ? null : 'durable_snapshot',
1342
+ scope: this.publicScope() as RuntimeScope,
1343
+ connectionId: epoch.connectionId,
1344
+ connectionState: projected === null ? 'owner_unavailable' : 'connected',
1345
+ receivedAtMs,
1346
+ ageMs: Math.max(0, Date.now() - receivedAtMs),
1347
+ backendTick: typeof epoch.domainTick === 'number' ? epoch.domainTick : null,
1348
+ reason: projected === null ? 'state_not_available_at_epoch' : null,
1349
+ },
1350
+ ...(projected === null ? {
1351
+ stateError: {
1352
+ code: 'STATE_NOT_READY',
1353
+ message: 'No game-facing State exists at or before this Runtime epoch.',
1354
+ },
1355
+ } : {}),
1356
+ };
1357
+ }
1358
+
1359
+ private async onEpochClosed(
1360
+ epoch: RuntimeEpoch<Record<string, any>, Record<string, unknown>>,
1361
+ frameSeq: number,
1362
+ result: RuntimeEpochExecutionResult,
1363
+ ): Promise<void> {
1364
+ const isCurrentScope = sameScope(epoch.scope, this.scope());
1365
+ const acceptedState = this.acceptedAgentStateByEpoch.get(epoch.epochSeq)
1366
+ ?? this.recoveredAgentState(epoch);
1367
+ const previousAnchor = [...this.closedReadyAnchors.values()]
1368
+ .reverse()
1369
+ .find((candidate) => (
1370
+ candidate.epochSeq < epoch.epochSeq
1371
+ && sameScope(candidate.scope, epoch.scope)
1372
+ ));
1373
+ const pluginStates = structuredClone(previousAnchor?.pluginStates ?? {});
1374
+ const domainTick = epoch.domainTick === undefined
1375
+ ? undefined
1376
+ : Number(epoch.domainTick);
1377
+ const normalizedDomainTick = domainTick !== undefined && Number.isFinite(domainTick)
1378
+ ? domainTick
1379
+ : undefined;
1380
+ for (const row of this.inputJournal.states(epoch.epochSeq)) {
1381
+ pluginStates[row.topic] = {
1382
+ pluginId: row.pluginId,
1383
+ topic: row.topic,
1384
+ value: structuredClone(row.value),
1385
+ updatedEpochSeq: epoch.epochSeq,
1386
+ ...(normalizedDomainTick === undefined ? {} : { updatedDomainTick: normalizedDomainTick }),
1387
+ };
1388
+ }
1389
+ const pluginOutcomes = Object.fromEntries(result.outcomes.map((outcome) => [
1390
+ outcome.pluginId,
1391
+ {
1392
+ pluginId: outcome.pluginId,
1393
+ epochSeq: epoch.epochSeq,
1394
+ ...(normalizedDomainTick === undefined ? {} : { domainTick: normalizedDomainTick }),
1395
+ outcome: outcome.outcome,
1396
+ ...(outcome.reason === undefined ? {} : { reason: outcome.reason }),
1397
+ } satisfies RuntimeReadyPluginOutcome,
1398
+ ]));
1399
+ const anchor: RuntimeReadyAnchor<Record<string, any> | null> = {
1400
+ scope: structuredClone(epoch.scope),
1401
+ state: structuredClone(acceptedState),
1402
+ pluginStates,
1403
+ pluginOutcomes,
1404
+ frameSeq,
1405
+ eventWatermark: result.eventWatermark,
1406
+ epochSeq: epoch.epochSeq,
1407
+ };
1408
+ this.closedReadyAnchors.set(epoch.epochSeq, anchor);
1409
+ while (this.closedReadyAnchors.size > CLOSED_READY_ANCHOR_LIMIT) {
1410
+ const oldest = this.closedReadyAnchors.keys().next().value as number | undefined;
1411
+ if (oldest === undefined) break;
1412
+ this.closedReadyAnchors.delete(oldest);
1413
+ }
1414
+ this.epochCompletions.delete(epoch.epochSeq);
1415
+ if (isCurrentScope) {
1416
+ this.readyScope = structuredClone(epoch.scope);
1417
+ this.readyEpochSeq = epoch.epochSeq;
1418
+ this.readyFrameSeq = frameSeq;
1419
+ this.readyState = structuredClone(acceptedState);
1420
+ this.readyPluginStates = structuredClone(pluginStates);
1421
+ this.readyPluginOutcomes = structuredClone(pluginOutcomes);
1422
+ this.readyEventWatermark = result.eventWatermark;
1423
+ }
1424
+ for (const acceptedEpochSeq of this.acceptedAgentStateByEpoch.keys()) {
1425
+ if (acceptedEpochSeq <= epoch.epochSeq) this.acceptedAgentStateByEpoch.delete(acceptedEpochSeq);
1426
+ }
1427
+ this.observability?.log('debug', 'runtime.view.ready', {
1428
+ epoch_seq: epoch.epochSeq,
1429
+ latest_epoch_seq: this.latestAcceptedEpochSeq,
1430
+ lag: Math.max(0, this.latestAcceptedEpochSeq - epoch.epochSeq),
1431
+ frame_seq: frameSeq,
1432
+ event_watermark: result.eventWatermark,
1433
+ current_scope: isCurrentScope,
1434
+ }, { component: 'runtime.view', scope: this.publicScope() });
1435
+ }
1436
+
1437
+ private resetReadyView(scope: RuntimeScope): void {
1438
+ this.readyScope = structuredClone(scope);
1439
+ this.readyState = this.readAgentState();
1440
+ this.readyFrameSeq = 0;
1441
+ this.readyEventWatermark = 0;
1442
+ this.readyEpochSeq = 0;
1443
+ this.readyPluginStates = {};
1444
+ this.readyPluginOutcomes = {};
1445
+ }
1446
+
1447
+ private trackEpochCompletion(
1448
+ epochSeq: number,
1449
+ completion: Promise<RuntimeEpochExecutionResult>,
1450
+ ): void {
1451
+ this.epochCompletions.set(epochSeq, completion);
1452
+ void completion.catch(() => {
1453
+ if (!this.closedReadyAnchors.has(epochSeq)) this.epochCompletions.delete(epochSeq);
1454
+ });
1455
+ }
1456
+
1457
+ private readyViewFromAnchor(
1458
+ anchor: RuntimeReadyAnchor<Record<string, any> | null>,
1459
+ afterCommitSeq: number,
1460
+ limit: number,
1461
+ ): RuntimeReadyView {
1462
+ const boundedLimit = Math.max(1, Math.min(500, Math.trunc(limit) || 100));
1463
+ const pending = this.repository.listCommittedEvents({
1464
+ sessionId: anchor.scope.sessionId,
1465
+ segmentId: anchor.scope.segmentId,
1466
+ afterCommitSeq,
1467
+ maxCommitSeq: anchor.eventWatermark,
1468
+ maxEpochSeq: anchor.epochSeq,
1469
+ order: 'asc',
1470
+ limit: boundedLimit + 1,
1471
+ });
1472
+ const events = pending.slice(0, boundedLimit);
1473
+ return {
1474
+ scope: this.publicScopeFor(anchor.scope),
1475
+ state: structuredClone(anchor.state),
1476
+ pluginStates: structuredClone(anchor.pluginStates),
1477
+ pluginOutcomes: structuredClone(anchor.pluginOutcomes),
1478
+ events,
1479
+ throughCommitSeq: events.at(-1)?.commitSeq ?? afterCommitSeq,
1480
+ frameSeq: anchor.frameSeq,
1481
+ eventWatermark: anchor.eventWatermark,
1482
+ epochSeq: anchor.epochSeq,
1483
+ hasMore: pending.length > events.length,
1484
+ };
1485
+ }
1486
+
1487
+ private pluginCapabilityAccess(
1488
+ plugin: RuntimeEpochPlugin<Record<string, any>, Record<string, unknown>>,
1489
+ scope: RuntimeScope,
1490
+ signal: AbortSignal,
1491
+ epochSeq: number,
1492
+ ): RuntimePluginCapabilityAccess {
1493
+ const provided = new Set(plugin.capabilities?.provides ?? []);
1494
+ const used = new Set(plugin.capabilities?.uses ?? []);
1495
+ const requireDeclared = (kind: 'provide' | 'use', capability: string): void => {
1496
+ const declarations = kind === 'provide' ? provided : used;
1497
+ if (!declarations.has(capability)) {
1498
+ throw new Error(
1499
+ `Runtime Epoch Plugin ${plugin.id} did not declare capability ${kind} ${capability}.`,
1500
+ );
1501
+ }
1502
+ };
1503
+ const requireCurrentScope = (): void => {
1504
+ if (!sameScope(scope, this.scope())) {
1505
+ throw new Error(`Runtime Epoch Plugin ${plugin.id} capability scope is no longer active.`);
1506
+ }
1507
+ };
1508
+ return Object.freeze({
1509
+ provideObservation: <Q, R>(provider: ObservationProvider<Q, R>): (() => void) => {
1510
+ requireCurrentScope();
1511
+ requireDeclared('provide', provider.capability);
1512
+ const scopedProvider: ObservationProvider<Q, R> = {
1513
+ capability: provider.capability,
1514
+ query: (request, requestedScope, queryContext) => {
1515
+ if (!sameScope(scope, requestedScope) || !sameScope(scope, this.scope())) {
1516
+ throw new Error(`Runtime Epoch Plugin ${plugin.id} capability scope is no longer active.`);
1517
+ }
1518
+ return provider.query(request, requestedScope, queryContext);
1519
+ },
1520
+ };
1521
+ return this.observations.register(scopedProvider);
1522
+ },
1523
+ provideAction: <A, R>(service: RegisteredActionService<A, R>): (() => void) => {
1524
+ requireCurrentScope();
1525
+ requireDeclared('provide', service.capability);
1526
+ const scopedService: RegisteredActionService<A, R> = {
1527
+ capability: service.capability,
1528
+ ...(service.describeControl
1529
+ ? {
1530
+ describeControl: (action, requestedScope, caller) => service.describeControl!(
1531
+ action,
1532
+ requestedScope,
1533
+ caller,
1534
+ ),
1535
+ }
1536
+ : {}),
1537
+ perform: (action, requestedScope, caller, actionContext) => {
1538
+ if (!sameScope(scope, requestedScope) || !sameScope(scope, this.scope())) {
1539
+ throw new Error(`Runtime Epoch Plugin ${plugin.id} capability scope is no longer active.`);
1540
+ }
1541
+ return service.perform(action, requestedScope, caller, actionContext);
1542
+ },
1543
+ };
1544
+ return this.actions.register(scopedService);
1545
+ },
1546
+ queryObservation: <Q, R>(capability: string, request: Q): Promise<ObservationResult<R>> => {
1547
+ requireCurrentScope();
1548
+ requireDeclared('use', capability);
1549
+ const stateFrame = this.stateHistoryRepository.queryStateFrames({
1550
+ scope,
1551
+ fromEpochSeq: epochSeq,
1552
+ toEpochSeq: epochSeq,
1553
+ order: 'desc',
1554
+ limit: 1,
1555
+ }).frames[0];
1556
+ return this.observations.query<Q, R>(capability, request, scope, {
1557
+ epochSeq,
1558
+ ...(stateFrame === undefined ? {} : { stateFrame: structuredClone(stateFrame) }),
1559
+ });
1560
+ },
1561
+ performAction: <A, R>(
1562
+ capability: string,
1563
+ action: A,
1564
+ caller: ActionCaller = { kind: 'system', id: `runtime-plugin:${plugin.id}` },
1565
+ ): Promise<ActionResult<R>> => {
1566
+ requireCurrentScope();
1567
+ requireDeclared('use', capability);
1568
+ return this.actions.perform<A, R>(
1569
+ capability,
1570
+ action,
1571
+ scope,
1572
+ caller,
1573
+ {
1574
+ isAuthorized: () => !signal.aborted && sameScope(scope, this.scope()),
1575
+ latestAcceptedState: () => this.latestAcceptedActionState(scope),
1576
+ },
1577
+ );
1578
+ },
1579
+ releaseActionCaller: (
1580
+ capability: string,
1581
+ caller: Extract<ActionCaller, { kind: 'strategy' }>,
1582
+ reason = 'strategy_released',
1583
+ ): void => {
1584
+ requireCurrentScope();
1585
+ requireDeclared('use', capability);
1586
+ if (caller.kind !== 'strategy' || !caller.id.trim()) {
1587
+ throw new Error(
1588
+ `Runtime Epoch Plugin ${plugin.id} may release only a named Strategy Action caller.`,
1589
+ );
1590
+ }
1591
+ this.actions.releaseCaller(caller, reason, scope);
1592
+ },
1593
+ });
1594
+ }
1595
+
1596
+ private latestAcceptedActionState(scope: RuntimeScope) {
1597
+ if (!sameScope(scope, this.scope())) return null;
1598
+ const frame = this.stateHistoryRepository.latestStateFrame(scope);
1599
+ if (!frame || frame.epochSeq === undefined) return null;
1600
+ return {
1601
+ epochSeq: frame.epochSeq,
1602
+ state: structuredClone(frame.state),
1603
+ };
1604
+ }
1605
+
1606
+ private persistTransition(transition: ParticipationTransition): void {
1607
+ if (transition.type === 'session_opened') {
1608
+ this.actions.activateScope(runtimeScope(transition.snapshot));
1609
+ this.repository.saveSession(eventSession(transition.snapshot, true));
1610
+ this.repository.saveSegment(eventSegment(transition.snapshot.segment, true));
1611
+ this.openStateScope(transition.snapshot);
1612
+ return;
1613
+ }
1614
+ if (transition.type === 'session_updated') {
1615
+ this.repository.saveSession(eventSession(transition.snapshot, true));
1616
+ return;
1617
+ }
1618
+ if (transition.type === 'segment_updated') {
1619
+ this.repository.saveSegment(eventSegment(transition.snapshot.segment, true));
1620
+ return;
1621
+ }
1622
+ if (transition.type === 'segment_changed') {
1623
+ this.actions.activateScope(runtimeScope(transition.snapshot));
1624
+ // Save the new current segment first: repository implementations use the
1625
+ // old current pointer to defer unread details into backlog atomically.
1626
+ this.repository.saveSegment(eventSegment(transition.snapshot.segment, true));
1627
+ if (transition.previous) {
1628
+ this.repository.saveSegment(eventSegment(transition.previous, false));
1629
+ const previousScope: RuntimeScope = {
1630
+ adapterId: transition.snapshot.session.adapterId,
1631
+ accountId: transition.snapshot.session.accountId,
1632
+ sessionId: transition.snapshot.session.id,
1633
+ segmentId: transition.previous.id,
1634
+ segmentSeq: transition.previous.ordinal,
1635
+ };
1636
+ this.stateHistoryRepository.sealScope(previousScope, Date.parse(transition.snapshot.segment.startedAt));
1637
+ }
1638
+ this.openStateScope(transition.snapshot);
1639
+ return;
1640
+ }
1641
+ if (transition.type === 'session_closed') {
1642
+ this.repository.saveSegment(eventSegment(transition.snapshot.segment, false));
1643
+ this.repository.saveSession(eventSession(transition.snapshot, false));
1644
+ this.stateHistoryRepository.sealScope(runtimeScope(transition.snapshot));
1645
+ }
1646
+ }
1647
+
1648
+ private openStateScope(snapshot: ParticipationSnapshot, historyComplete = true): void {
1649
+ const scope = runtimeScope(snapshot);
1650
+ const atMs = Date.parse(snapshot.segment.startedAt);
1651
+ this.stateIngress.openScope(scope, Number.isFinite(atMs) ? atMs : Date.now());
1652
+ this.historyWriter.openScope(
1653
+ scope,
1654
+ Number.isFinite(atMs) ? atMs : Date.now(),
1655
+ historyComplete,
1656
+ );
1657
+ }
1658
+
1659
+ private connectionKey(sourceId: string, connectionId: string): string {
1660
+ return `${sourceId}\u001f${connectionId}`;
1661
+ }
1662
+
1663
+ private enqueueOwnerRestartGap(
1664
+ kind: 'stream_gap_started' | 'stream_gap_ended',
1665
+ connectionId?: string,
1666
+ atMs = Date.now(),
1667
+ ): void {
1668
+ const record: TrajectoryRecord<TPosition> = {
1669
+ recordId: randomUUID(),
1670
+ scope: this.scope(),
1671
+ connectionId,
1672
+ subjectId: '__owner__',
1673
+ subjectKind: 'system',
1674
+ kind,
1675
+ sourceType: 'local_lifecycle',
1676
+ sourceKey: `owner-restart:${kind}:${atMs}`,
1677
+ receivedAtMs: atMs,
1678
+ attributes: { reason: 'owner_restart' },
1679
+ };
1680
+ this.historyWriter.enqueue([record]);
1681
+ }
1682
+
1683
+ private sealDurableScope(scope: CurrentEventScope): void {
1684
+ const now = new Date().toISOString();
1685
+ this.repository.saveSegment({
1686
+ ...scope.segment,
1687
+ status: 'closed',
1688
+ isCurrent: false,
1689
+ closedAt: scope.segment.closedAt ?? now,
1690
+ });
1691
+ this.repository.saveSession({
1692
+ ...scope.session,
1693
+ status: 'sealed',
1694
+ isCurrent: false,
1695
+ sealedAt: scope.session.sealedAt ?? now,
1696
+ });
1697
+ }
1698
+
1699
+ private assertOpen(): void {
1700
+ if (this.closed) throw new Error('Runtime is closed.');
1701
+ if (this.closing) throw new Error('Runtime is closing.');
1702
+ if (this.fatalError) throw this.fatalError;
1703
+ }
1704
+
1705
+ private assertSourceInputOpen(): void {
1706
+ if (this.closed || !this.sourceInputOpen) throw new Error('Runtime input is closed.');
1707
+ if (this.fatalError) throw this.fatalError;
1708
+ }
1709
+
1710
+ private assertExpectedScope(expected: ExpectedRuntimeScope): RuntimeScope {
1711
+ this.assertOpen();
1712
+ const scope = this.scope();
1713
+ if (scope.sessionId !== expected.sessionId || scope.segmentId !== expected.segmentId) {
1714
+ throw new Error('runtime_scope_changed');
1715
+ }
1716
+ return scope;
1717
+ }
1718
+
1719
+ private onHistoryWriterHealthChanged(health: HistoryWriterHealth): void {
1720
+ const degradedScopes = this.historyWriter.degradedScopeHealth();
1721
+ // Queue depth changes on normal frames, so it is intentionally excluded
1722
+ // from transition identity. A new affected scope or reason is a real
1723
+ // health transition and is emitted once.
1724
+ const signature = JSON.stringify({
1725
+ status: health.status,
1726
+ scopes: degradedScopes.map((entry) => ({
1727
+ scope: {
1728
+ adapterId: entry.scope.adapterId,
1729
+ sessionId: entry.scope.sessionId,
1730
+ segmentId: entry.scope.segmentId,
1731
+ segmentSeq: entry.scope.segmentSeq,
1732
+ },
1733
+ reason: entry.reason,
1734
+ })),
1735
+ });
1736
+ if (signature === this.lastHistoryWriterHealthSignature) return;
1737
+ const previous = this.lastHistoryWriterHealthSignature;
1738
+ this.lastHistoryWriterHealthSignature = signature;
1739
+ if (previous === null && health.status === 'healthy') return;
1740
+ const activeScope = degradedScopes[0]?.scope ?? this.scope();
1741
+ const { accountId: _accountId, ...scope } = activeScope;
1742
+ this.observability?.log(
1743
+ health.status === 'degraded' ? 'warn' : 'info',
1744
+ 'runtime.state_history.writer_health_changed',
1745
+ {
1746
+ status: health.status,
1747
+ reason: health.reason,
1748
+ queue_depth: health.queueDepth,
1749
+ dropped_record_count: health.droppedRecordCount,
1750
+ degraded_since_ms: health.degradedSinceMs,
1751
+ degraded_scope_count: degradedScopes.length,
1752
+ },
1753
+ { component: 'runtime.state-history', scope },
1754
+ );
1755
+ }
1756
+ }