@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,1529 @@
1
+ import type {
2
+ RuntimeEpochFlushReason,
3
+ RuntimeEpochPlugin,
4
+ RuntimeEpochPluginContext,
5
+ RuntimeEpochPluginInput,
6
+ RuntimeEpochPluginResult,
7
+ RuntimeDiagnosticSeverity,
8
+ RuntimeEventProposal,
9
+ } from '../../../framework/plugins/index.js';
10
+ import { performance } from 'node:perf_hooks';
11
+ import type { StoredStateFrame } from '../../../framework/state/history/contracts.js';
12
+ import { isClawclawRuntimeState } from '../../runtime-state.js';
13
+ import {
14
+ PERCEPTION_PLUGIN_API_VERSION,
15
+ ClawclawPerception,
16
+ type ClawclawPerceptionClass,
17
+ type ClawclawPerceptionManifest,
18
+ type PerceptionApi,
19
+ type PerceptionAnalysisInput,
20
+ type PerceptionBoundary,
21
+ type PerceptionBoundaryKind,
22
+ type PerceptionEventProposal,
23
+ type PerceptionModuleId,
24
+ type PerceptionSpatialFacts,
25
+ type VisualState,
26
+ } from './contracts.js';
27
+ import { DEFAULT_PERCEPTION_MODULES } from './official-module-ids.js';
28
+ import {
29
+ ImportedLocalPerceptionModuleRunner,
30
+ LocalPerceptionModuleRunner,
31
+ type PerceptionModuleRunner,
32
+ } from './module-runner.js';
33
+ import {
34
+ listClawclawPerceptionSources,
35
+ type ResolvedClawclawPerceptionSource,
36
+ } from './perception-source.js';
37
+ import {
38
+ officialPerceptionModuleClass,
39
+ } from './official-modules.js';
40
+ import {
41
+ PerceptionAnalysisThreadPool,
42
+ type PerceptionAnalysisJob,
43
+ } from './perception-analysis-thread-pool.js';
44
+ import {
45
+ PerceptionModuleLoader,
46
+ type PerceptionThreadModuleSpec,
47
+ } from './perception-module-loader.js';
48
+ import {
49
+ CLAWCLAW_PERCEPTION_SPATIAL_API,
50
+ CLAWCLAW_PERCEPTION_SPATIAL_FACTS,
51
+ } from './spatial-facts.js';
52
+ import { VisualStateProjector } from './visual-state-projector.js';
53
+
54
+ export { DEFAULT_PERCEPTION_MODULES } from './official-module-ids.js';
55
+
56
+ export const CLAWCLAW_PERCEPTION_PLUGIN_ID = 'clawclaw.perception';
57
+ export const DEFAULT_MAX_PERCEPTION_BACKFILL_VISUAL_FRAMES = 10;
58
+ const PERCEPTION_MODULE_TIMING_WINDOW_MS = 10_000;
59
+ const PERCEPTION_ANALYSIS_WINDOW_FRAMES = 10;
60
+
61
+ export interface ClawclawPerceptionConfig {
62
+ modules?: readonly string[];
63
+ /** Maximum visual frames replayed into modules during one live Runtime invocation. */
64
+ maxBackfillVisualFrames?: number;
65
+ }
66
+
67
+ export interface PerceptionModuleDescriptor extends ClawclawPerceptionManifest {
68
+ /** Every module is hosted by the same Runtime plugin. */
69
+ readonly pluginId: typeof CLAWCLAW_PERCEPTION_PLUGIN_ID;
70
+ }
71
+
72
+ export interface PerceptionFrameInspection {
73
+ visual: VisualState | null;
74
+ proposals: readonly RuntimeEventProposal[];
75
+ moduleStates: Record<string, unknown>;
76
+ reason?: string;
77
+ }
78
+
79
+ interface PerceptionModuleSlot {
80
+ readonly manifest: ClawclawPerceptionManifest;
81
+ readonly runner: PerceptionModuleRunner;
82
+ readonly customSource?: ResolvedClawclawPerceptionSource;
83
+ /** Invalidates analyses that were computed before an ordered reducer barrier. */
84
+ analysisGeneration: number;
85
+ /** Oldest raw visual frame that a new generation may use as trajectory history. */
86
+ analysisHistoryFloorFrameSeq: number;
87
+ /** The first successful reducer application after failure establishes state only. */
88
+ analysisBaselinePending: boolean;
89
+ /** Undefined follows global replay; null means reset with no successful reducer commit yet. */
90
+ reducerReplayFromFrameSeq: number | null | undefined;
91
+ }
92
+
93
+ function elapsedMs(startedAt: number): number {
94
+ return Math.round(Math.max(0, performance.now() - startedAt) * 1_000) / 1_000;
95
+ }
96
+
97
+ interface PerceptionModuleTimingWindow {
98
+ readonly moduleId: string;
99
+ readonly operation: string;
100
+ readonly durationsMs: number[];
101
+ eventCount: number;
102
+ failureCount: number;
103
+ }
104
+
105
+ function percentile95(values: readonly number[]): number {
106
+ if (values.length === 0) return 0;
107
+ const sorted = [...values].sort((left, right) => left - right);
108
+ return sorted[Math.max(0, Math.ceil(sorted.length * 0.95) - 1)]!;
109
+ }
110
+
111
+ function roundedAverage(values: readonly number[]): number {
112
+ if (values.length === 0) return 0;
113
+ return Math.round((values.reduce((sum, value) => sum + value, 0) / values.length) * 1_000) / 1_000;
114
+ }
115
+
116
+ interface PreparedPerceptionFrame {
117
+ readonly stored: StoredStateFrame<Record<string, any>>;
118
+ readonly visual: VisualState | null;
119
+ readonly analyses: readonly PerceptionModuleAnalysis[];
120
+ }
121
+
122
+ interface PerceptionModuleAnalysis {
123
+ readonly moduleId: string;
124
+ readonly generation: number;
125
+ readonly outcome: 'fulfilled' | 'rejected';
126
+ readonly durationMs: number;
127
+ readonly analysis?: unknown;
128
+ readonly failure?: Readonly<{
129
+ errorCode: string;
130
+ messagePresent: boolean;
131
+ messageLength?: number;
132
+ }>;
133
+ }
134
+
135
+ interface PerceptionComputationProposal {
136
+ readonly schema: 'clawclaw.perception-computation.v1';
137
+ readonly visual: VisualState | null;
138
+ readonly analyses: readonly PerceptionModuleAnalysis[];
139
+ }
140
+
141
+ interface PerceptionCheckpoint {
142
+ readonly schema: 'clawclaw.perception-checkpoint.v1';
143
+ /** First State frame needed to rebuild current module-private state; null means empty state. */
144
+ readonly replayFromFrameSeq: number | null;
145
+ /** Per parallel module, the first frame allowed after its latest private failure boundary. */
146
+ readonly parallelModuleHistoryFloors?: Readonly<Record<string, number>>;
147
+ /** Actual first reducer commit after a private boundary; null means the reducer is still empty. */
148
+ readonly parallelModuleReducerReplayStarts?: Readonly<Record<string, number | null>>;
149
+ /** Whether the next successful reducer commit establishes state without emitting Events. */
150
+ readonly parallelModuleBaselinePending?: Readonly<Record<string, boolean>>;
151
+ }
152
+
153
+ type PerceptionDiagnostic = (
154
+ name: string,
155
+ attributes?: Readonly<Record<string, unknown>>,
156
+ severity?: RuntimeDiagnosticSeverity,
157
+ ) => void;
158
+
159
+ const PERCEPTION_CHECKPOINT_SCHEMA = 'clawclaw.perception-checkpoint.v1' as const;
160
+ const PERCEPTION_COMPUTATION_SCHEMA = 'clawclaw.perception-computation.v1' as const;
161
+ const PERCEPTION_FAILURE_REPORT_WINDOW_MS = 30_000;
162
+
163
+ function nonEmpty(value: unknown): value is string {
164
+ return typeof value === 'string' && value.trim().length > 0;
165
+ }
166
+
167
+ function moduleClass(instance: ClawclawPerception): ClawclawPerceptionClass {
168
+ return instance.constructor as ClawclawPerceptionClass;
169
+ }
170
+
171
+ function perceptionFailureDetails(reason: unknown): Readonly<{
172
+ errorCode: string;
173
+ messagePresent: boolean;
174
+ messageLength?: number;
175
+ }> {
176
+ const code = reason && typeof reason === 'object' && typeof (reason as any).code === 'string'
177
+ ? (reason as any).code.trim()
178
+ : '';
179
+ const message = reason instanceof Error
180
+ ? reason.message
181
+ : typeof reason === 'string' ? reason : '';
182
+ const prefix = /^([A-Za-z][A-Za-z0-9_.-]{0,119})(?::|$)/.exec(message.trim())?.[1];
183
+ return {
184
+ errorCode: /^[A-Za-z][A-Za-z0-9_.-]{0,119}$/.test(code)
185
+ ? code
186
+ : prefix ?? 'PERCEPTION_MODULE_FAILED',
187
+ messagePresent: message.length > 0,
188
+ ...(message ? { messageLength: message.length } : {}),
189
+ };
190
+ }
191
+
192
+ export function perceptionManifest(instance: ClawclawPerception): ClawclawPerceptionManifest {
193
+ const ModuleClass = moduleClass(instance);
194
+ if (ModuleClass.apiVersion !== PERCEPTION_PLUGIN_API_VERSION) {
195
+ throw new Error('Perception module API version is unsupported.');
196
+ }
197
+ return validatePerceptionManifest(ModuleClass.manifest);
198
+ }
199
+
200
+ export function validatePerceptionManifest(
201
+ manifest: ClawclawPerceptionManifest | undefined,
202
+ ): ClawclawPerceptionManifest {
203
+ if (
204
+ !manifest
205
+ || !/^[a-z0-9][a-z0-9._-]*$/.test(manifest.id)
206
+ || !nonEmpty(manifest.name)
207
+ || !nonEmpty(manifest.description)
208
+ || !['others', 'self_and_others', 'visible_pairs', 'corpses'].includes(manifest.subjectScope)
209
+ || !Array.isArray(manifest.produces)
210
+ || manifest.produces.length === 0
211
+ || manifest.produces.some((type) => !/^visual\.[a-z0-9_.-]+$/.test(type))
212
+ || new Set(manifest.produces).size !== manifest.produces.length
213
+ || (manifest.execution !== undefined && manifest.execution !== 'parallel_analysis')
214
+ || (
215
+ manifest.boundaryBaseline !== undefined
216
+ && (
217
+ manifest.execution !== 'parallel_analysis'
218
+ || manifest.boundaryBaseline !== 'current_only'
219
+ )
220
+ )
221
+ ) {
222
+ throw new Error('Perception module manifest is invalid.');
223
+ }
224
+ return manifest;
225
+ }
226
+
227
+ export function createOfficialPerceptionModule(id: PerceptionModuleId): ClawclawPerception {
228
+ return new (officialPerceptionModuleClass(id))();
229
+ }
230
+
231
+ function createModuleSlots(
232
+ config: ClawclawPerceptionConfig,
233
+ loader: PerceptionModuleLoader,
234
+ ): PerceptionModuleSlot[] {
235
+ const ids = [...new Set(config.modules ?? DEFAULT_PERCEPTION_MODULES)].sort();
236
+ const officialIds = new Set<string>(DEFAULT_PERCEPTION_MODULES);
237
+ const customIds = ids.filter((id) => !officialIds.has(id));
238
+ const customSources = new Map(
239
+ customIds.length > 0
240
+ ? listClawclawPerceptionSources().map((source) => [source.id, source])
241
+ : [],
242
+ );
243
+ const collisions = [...customSources.keys()].filter((id) => officialIds.has(id));
244
+ if (collisions.length > 0) {
245
+ throw new Error(`User perception module id conflicts with an official module: ${collisions.join(', ')}`);
246
+ }
247
+ return ids.map((id) => {
248
+ if (officialIds.has(id)) {
249
+ const instance = createOfficialPerceptionModule(id as PerceptionModuleId);
250
+ const manifest = perceptionManifest(instance);
251
+ const runner = new LocalPerceptionModuleRunner(instance, manifest);
252
+ return {
253
+ manifest,
254
+ runner,
255
+ analysisGeneration: 0,
256
+ analysisHistoryFloorFrameSeq: 0,
257
+ analysisBaselinePending: false,
258
+ reducerReplayFromFrameSeq: undefined,
259
+ };
260
+ }
261
+ const source = customSources.get(id);
262
+ if (!source) throw new Error(`Unknown perception module '${id}'.`);
263
+ const runner = new ImportedLocalPerceptionModuleRunner(source, loader);
264
+ return {
265
+ manifest: validatePerceptionManifest(runner.manifest),
266
+ runner,
267
+ customSource: source,
268
+ analysisGeneration: 0,
269
+ analysisHistoryFloorFrameSeq: 0,
270
+ analysisBaselinePending: false,
271
+ reducerReplayFromFrameSeq: undefined,
272
+ };
273
+ });
274
+ }
275
+
276
+ function proposals(value: readonly PerceptionEventProposal[] | void): RuntimeEventProposal[] {
277
+ return value ? value.map((proposal) => ({
278
+ ...proposal,
279
+ payload: { ...proposal.payload },
280
+ })) : [];
281
+ }
282
+
283
+ function perceptionCheckpoint(value: unknown): PerceptionCheckpoint | null {
284
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
285
+ const checkpoint = value as Record<string, unknown>;
286
+ if (checkpoint.schema !== PERCEPTION_CHECKPOINT_SCHEMA) return null;
287
+ const replayFromFrameSeq = checkpoint.replayFromFrameSeq;
288
+ if (
289
+ replayFromFrameSeq !== null
290
+ && (!Number.isInteger(replayFromFrameSeq) || Number(replayFromFrameSeq) <= 0)
291
+ ) return null;
292
+ const rawFloors = checkpoint.parallelModuleHistoryFloors;
293
+ if (rawFloors !== undefined && (
294
+ !rawFloors
295
+ || typeof rawFloors !== 'object'
296
+ || Array.isArray(rawFloors)
297
+ )) return null;
298
+ const parallelModuleHistoryFloors: Record<string, number> = {};
299
+ for (const [moduleId, floor] of Object.entries(rawFloors ?? {})) {
300
+ if (
301
+ !/^[a-z0-9][a-z0-9._-]*$/.test(moduleId)
302
+ || !Number.isInteger(floor)
303
+ || Number(floor) <= 0
304
+ ) return null;
305
+ parallelModuleHistoryFloors[moduleId] = Number(floor);
306
+ }
307
+ const rawReplayStarts = checkpoint.parallelModuleReducerReplayStarts;
308
+ if (rawReplayStarts !== undefined && (
309
+ !rawReplayStarts
310
+ || typeof rawReplayStarts !== 'object'
311
+ || Array.isArray(rawReplayStarts)
312
+ )) return null;
313
+ const parallelModuleReducerReplayStarts: Record<string, number | null> = {};
314
+ for (const [moduleId, start] of Object.entries(rawReplayStarts ?? {})) {
315
+ if (
316
+ !/^[a-z0-9][a-z0-9._-]*$/.test(moduleId)
317
+ || (
318
+ start !== null
319
+ && (!Number.isInteger(start) || Number(start) <= 0)
320
+ )
321
+ ) return null;
322
+ parallelModuleReducerReplayStarts[moduleId] = start === null ? null : Number(start);
323
+ }
324
+ const rawBaselinePending = checkpoint.parallelModuleBaselinePending;
325
+ if (rawBaselinePending !== undefined && (
326
+ !rawBaselinePending
327
+ || typeof rawBaselinePending !== 'object'
328
+ || Array.isArray(rawBaselinePending)
329
+ )) return null;
330
+ const parallelModuleBaselinePending: Record<string, boolean> = {};
331
+ for (const [moduleId, pending] of Object.entries(rawBaselinePending ?? {})) {
332
+ if (
333
+ !/^[a-z0-9][a-z0-9._-]*$/.test(moduleId)
334
+ || typeof pending !== 'boolean'
335
+ ) return null;
336
+ parallelModuleBaselinePending[moduleId] = pending;
337
+ }
338
+ return {
339
+ schema: PERCEPTION_CHECKPOINT_SCHEMA,
340
+ replayFromFrameSeq: replayFromFrameSeq === null ? null : Number(replayFromFrameSeq),
341
+ ...(Object.keys(parallelModuleHistoryFloors).length === 0
342
+ ? {}
343
+ : { parallelModuleHistoryFloors }),
344
+ ...(Object.keys(parallelModuleReducerReplayStarts).length === 0
345
+ ? {}
346
+ : { parallelModuleReducerReplayStarts }),
347
+ ...(Object.keys(parallelModuleBaselinePending).length === 0
348
+ ? {}
349
+ : { parallelModuleBaselinePending }),
350
+ };
351
+ }
352
+
353
+ /** One Runtime plugin that projects each frame once and fans it out to perception modules. */
354
+ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<string, any>> {
355
+ readonly kind = 'epoch' as const;
356
+ readonly id = CLAWCLAW_PERCEPTION_PLUGIN_ID;
357
+ readonly version = String(PERCEPTION_PLUGIN_API_VERSION);
358
+ get catchUp(): 'every_epoch' | 'latest_only' {
359
+ return this.maxBackfillVisualFrames === 1
360
+ && this.modules.some(({ runner }) => runner.execution === 'parallel_analysis')
361
+ ? 'latest_only'
362
+ : 'every_epoch';
363
+ }
364
+ readonly maxInFlight: number;
365
+ readonly produces: { readonly events: readonly string[] };
366
+
367
+ private readonly modules: readonly PerceptionModuleSlot[];
368
+ private readonly maxBackfillVisualFrames: number;
369
+ private readonly moduleLoader = new PerceptionModuleLoader();
370
+ private analysisPool?: PerceptionAnalysisThreadPool;
371
+ private readonly projector = new VisualStateProjector();
372
+ private readonly api: PerceptionApi = Object.freeze({
373
+ spatial: CLAWCLAW_PERCEPTION_SPATIAL_API,
374
+ });
375
+ private phase: string | null = null;
376
+ private lastFrameSeq = 0;
377
+ private lastFrameTimeMs: number | null = null;
378
+ private lastVisualTick: number | null = null;
379
+ private lastVisualFrame: VisualState | null = null;
380
+ private lastConnectionId: string | null = null;
381
+ private readonly analysisWindow: VisualState[] = [];
382
+ private replayFromFrameSeq: number | null = null;
383
+ private readonly moduleFailureReports = new Map<string, {
384
+ lastReportedAtMs: number;
385
+ failureCount: number;
386
+ suppressedCount: number;
387
+ }>();
388
+ private readonly moduleTimingWindows = new Map<string, PerceptionModuleTimingWindow>();
389
+ private moduleTimingWindowStartedAt = performance.now();
390
+ private runnersStarted = false;
391
+ private runnersStartTask?: Promise<void>;
392
+ private runnersStartGeneration = 0;
393
+ private runnersStopTask?: Promise<void>;
394
+ private runnerLifecycleGeneration = 0;
395
+ private recovering = false;
396
+
397
+ constructor(config: ClawclawPerceptionConfig = {}) {
398
+ const maxBackfillVisualFrames = config.maxBackfillVisualFrames
399
+ ?? DEFAULT_MAX_PERCEPTION_BACKFILL_VISUAL_FRAMES;
400
+ if (
401
+ !Number.isInteger(maxBackfillVisualFrames)
402
+ || maxBackfillVisualFrames <= 0
403
+ || maxBackfillVisualFrames > 10
404
+ ) {
405
+ throw new TypeError('maxBackfillVisualFrames must be an integer between 1 and 10.');
406
+ }
407
+ this.maxBackfillVisualFrames = maxBackfillVisualFrames;
408
+ this.modules = createModuleSlots(config, this.moduleLoader);
409
+ // Pure legacy assemblies do all module work in ordered commit. Keeping
410
+ // them at one in-flight epoch preserves the scheduler's normal catch-up
411
+ // path instead of buffering ten empty analysis proposals ahead of a slow
412
+ // stateful reducer. Only an explicit parallel analyzer needs the ROB.
413
+ this.maxInFlight = this.modules.some(({ runner }) => (
414
+ runner.execution === 'parallel_analysis'
415
+ )) ? maxBackfillVisualFrames : 1;
416
+ this.produces = {
417
+ events: [...new Set(this.modules.flatMap(({ manifest }) => [...manifest.produces]))],
418
+ };
419
+ }
420
+
421
+ async start(context: RuntimeEpochPluginContext<Record<string, any>>): Promise<void> {
422
+ await this.startRunners(context.signal, context.diagnostic);
423
+ }
424
+
425
+ async recover(context: RuntimeEpochPluginContext<Record<string, any>>): Promise<void> {
426
+ const completedThroughEpochSeq = context.progress().completedThroughEpochSeq;
427
+ if (completedThroughEpochSeq <= 0) return;
428
+ const checkpointValue = context.checkpoint();
429
+ const checkpoint = perceptionCheckpoint(checkpointValue);
430
+ const hasCheckpoint = checkpoint !== null;
431
+ this.replayFromFrameSeq = checkpoint?.replayFromFrameSeq ?? null;
432
+ for (const module of this.modules) {
433
+ if (module.runner.execution !== 'parallel_analysis') continue;
434
+ const floor = checkpoint?.parallelModuleHistoryFloors?.[module.manifest.id];
435
+ if (floor !== undefined) module.analysisHistoryFloorFrameSeq = floor;
436
+ const replayStarts = checkpoint?.parallelModuleReducerReplayStarts;
437
+ const baselinePending = checkpoint?.parallelModuleBaselinePending;
438
+ const hasExactBaseline = !!baselinePending
439
+ && Object.hasOwn(baselinePending, module.manifest.id);
440
+ if (replayStarts && Object.hasOwn(replayStarts, module.manifest.id)) {
441
+ module.reducerReplayFromFrameSeq = replayStarts[module.manifest.id]!;
442
+ if (!hasExactBaseline) {
443
+ module.analysisBaselinePending = module.reducerReplayFromFrameSeq === null;
444
+ }
445
+ } else if (floor !== undefined && !hasExactBaseline) {
446
+ // Older additive checkpoints only had the history floor. Preserve
447
+ // their conservative behavior by rebuilding a baseline at that floor.
448
+ module.analysisBaselinePending = true;
449
+ }
450
+ if (hasExactBaseline) {
451
+ module.analysisBaselinePending = baselinePending[module.manifest.id]!;
452
+ }
453
+ }
454
+ this.recovering = true;
455
+ try {
456
+ let afterFrameSeq = 0;
457
+ while (true) {
458
+ const page = context.stateHistory.queryStateFrames({
459
+ scope: context.scope,
460
+ afterFrameSeq,
461
+ order: 'asc',
462
+ limit: 500,
463
+ });
464
+ if (page.frames.length === 0) break;
465
+ for (const frame of page.frames) {
466
+ if (frame.epochSeq !== undefined && frame.epochSeq > completedThroughEpochSeq) return;
467
+ const visual = this.projector.project(frame);
468
+ if (
469
+ hasCheckpoint
470
+ && (
471
+ checkpoint.replayFromFrameSeq === null
472
+ || frame.frameSeq < checkpoint.replayFromFrameSeq
473
+ )
474
+ ) {
475
+ this.lastFrameSeq = frame.frameSeq;
476
+ } else {
477
+ await this.inspectPreparedFrame(
478
+ await this.prepareFrame(
479
+ frame,
480
+ visual,
481
+ context.signal,
482
+ visual && this.shouldAnalyze(frame)
483
+ ? this.analysisInputFromHistory(frame, visual, context)
484
+ : null,
485
+ ),
486
+ context.signal,
487
+ context.diagnostic,
488
+ );
489
+ }
490
+ afterFrameSeq = frame.frameSeq;
491
+ }
492
+ if (!page.page.hasMore) break;
493
+ }
494
+ } finally {
495
+ this.recovering = false;
496
+ }
497
+ }
498
+
499
+ async update(
500
+ input: RuntimeEpochPluginInput<Record<string, any>>,
501
+ context: RuntimeEpochPluginContext<Record<string, any>>,
502
+ ): Promise<RuntimeEpochPluginResult> {
503
+ const visual = this.projector.project(input.frame);
504
+ const analysisInput = visual && this.shouldAnalyze(input.frame)
505
+ ? this.analysisInputFromHistory(input.frame, visual, context)
506
+ : null;
507
+ const prepared = await this.prepareFrame(input.frame, visual, context.signal, analysisInput);
508
+ const proposal: PerceptionComputationProposal = {
509
+ schema: PERCEPTION_COMPUTATION_SCHEMA,
510
+ visual: prepared.visual,
511
+ analyses: prepared.analyses,
512
+ };
513
+ return {
514
+ outcome: 'processed',
515
+ reason: prepared.visual ? 'visual_analyzed' : 'state_classified',
516
+ proposal,
517
+ };
518
+ }
519
+
520
+ async commit(
521
+ input: RuntimeEpochPluginInput<Record<string, any>>,
522
+ computation: Readonly<RuntimeEpochPluginResult>,
523
+ context: RuntimeEpochPluginContext<Record<string, any>>,
524
+ ): Promise<RuntimeEpochPluginResult> {
525
+ const proposal = this.computationProposal(computation.proposal);
526
+ const previousFrameSeq = this.lastFrameSeq;
527
+ const inspected = await this.inspectPreparedFrame({
528
+ stored: input.frame,
529
+ visual: proposal.visual,
530
+ analyses: proposal.analyses,
531
+ }, context.signal, context.diagnostic);
532
+ if (input.frame.frameSeq > previousFrameSeq + 1) {
533
+ context.diagnostic('perception.catchup_frames_dropped', {
534
+ target_epoch_seq: input.epoch.epochSeq,
535
+ max_backfill_visual_frames: this.maxBackfillVisualFrames,
536
+ dropped_state_frame_count: input.frame.frameSeq - previousFrameSeq - 1,
537
+ dropped_from_frame_seq: previousFrameSeq + 1,
538
+ dropped_through_frame_seq: input.frame.frameSeq - 1,
539
+ retained_from_frame_seq: input.frame.frameSeq,
540
+ retained_through_frame_seq: input.frame.frameSeq,
541
+ });
542
+ }
543
+ const checkpoint = this.checkpointValue();
544
+ return inspected.visual || inspected.proposals.length > 0
545
+ ? {
546
+ outcome: 'processed',
547
+ ...(inspected.reason ? { reason: inspected.reason } : {}),
548
+ events: inspected.proposals,
549
+ checkpoint,
550
+ }
551
+ : { outcome: 'noop', reason: inspected.reason ?? 'not_visual_state', checkpoint };
552
+ }
553
+
554
+ /** Advances one frame; used by Runtime and deterministic offline replay. */
555
+ async inspectFrame(
556
+ input: StoredStateFrame<Record<string, any>>,
557
+ signal = new AbortController().signal,
558
+ diagnostic?: PerceptionDiagnostic,
559
+ ): Promise<PerceptionFrameInspection> {
560
+ if (!this.runnersStarted) await this.startRunners(signal);
561
+ if (input.frameSeq <= this.lastFrameSeq) {
562
+ return { visual: null, proposals: [], moduleStates: this.moduleStateSnapshot() };
563
+ }
564
+ const projected = this.projector.project(input);
565
+ return this.inspectPreparedFrame(
566
+ await this.prepareFrame(
567
+ input,
568
+ projected,
569
+ signal,
570
+ projected && this.shouldAnalyze(input)
571
+ ? this.localAnalysisInput(input, projected)
572
+ : null,
573
+ ),
574
+ signal,
575
+ diagnostic,
576
+ );
577
+ }
578
+
579
+ private async inspectPreparedFrame(
580
+ input: PreparedPerceptionFrame,
581
+ signal: AbortSignal,
582
+ diagnostic?: PerceptionDiagnostic,
583
+ ): Promise<PerceptionFrameInspection> {
584
+ if (input.stored.frameSeq <= this.lastFrameSeq) {
585
+ return { visual: null, proposals: [], moduleStates: this.moduleStateSnapshot() };
586
+ }
587
+ const stateFrameGap = this.lastFrameSeq > 0
588
+ && input.stored.frameSeq > this.lastFrameSeq + 1;
589
+ this.lastFrameSeq = input.stored.frameSeq;
590
+ const runtimeState = input.stored.state;
591
+ if (isClawclawRuntimeState(runtimeState)) {
592
+ if (runtimeState.connection !== 'connected') {
593
+ const events = await this.flushAndReset(
594
+ 'trajectory_gap',
595
+ signal,
596
+ diagnostic,
597
+ input.stored.frameSeq + 1,
598
+ );
599
+ return {
600
+ visual: null,
601
+ proposals: events,
602
+ moduleStates: this.moduleStateSnapshot(),
603
+ reason: runtimeState.connection,
604
+ };
605
+ }
606
+ if (
607
+ runtimeState.cause === 'agent_events_query'
608
+ && runtimeState.control?.type === 'events_query'
609
+ ) {
610
+ const events = await this.flushModules(
611
+ 'events_requested',
612
+ 'snapshot',
613
+ signal,
614
+ diagnostic,
615
+ );
616
+ return {
617
+ visual: null,
618
+ proposals: events,
619
+ moduleStates: this.moduleStateSnapshot(),
620
+ reason: 'events_requested',
621
+ };
622
+ }
623
+ if (runtimeState.stage === 'ended') {
624
+ const events = await this.flushAndReset(
625
+ 'segment_ending',
626
+ signal,
627
+ diagnostic,
628
+ input.stored.frameSeq + 1,
629
+ );
630
+ return {
631
+ visual: null,
632
+ proposals: events,
633
+ moduleStates: this.moduleStateSnapshot(),
634
+ reason: 'segment_ending',
635
+ };
636
+ }
637
+ if (runtimeState.game_snapshot.status !== 'fresh') {
638
+ return {
639
+ visual: null,
640
+ proposals: [],
641
+ moduleStates: this.moduleStateSnapshot(),
642
+ reason: `game_snapshot:${runtimeState.game_snapshot.status}`,
643
+ };
644
+ }
645
+ }
646
+
647
+ const projected = input.visual;
648
+ if (!projected) {
649
+ return { visual: null, proposals: [], moduleStates: this.moduleStateSnapshot() };
650
+ }
651
+
652
+ const previousVisualTick = this.lastVisualTick;
653
+ const phaseChanged = this.phase !== null && this.phase !== projected.phase;
654
+ const tickDelta = previousVisualTick === null ? null : projected.tick - previousVisualTick;
655
+ const sameConnection = this.lastConnectionId === input.stored.connectionId;
656
+ const emitted: RuntimeEventProposal[] = [];
657
+
658
+ if (previousVisualTick !== null && projected.tick > previousVisualTick + 1) {
659
+ diagnostic?.('runtime.plugin.coverage_gap', {
660
+ reason: 'game_tick_gap',
661
+ previous_game_tick: previousVisualTick,
662
+ received_game_tick: projected.tick,
663
+ missing_from_game_tick: previousVisualTick + 1,
664
+ missing_to_game_tick: projected.tick - 1,
665
+ frame_seq: input.stored.frameSeq,
666
+ });
667
+ }
668
+
669
+ const continuousFromPrevious = !stateFrameGap
670
+ && !phaseChanged
671
+ && tickDelta !== null
672
+ && tickDelta >= 0
673
+ && tickDelta <= 3
674
+ && sameConnection;
675
+ const frame: VisualState = { ...projected, tickDelta, continuousFromPrevious };
676
+ const gap = this.lastVisualTick !== null && !phaseChanged && !continuousFromPrevious;
677
+
678
+ // Close every module's old slice before it receives the new phase/gap frame.
679
+ if (gap || phaseChanged) {
680
+ const kind: PerceptionBoundaryKind = gap ? 'trajectory_gap' : 'phase_changed';
681
+ emitted.push(...await this.flushModules(kind, 'close', signal, diagnostic));
682
+ await this.resetModules(
683
+ kind,
684
+ signal,
685
+ diagnostic,
686
+ input.stored.frameSeq,
687
+ false,
688
+ );
689
+ this.replayFromFrameSeq = input.stored.frameSeq;
690
+ }
691
+
692
+ if (this.replayFromFrameSeq === null) this.replayFromFrameSeq = input.stored.frameSeq;
693
+
694
+ emitted.push(...await this.deliverVisualFrame(
695
+ frame,
696
+ input.stored.connectionId,
697
+ input.analyses,
698
+ gap || phaseChanged,
699
+ signal,
700
+ diagnostic,
701
+ ));
702
+ return { visual: frame, proposals: emitted, moduleStates: this.moduleStateSnapshot() };
703
+ }
704
+
705
+ async flushForEventsQuery(signal = new AbortController().signal): Promise<RuntimeEpochPluginResult> {
706
+ const events = await this.flushModules('events_requested', 'snapshot', signal);
707
+ return events.length > 0
708
+ ? { outcome: 'processed', reason: 'events_requested', events }
709
+ : { outcome: 'noop', reason: 'events_requested' };
710
+ }
711
+
712
+ async flush(
713
+ reason: RuntimeEpochFlushReason,
714
+ context: RuntimeEpochPluginContext<Record<string, any>>,
715
+ ): Promise<void> {
716
+ const events = await this.flushModules(reason, 'close', context.signal, context.diagnostic);
717
+ if (events.length > 0) {
718
+ context.diagnostic('perception.lifecycle_output_uncommitted', {
719
+ event_count: events.length,
720
+ reason,
721
+ });
722
+ }
723
+ await this.resetModules(
724
+ reason,
725
+ context.signal,
726
+ context.diagnostic,
727
+ this.lastFrameSeq + 1,
728
+ );
729
+ this.flushModuleTimingWindows(context.diagnostic, true);
730
+ }
731
+
732
+ stop(reason: 'segment_ending' | 'shutdown'): Promise<void> {
733
+ if (this.runnersStopTask) return this.runnersStopTask;
734
+ this.runnerLifecycleGeneration += 1;
735
+ this.runnersStarted = false;
736
+ let task!: Promise<void>;
737
+ task = this.stopRunners(reason).finally(() => {
738
+ if (this.runnersStopTask === task) this.runnersStopTask = undefined;
739
+ });
740
+ this.runnersStopTask = task;
741
+ return task;
742
+ }
743
+
744
+ private async stopRunners(reason: 'segment_ending' | 'shutdown'): Promise<void> {
745
+ const analysisPool = this.analysisPool;
746
+ this.analysisPool = undefined;
747
+ await analysisPool?.stop();
748
+ // This includes direct imports that are still starting; their own
749
+ // generation fence prevents a late loader result from resurrecting them.
750
+ await Promise.allSettled(this.modules.map(({ runner }) => runner.stop(reason)));
751
+ await this.moduleLoader.stop();
752
+ this.moduleFailureReports.clear();
753
+ this.moduleTimingWindows.clear();
754
+ this.moduleTimingWindowStartedAt = performance.now();
755
+ this.resetProjection();
756
+ }
757
+
758
+ /** Starts the same module lifecycle without constructing a Runtime context. */
759
+ async startForReplay(signal = new AbortController().signal): Promise<void> {
760
+ await this.startRunners(signal);
761
+ }
762
+
763
+ async stopForReplay(): Promise<void> {
764
+ await this.stop('shutdown');
765
+ }
766
+
767
+ moduleDescriptors(): PerceptionModuleDescriptor[] {
768
+ return this.modules.map(({ manifest }) => ({
769
+ ...manifest,
770
+ produces: [...manifest.produces],
771
+ pluginId: CLAWCLAW_PERCEPTION_PLUGIN_ID,
772
+ }));
773
+ }
774
+
775
+ moduleStateSnapshot(): Record<string, unknown> {
776
+ return Object.fromEntries(this.modules.map(({ manifest, runner }) => [
777
+ manifest.id,
778
+ runner.debugSnapshot(),
779
+ ]));
780
+ }
781
+
782
+ private async deliverVisualFrame(
783
+ frame: Readonly<VisualState>,
784
+ connectionId: string,
785
+ analyses: readonly PerceptionModuleAnalysis[],
786
+ discardParallelAnalysis: boolean,
787
+ signal: AbortSignal,
788
+ diagnostic?: PerceptionDiagnostic,
789
+ ): Promise<RuntimeEventProposal[]> {
790
+ this.lastFrameTimeMs = frame.timeMs;
791
+ this.phase = frame.phase;
792
+ this.lastVisualTick = frame.tick;
793
+ this.lastVisualFrame = frame;
794
+ this.lastConnectionId = connectionId;
795
+ this.analysisWindow.push(frame);
796
+ if (this.analysisWindow.length > PERCEPTION_ANALYSIS_WINDOW_FRAMES) this.analysisWindow.shift();
797
+ return this.withOccurredAt(
798
+ await this.updateModules(
799
+ frame,
800
+ analyses,
801
+ discardParallelAnalysis,
802
+ signal,
803
+ diagnostic,
804
+ ),
805
+ frame.timeMs,
806
+ );
807
+ }
808
+
809
+ private async updateModules(
810
+ frame: Readonly<VisualState>,
811
+ analyses: readonly PerceptionModuleAnalysis[],
812
+ discardParallelAnalysis: boolean,
813
+ signal: AbortSignal,
814
+ diagnostic?: PerceptionDiagnostic,
815
+ ): Promise<RuntimeEventProposal[]> {
816
+ const analysisByModule = new Map(analyses.map((entry) => [entry.moduleId, entry] as const));
817
+ this.recordAnalysisResults(analyses, diagnostic);
818
+ return this.collectModuleEvents(
819
+ 'update',
820
+ async (module) => {
821
+ const { manifest, runner } = module;
822
+ if (runner.execution === 'ordered_update') {
823
+ return runner.update(frame, this.api, signal);
824
+ }
825
+ if (!this.shouldRunParallelModuleForFrame(module, frame.frameSeq)) return [];
826
+ const analysis = analysisByModule.get(manifest.id);
827
+ // A computation may have started before the scheduler dropped older
828
+ // epochs. Its analysis can therefore describe relationships to frames
829
+ // that will never commit. Only a module with the explicit current-only
830
+ // contract may install this frame into its freshly reset reducer, and
831
+ // even then no boundary Event is accepted.
832
+ if (discardParallelAnalysis) {
833
+ if (
834
+ manifest.boundaryBaseline !== 'current_only'
835
+ || !analysis
836
+ || analysis.outcome === 'rejected'
837
+ || analysis.generation + 1 !== module.analysisGeneration
838
+ ) {
839
+ module.analysisBaselinePending = true;
840
+ module.reducerReplayFromFrameSeq = null;
841
+ return [];
842
+ }
843
+ await runner.commit(frame, analysis.analysis, this.api, signal);
844
+ module.reducerReplayFromFrameSeq = frame.frameSeq;
845
+ module.analysisBaselinePending = false;
846
+ return [];
847
+ }
848
+ if (!analysis || analysis.outcome === 'rejected') {
849
+ await this.invalidateParallelModule(
850
+ module,
851
+ frame.frameSeq + 1,
852
+ signal,
853
+ );
854
+ return [];
855
+ }
856
+ if (analysis.generation !== module.analysisGeneration) {
857
+ // A current-only hard boundary can install its own frame as the new
858
+ // reducer baseline while later, already-computed frames still belong
859
+ // to the old generation. Dropping those frames creates another
860
+ // reducer discontinuity. Reset once, but do not advance generation:
861
+ // the first valid current-generation analysis can then establish a
862
+ // fresh baseline without emitting an Event.
863
+ if (!module.analysisBaselinePending) {
864
+ module.analysisBaselinePending = true;
865
+ module.reducerReplayFromFrameSeq = null;
866
+ await runner.reset('trajectory_gap', signal);
867
+ }
868
+ return [];
869
+ }
870
+ const events = await runner.commit(frame, analysis.analysis, this.api, signal);
871
+ if (
872
+ module.reducerReplayFromFrameSeq === null
873
+ || (
874
+ module.reducerReplayFromFrameSeq === undefined
875
+ && module.analysisBaselinePending
876
+ && module.analysisHistoryFloorFrameSeq > 0
877
+ )
878
+ ) module.reducerReplayFromFrameSeq = frame.frameSeq;
879
+ if (module.analysisBaselinePending) {
880
+ module.analysisBaselinePending = false;
881
+ return [];
882
+ }
883
+ return events;
884
+ },
885
+ diagnostic,
886
+ async (module) => {
887
+ if (module.runner.execution !== 'parallel_analysis') return;
888
+ await this.invalidateParallelModule(
889
+ module,
890
+ frame.frameSeq + 1,
891
+ signal,
892
+ );
893
+ },
894
+ );
895
+ }
896
+
897
+ private async invalidateParallelModule(
898
+ module: PerceptionModuleSlot,
899
+ historyFloorFrameSeq: number,
900
+ signal: AbortSignal,
901
+ ): Promise<void> {
902
+ this.advanceParallelGeneration(module, historyFloorFrameSeq);
903
+ await module.runner.reset('trajectory_gap', signal);
904
+ }
905
+
906
+ private advanceParallelGeneration(
907
+ module: PerceptionModuleSlot,
908
+ historyFloorFrameSeq: number,
909
+ baselinePending = true,
910
+ ): void {
911
+ module.analysisGeneration += 1;
912
+ module.analysisHistoryFloorFrameSeq = Math.max(
913
+ module.analysisHistoryFloorFrameSeq,
914
+ historyFloorFrameSeq,
915
+ );
916
+ module.analysisBaselinePending = baselinePending;
917
+ module.reducerReplayFromFrameSeq = null;
918
+ }
919
+
920
+ private async prepareFrame(
921
+ stored: StoredStateFrame<Record<string, any>>,
922
+ visual: VisualState | null,
923
+ signal: AbortSignal,
924
+ analysisInput: Readonly<PerceptionAnalysisInput> | null = null,
925
+ ): Promise<PreparedPerceptionFrame> {
926
+ if (!visual || !this.shouldAnalyze(stored)) {
927
+ return { stored, visual, analyses: [] };
928
+ }
929
+ const preparedVisual = analysisInput?.frame ?? visual;
930
+ const analyzerInput = analysisInput ?? this.localAnalysisInput(stored, visual);
931
+ const parallelModules = this.modules.filter((module) => (
932
+ module.runner.execution === 'parallel_analysis'
933
+ && this.shouldRunParallelModuleForFrame(module, stored.frameSeq)
934
+ ));
935
+ if (parallelModules.length === 0) return { stored, visual: preparedVisual, analyses: [] };
936
+ const analysisPool = this.analysisPool;
937
+ if (!analysisPool) throw new Error('perception_analysis_pool_not_started');
938
+ // Capture generations and module-specific history before submitting one
939
+ // frame batch. Ordered commit may advance an individual generation while
940
+ // this Worker is still running; the existing reducer gate rejects it.
941
+ const generations = new Map(parallelModules.map((module) => [
942
+ module.manifest.id,
943
+ module.analysisGeneration,
944
+ ] as const));
945
+ const jobs: PerceptionAnalysisJob[] = parallelModules.map((module) => ({
946
+ moduleId: module.manifest.id,
947
+ input: this.analysisInputForModule(analyzerInput, module),
948
+ }));
949
+ const startedAt = performance.now();
950
+ try {
951
+ signal.throwIfAborted();
952
+ const batch = await analysisPool.analyze(jobs, signal);
953
+ const analyses: PerceptionModuleAnalysis[] = batch.results.map((result) => result.outcome === 'fulfilled'
954
+ ? {
955
+ moduleId: result.moduleId,
956
+ generation: generations.get(result.moduleId)!,
957
+ outcome: 'fulfilled',
958
+ durationMs: result.durationMs,
959
+ analysis: result.analysis,
960
+ }
961
+ : {
962
+ moduleId: result.moduleId,
963
+ generation: generations.get(result.moduleId)!,
964
+ outcome: 'rejected',
965
+ durationMs: result.durationMs,
966
+ failure: result.failure,
967
+ });
968
+ return { stored, visual: preparedVisual, analyses };
969
+ } catch (error) {
970
+ const failure = perceptionFailureDetails(error);
971
+ const durationMs = elapsedMs(startedAt);
972
+ return {
973
+ stored,
974
+ visual: preparedVisual,
975
+ analyses: parallelModules.map((module) => ({
976
+ moduleId: module.manifest.id,
977
+ generation: generations.get(module.manifest.id)!,
978
+ outcome: 'rejected' as const,
979
+ durationMs,
980
+ failure,
981
+ })),
982
+ };
983
+ }
984
+ }
985
+
986
+ private analysisInputForModule(
987
+ input: Readonly<PerceptionAnalysisInput>,
988
+ module: PerceptionModuleSlot,
989
+ ): PerceptionAnalysisInput {
990
+ const floor = module.analysisHistoryFloorFrameSeq;
991
+ if (floor <= 0) return input as PerceptionAnalysisInput;
992
+ const history = input.history.filter((frame) => frame.frameSeq >= floor);
993
+ const previous = history.at(-1);
994
+ const keptImmediatePrevious = previous === input.history.at(-1);
995
+ const tickDelta = previous ? input.frame.tick - previous.tick : null;
996
+ const frame: VisualState = {
997
+ ...input.frame,
998
+ tickDelta,
999
+ continuousFromPrevious: !!previous
1000
+ && keptImmediatePrevious
1001
+ && input.frame.continuousFromPrevious,
1002
+ };
1003
+ return {
1004
+ frame,
1005
+ history,
1006
+ gapBefore: input.gapBefore
1007
+ || history.length !== input.history.length
1008
+ || !frame.continuousFromPrevious,
1009
+ };
1010
+ }
1011
+
1012
+ private shouldRunParallelModuleForFrame(
1013
+ module: PerceptionModuleSlot,
1014
+ frameSeq: number,
1015
+ ): boolean {
1016
+ if (frameSeq < module.analysisHistoryFloorFrameSeq) return false;
1017
+ if (!this.recovering) return true;
1018
+ const replayFrom = module.reducerReplayFromFrameSeq;
1019
+ return replayFrom === undefined || (replayFrom !== null && frameSeq >= replayFrom);
1020
+ }
1021
+
1022
+ private analysisInputFromHistory(
1023
+ stored: StoredStateFrame<Record<string, any>>,
1024
+ currentVisual: VisualState,
1025
+ context: RuntimeEpochPluginContext<Record<string, any>>,
1026
+ ): PerceptionAnalysisInput {
1027
+ const projected = new Map<number, {
1028
+ stored: StoredStateFrame<Record<string, any>>;
1029
+ visual: VisualState;
1030
+ }>();
1031
+ let beforeFrameSeq = stored.frameSeq + 1;
1032
+ while (projected.size < PERCEPTION_ANALYSIS_WINDOW_FRAMES + 1 && beforeFrameSeq > 1) {
1033
+ context.signal.throwIfAborted();
1034
+ const page = context.stateHistory.queryStateFrames({
1035
+ scope: context.scope,
1036
+ beforeFrameSeq,
1037
+ order: 'desc',
1038
+ limit: 32,
1039
+ });
1040
+ if (page.frames.length === 0) break;
1041
+ for (const candidate of page.frames) {
1042
+ if (candidate.frameSeq > stored.frameSeq) continue;
1043
+ const visual = candidate.frameSeq === stored.frameSeq
1044
+ ? currentVisual
1045
+ : this.projector.project(candidate);
1046
+ if (visual) projected.set(candidate.frameSeq, { stored: candidate, visual });
1047
+ if (projected.size >= PERCEPTION_ANALYSIS_WINDOW_FRAMES + 1) break;
1048
+ }
1049
+ beforeFrameSeq = page.frames.at(-1)!.frameSeq;
1050
+ if (!page.page.hasMore) break;
1051
+ }
1052
+ if (!projected.has(stored.frameSeq)) {
1053
+ projected.set(stored.frameSeq, { stored, visual: currentVisual });
1054
+ }
1055
+ const values = [...projected.values()]
1056
+ .sort((left, right) => left.stored.frameSeq - right.stored.frameSeq);
1057
+ const enriched: VisualState[] = [];
1058
+ values.forEach((value, index) => {
1059
+ const previous = index > 0 ? values[index - 1] : undefined;
1060
+ const before = enriched.at(-1);
1061
+ const tickDelta = before ? value.visual.tick - before.tick : null;
1062
+ const continuousFromPrevious = !!before
1063
+ && before.phase === value.visual.phase
1064
+ && tickDelta !== null
1065
+ && tickDelta >= 0
1066
+ && tickDelta <= 3
1067
+ && previous?.stored.connectionId === value.stored.connectionId;
1068
+ enriched.push({ ...value.visual, tickDelta, continuousFromPrevious });
1069
+ });
1070
+ const bounded = enriched.slice(-PERCEPTION_ANALYSIS_WINDOW_FRAMES);
1071
+ const frame = bounded.at(-1)!;
1072
+ const history = bounded.slice(0, -1);
1073
+ return {
1074
+ frame,
1075
+ history,
1076
+ gapBefore: history.length > 0 && !frame.continuousFromPrevious,
1077
+ };
1078
+ }
1079
+
1080
+ private localAnalysisInput(
1081
+ stored: StoredStateFrame<Record<string, any>>,
1082
+ visual: VisualState,
1083
+ ): PerceptionAnalysisInput {
1084
+ const history = this.analysisWindow.slice(-(PERCEPTION_ANALYSIS_WINDOW_FRAMES - 1));
1085
+ const previous = history.at(-1);
1086
+ const tickDelta = previous ? visual.tick - previous.tick : null;
1087
+ const frame: VisualState = {
1088
+ ...visual,
1089
+ tickDelta,
1090
+ continuousFromPrevious: !!previous
1091
+ && previous.phase === visual.phase
1092
+ && tickDelta !== null
1093
+ && tickDelta >= 0
1094
+ && tickDelta <= 3
1095
+ && this.lastConnectionId === stored.connectionId,
1096
+ };
1097
+ return {
1098
+ frame,
1099
+ history,
1100
+ gapBefore: history.length > 0 && !frame.continuousFromPrevious,
1101
+ };
1102
+ }
1103
+
1104
+ private shouldAnalyze(stored: StoredStateFrame<Record<string, any>>): boolean {
1105
+ const runtimeState = stored.state;
1106
+ if (!isClawclawRuntimeState(runtimeState)) return true;
1107
+ return runtimeState.connection === 'connected'
1108
+ && runtimeState.stage !== 'ended'
1109
+ && runtimeState.game_snapshot.status === 'fresh'
1110
+ && !(
1111
+ runtimeState.cause === 'agent_events_query'
1112
+ && runtimeState.control?.type === 'events_query'
1113
+ );
1114
+ }
1115
+
1116
+ private computationProposal(value: unknown): PerceptionComputationProposal {
1117
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
1118
+ throw new Error('perception_computation_missing');
1119
+ }
1120
+ const proposal = value as Partial<PerceptionComputationProposal>;
1121
+ if (
1122
+ proposal.schema !== PERCEPTION_COMPUTATION_SCHEMA
1123
+ || !Array.isArray(proposal.analyses)
1124
+ || (proposal.visual !== null && typeof proposal.visual !== 'object')
1125
+ ) throw new Error('perception_computation_invalid');
1126
+ return proposal as PerceptionComputationProposal;
1127
+ }
1128
+
1129
+ private recordAnalysisResults(
1130
+ analyses: readonly PerceptionModuleAnalysis[],
1131
+ diagnostic?: PerceptionDiagnostic,
1132
+ ): void {
1133
+ if (analyses.length === 0) return;
1134
+ this.recordModuleTimings('analyze', analyses.map((entry) => ({
1135
+ module_id: entry.moduleId,
1136
+ duration_ms: entry.durationMs,
1137
+ outcome: entry.outcome,
1138
+ event_count: 0,
1139
+ })));
1140
+ this.flushModuleTimingWindows(diagnostic);
1141
+ for (const entry of analyses) {
1142
+ if (entry.outcome !== 'rejected' || !entry.failure) continue;
1143
+ this.reportModuleFailure(entry.moduleId, 'analyze', entry.failure, diagnostic);
1144
+ }
1145
+ }
1146
+
1147
+ private async flushModules(
1148
+ kind: PerceptionBoundaryKind,
1149
+ mode: PerceptionBoundary['mode'],
1150
+ signal: AbortSignal,
1151
+ diagnostic?: PerceptionDiagnostic,
1152
+ ): Promise<RuntimeEventProposal[]> {
1153
+ const boundary: PerceptionBoundary = Object.freeze({
1154
+ kind,
1155
+ mode,
1156
+ through: this.lastVisualFrame,
1157
+ });
1158
+ const output = await this.collectModuleEvents(
1159
+ `flush:${kind}`,
1160
+ ({ runner }) => runner.flush(boundary, this.api, signal),
1161
+ diagnostic,
1162
+ );
1163
+ return this.withOccurredAt(output, boundary.through?.timeMs ?? this.lastFrameTimeMs);
1164
+ }
1165
+
1166
+ private async flushAndReset(
1167
+ kind: Exclude<PerceptionBoundaryKind, 'events_requested'>,
1168
+ signal: AbortSignal,
1169
+ diagnostic?: PerceptionDiagnostic,
1170
+ replayFromFrameSeq: number | null = null,
1171
+ ): Promise<RuntimeEventProposal[]> {
1172
+ const emitted = await this.flushModules(kind, 'close', signal, diagnostic);
1173
+ await this.resetModules(
1174
+ kind,
1175
+ signal,
1176
+ diagnostic,
1177
+ replayFromFrameSeq ?? this.lastFrameSeq + 1,
1178
+ );
1179
+ this.phase = null;
1180
+ this.lastFrameTimeMs = null;
1181
+ this.lastVisualTick = null;
1182
+ this.lastVisualFrame = null;
1183
+ this.lastConnectionId = null;
1184
+ this.analysisWindow.length = 0;
1185
+ this.replayFromFrameSeq = replayFromFrameSeq;
1186
+ return emitted;
1187
+ }
1188
+
1189
+ private async resetModules(
1190
+ reason: Exclude<PerceptionBoundaryKind, 'events_requested'> | 'replay',
1191
+ signal: AbortSignal,
1192
+ diagnostic?: PerceptionDiagnostic,
1193
+ parallelHistoryFloorFrameSeq?: number,
1194
+ parallelBaselinePending = true,
1195
+ ): Promise<void> {
1196
+ if (parallelHistoryFloorFrameSeq !== undefined) {
1197
+ for (const module of this.modules) {
1198
+ if (module.runner.execution !== 'parallel_analysis') continue;
1199
+ this.advanceParallelGeneration(
1200
+ module,
1201
+ parallelHistoryFloorFrameSeq,
1202
+ parallelBaselinePending || module.manifest.boundaryBaseline !== 'current_only',
1203
+ );
1204
+ }
1205
+ }
1206
+ const results = await Promise.allSettled(
1207
+ this.modules.map(({ runner }) => runner.reset(reason, signal)),
1208
+ );
1209
+ this.reportModuleFailures(`reset:${reason}`, results, diagnostic);
1210
+ }
1211
+
1212
+ private async collectModuleEvents(
1213
+ operation: string,
1214
+ invoke: (
1215
+ module: PerceptionModuleSlot,
1216
+ ) => readonly PerceptionEventProposal[] | void | Promise<readonly PerceptionEventProposal[] | void>,
1217
+ diagnostic?: PerceptionDiagnostic,
1218
+ onRejected?: (module: PerceptionModuleSlot, error: unknown) => void | Promise<void>,
1219
+ ): Promise<RuntimeEventProposal[]> {
1220
+ const timings: Array<{
1221
+ module_id: string;
1222
+ duration_ms: number;
1223
+ outcome: 'fulfilled' | 'rejected';
1224
+ event_count: number;
1225
+ }> = new Array(this.modules.length);
1226
+ const results = await Promise.allSettled(this.modules.map(async (module, index) => {
1227
+ const startedAt = performance.now();
1228
+ try {
1229
+ const result = await invoke(module);
1230
+ timings[index] = {
1231
+ module_id: module.manifest.id,
1232
+ duration_ms: elapsedMs(startedAt),
1233
+ outcome: 'fulfilled',
1234
+ event_count: proposals(result).length,
1235
+ };
1236
+ return result;
1237
+ } catch (error) {
1238
+ timings[index] = {
1239
+ module_id: module.manifest.id,
1240
+ duration_ms: elapsedMs(startedAt),
1241
+ outcome: 'rejected',
1242
+ event_count: 0,
1243
+ };
1244
+ throw error;
1245
+ }
1246
+ }));
1247
+ this.reportModuleFailures(operation, results, diagnostic);
1248
+ if (onRejected) {
1249
+ await Promise.allSettled(results.map((result, index) => (
1250
+ result.status === 'rejected'
1251
+ ? onRejected(this.modules[index]!, result.reason)
1252
+ : Promise.resolve()
1253
+ )));
1254
+ }
1255
+ if (diagnostic) {
1256
+ this.recordModuleTimings(operation, timings);
1257
+ this.flushModuleTimingWindows(diagnostic);
1258
+ }
1259
+ return results.flatMap((result) => (
1260
+ result.status === 'fulfilled' ? proposals(result.value) : []
1261
+ ));
1262
+ }
1263
+
1264
+ private recordModuleTimings(
1265
+ operation: string,
1266
+ timings: readonly {
1267
+ module_id: string;
1268
+ duration_ms: number;
1269
+ outcome: 'fulfilled' | 'rejected';
1270
+ event_count: number;
1271
+ }[],
1272
+ ): void {
1273
+ for (const timing of timings) {
1274
+ const key = `${timing.module_id}\0${operation}`;
1275
+ let window = this.moduleTimingWindows.get(key);
1276
+ if (!window) {
1277
+ window = {
1278
+ moduleId: timing.module_id,
1279
+ operation,
1280
+ durationsMs: [],
1281
+ eventCount: 0,
1282
+ failureCount: 0,
1283
+ };
1284
+ this.moduleTimingWindows.set(key, window);
1285
+ }
1286
+ window.durationsMs.push(timing.duration_ms);
1287
+ window.eventCount += timing.event_count;
1288
+ if (timing.outcome === 'rejected') window.failureCount += 1;
1289
+ }
1290
+ }
1291
+
1292
+ private flushModuleTimingWindows(
1293
+ diagnostic: PerceptionDiagnostic | undefined,
1294
+ force = false,
1295
+ ): void {
1296
+ if (!diagnostic || this.moduleTimingWindows.size === 0) return;
1297
+ const now = performance.now();
1298
+ const windowMs = Math.max(0, now - this.moduleTimingWindowStartedAt);
1299
+ if (!force && windowMs < PERCEPTION_MODULE_TIMING_WINDOW_MS) return;
1300
+ for (const window of this.moduleTimingWindows.values()) {
1301
+ diagnostic('perception.module.timing_window', {
1302
+ module_id: window.moduleId,
1303
+ operation: window.operation,
1304
+ window_ms: Math.round(windowMs),
1305
+ count: window.durationsMs.length,
1306
+ average_duration_ms: roundedAverage(window.durationsMs),
1307
+ p95_duration_ms: percentile95(window.durationsMs),
1308
+ max_duration_ms: Math.max(...window.durationsMs),
1309
+ failure_count: window.failureCount,
1310
+ event_count: window.eventCount,
1311
+ });
1312
+ }
1313
+ this.moduleTimingWindows.clear();
1314
+ this.moduleTimingWindowStartedAt = now;
1315
+ }
1316
+
1317
+ private reportModuleFailures(
1318
+ operation: string,
1319
+ results: readonly PromiseSettledResult<unknown>[],
1320
+ diagnostic?: PerceptionDiagnostic,
1321
+ ): void {
1322
+ results.forEach((result, index) => {
1323
+ if (result.status === 'fulfilled' || !diagnostic) return;
1324
+ const moduleId = this.modules[index].manifest.id;
1325
+ this.reportModuleFailure(
1326
+ moduleId,
1327
+ operation,
1328
+ perceptionFailureDetails(result.reason),
1329
+ diagnostic,
1330
+ );
1331
+ });
1332
+ }
1333
+
1334
+ private reportModuleFailure(
1335
+ moduleId: string,
1336
+ operation: string,
1337
+ details: Readonly<{
1338
+ errorCode: string;
1339
+ messagePresent: boolean;
1340
+ messageLength?: number;
1341
+ }>,
1342
+ diagnostic?: PerceptionDiagnostic,
1343
+ ): void {
1344
+ if (!diagnostic) return;
1345
+ const now = Date.now();
1346
+ const previous = this.moduleFailureReports.get(moduleId);
1347
+ const failureCount = (previous?.failureCount ?? 0) + 1;
1348
+ if (previous && now - previous.lastReportedAtMs < PERCEPTION_FAILURE_REPORT_WINDOW_MS) {
1349
+ this.moduleFailureReports.set(moduleId, {
1350
+ ...previous,
1351
+ failureCount,
1352
+ suppressedCount: previous.suppressedCount + 1,
1353
+ });
1354
+ return;
1355
+ }
1356
+ diagnostic('perception.module.failed', {
1357
+ module_id: moduleId,
1358
+ operation,
1359
+ error_code: details.errorCode,
1360
+ error_message_present: details.messagePresent,
1361
+ error_message_length: details.messageLength,
1362
+ failure_count: failureCount,
1363
+ suppressed_failure_count: previous?.suppressedCount ?? 0,
1364
+ }, 'error');
1365
+ this.moduleFailureReports.set(moduleId, {
1366
+ lastReportedAtMs: now,
1367
+ failureCount,
1368
+ suppressedCount: 0,
1369
+ });
1370
+ }
1371
+
1372
+ private startRunners(
1373
+ signal: AbortSignal,
1374
+ diagnostic?: PerceptionDiagnostic,
1375
+ ): Promise<void> {
1376
+ signal.throwIfAborted();
1377
+ if (this.runnersStarted) return Promise.resolve();
1378
+ if (this.runnersStopTask) {
1379
+ const pending = [this.runnersStopTask, this.runnersStartTask].filter(
1380
+ (task): task is Promise<void> => !!task,
1381
+ );
1382
+ return Promise.allSettled(pending).then(() => {
1383
+ signal.throwIfAborted();
1384
+ return this.startRunners(signal, diagnostic);
1385
+ });
1386
+ }
1387
+ if (this.runnersStartTask) {
1388
+ if (this.runnersStartGeneration === this.runnerLifecycleGeneration) {
1389
+ return this.runnersStartTask;
1390
+ }
1391
+ return this.runnersStartTask.catch(() => {}).then(() => {
1392
+ signal.throwIfAborted();
1393
+ return this.startRunners(signal, diagnostic);
1394
+ });
1395
+ }
1396
+ const generation = ++this.runnerLifecycleGeneration;
1397
+ let task!: Promise<void>;
1398
+ task = this.startRunnersInternal(signal, diagnostic, generation).finally(() => {
1399
+ if (this.runnersStartTask === task) this.runnersStartTask = undefined;
1400
+ });
1401
+ this.runnersStartGeneration = generation;
1402
+ this.runnersStartTask = task;
1403
+ return task;
1404
+ }
1405
+
1406
+ private async startRunnersInternal(
1407
+ signal: AbortSignal,
1408
+ diagnostic: PerceptionDiagnostic | undefined,
1409
+ generation: number,
1410
+ ): Promise<void> {
1411
+ let analysisPool: PerceptionAnalysisThreadPool | undefined;
1412
+ try {
1413
+ const parallelModules = this.modules.filter(({ runner }) => (
1414
+ runner.execution === 'parallel_analysis'
1415
+ ));
1416
+ const threadModules: PerceptionThreadModuleSpec[] = await Promise.all(
1417
+ parallelModules.map(async (module) => module.customSource
1418
+ ? this.moduleLoader.threadSpec(module.customSource)
1419
+ : {
1420
+ moduleId: module.manifest.id,
1421
+ kind: 'official' as const,
1422
+ }),
1423
+ );
1424
+ this.assertRunnerLifecycle(generation, signal);
1425
+ analysisPool = threadModules.length > 0
1426
+ ? new PerceptionAnalysisThreadPool({
1427
+ modules: threadModules,
1428
+ loader: this.moduleLoader.threadConfig(),
1429
+ spatialFacts: CLAWCLAW_PERCEPTION_SPATIAL_FACTS satisfies PerceptionSpatialFacts,
1430
+ maxWorkers: this.maxInFlight,
1431
+ diagnostic,
1432
+ })
1433
+ : undefined;
1434
+ this.analysisPool = analysisPool;
1435
+ await Promise.all([
1436
+ ...this.modules.map(({ runner }) => runner.start(
1437
+ CLAWCLAW_PERCEPTION_SPATIAL_FACTS satisfies PerceptionSpatialFacts,
1438
+ this.api,
1439
+ signal,
1440
+ )),
1441
+ ...(analysisPool ? [analysisPool.start()] : []),
1442
+ ]);
1443
+ this.assertRunnerLifecycle(generation, signal);
1444
+ this.moduleTimingWindows.clear();
1445
+ this.moduleTimingWindowStartedAt = performance.now();
1446
+ await this.resetModules('replay', signal);
1447
+ this.assertRunnerLifecycle(generation, signal);
1448
+ this.resetProjection();
1449
+ this.runnersStarted = true;
1450
+ } catch (error) {
1451
+ await analysisPool?.stop();
1452
+ if (this.analysisPool === analysisPool) this.analysisPool = undefined;
1453
+ await Promise.allSettled(this.modules.map(({ runner }) => runner.stop('shutdown')));
1454
+ if (generation === this.runnerLifecycleGeneration) {
1455
+ await this.moduleLoader.stop();
1456
+ this.runnersStarted = false;
1457
+ }
1458
+ throw error;
1459
+ }
1460
+ }
1461
+
1462
+ private assertRunnerLifecycle(generation: number, signal: AbortSignal): void {
1463
+ signal.throwIfAborted();
1464
+ if (generation !== this.runnerLifecycleGeneration) {
1465
+ throw new Error('perception_runners_start_cancelled');
1466
+ }
1467
+ }
1468
+
1469
+ private resetProjection(): void {
1470
+ this.projector.reset();
1471
+ this.phase = null;
1472
+ this.lastFrameSeq = 0;
1473
+ this.lastFrameTimeMs = null;
1474
+ this.lastVisualTick = null;
1475
+ this.lastVisualFrame = null;
1476
+ this.lastConnectionId = null;
1477
+ this.analysisWindow.length = 0;
1478
+ this.replayFromFrameSeq = null;
1479
+ }
1480
+
1481
+ private checkpointValue(): PerceptionCheckpoint {
1482
+ const parallelModuleHistoryFloors = Object.fromEntries(this.modules.flatMap((module) => (
1483
+ module.runner.execution === 'parallel_analysis'
1484
+ && module.analysisHistoryFloorFrameSeq > 0
1485
+ ? [[module.manifest.id, module.analysisHistoryFloorFrameSeq] as const]
1486
+ : []
1487
+ )));
1488
+ const parallelModuleReducerReplayStarts = Object.fromEntries(this.modules.flatMap((module) => (
1489
+ module.runner.execution === 'parallel_analysis'
1490
+ && module.reducerReplayFromFrameSeq !== undefined
1491
+ ? [[module.manifest.id, module.reducerReplayFromFrameSeq] as const]
1492
+ : []
1493
+ )));
1494
+ const parallelModuleBaselinePending = Object.fromEntries(this.modules.flatMap((module) => (
1495
+ module.runner.execution === 'parallel_analysis'
1496
+ && (
1497
+ module.analysisHistoryFloorFrameSeq > 0
1498
+ || module.reducerReplayFromFrameSeq !== undefined
1499
+ )
1500
+ ? [[module.manifest.id, module.analysisBaselinePending] as const]
1501
+ : []
1502
+ )));
1503
+ return {
1504
+ schema: PERCEPTION_CHECKPOINT_SCHEMA,
1505
+ replayFromFrameSeq: this.replayFromFrameSeq,
1506
+ ...(Object.keys(parallelModuleHistoryFloors).length === 0
1507
+ ? {}
1508
+ : { parallelModuleHistoryFloors }),
1509
+ ...(Object.keys(parallelModuleReducerReplayStarts).length === 0
1510
+ ? {}
1511
+ : { parallelModuleReducerReplayStarts }),
1512
+ ...(Object.keys(parallelModuleBaselinePending).length === 0
1513
+ ? {}
1514
+ : { parallelModuleBaselinePending }),
1515
+ };
1516
+ }
1517
+
1518
+ private withOccurredAt(
1519
+ values: readonly RuntimeEventProposal[],
1520
+ timeMs: number | null,
1521
+ ): RuntimeEventProposal[] {
1522
+ const occurredAt = timeMs !== null && Number.isFinite(timeMs)
1523
+ ? new Date(timeMs).toISOString()
1524
+ : undefined;
1525
+ return values.map((proposal) => (
1526
+ proposal.occurredAt || !occurredAt ? proposal : { ...proposal, occurredAt }
1527
+ ));
1528
+ }
1529
+ }