@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,1516 @@
1
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { afterEach, describe, expect, it, vi } from 'vitest';
5
+ import { createClawclawEventCatalog } from '../../../clawclaw-event-catalog.js';
6
+ import { MemoryEventRepository } from '../../../framework/events/index.js';
7
+ import type {
8
+ RuntimeEpochPluginContext,
9
+ RuntimeEpochPluginInput,
10
+ } from '../../../framework/plugins/index.js';
11
+ import { Runtime } from '../../../framework/runtime.js';
12
+ import type { StoredStateFrame } from '../../../framework/state/history/contracts.js';
13
+ import { MemoryStateHistoryRepository } from '../../../framework/state/history/memory-state-history-repository.js';
14
+ import {
15
+ CLAWCLAW_PERCEPTION_PLUGIN_ID,
16
+ ClawclawPerceptionPlugin,
17
+ } from './perception-plugin.js';
18
+ import { LocalPerceptionModuleRunner } from './module-runner.js';
19
+ import { VisualStateProjector } from './visual-state-projector.js';
20
+
21
+ function stored(
22
+ frameSeq: number,
23
+ tick: number,
24
+ state: Record<string, any>,
25
+ connectionId = 'ws',
26
+ ): StoredStateFrame<Record<string, any>> {
27
+ return {
28
+ frameSeq,
29
+ epochSeq: frameSeq,
30
+ scope: {
31
+ adapterId: 'clawclaw',
32
+ accountId: 'account',
33
+ sessionId: 'session',
34
+ segmentId: 'game',
35
+ },
36
+ connectionId,
37
+ sourceKey: `state:${frameSeq}`,
38
+ backendTick: tick,
39
+ observedAtMs: tick * 100,
40
+ receivedAtMs: tick * 100,
41
+ state: { tick, phase: 'wandering', ...state },
42
+ };
43
+ }
44
+
45
+ function stateAt(tick: number, sevenX: number, nineX?: number) {
46
+ return {
47
+ players: [
48
+ { seat: 1, name: 'Observer', known_status: { is_alive: true } },
49
+ { seat: 7, name: 'Seven', known_status: { is_alive: true } },
50
+ { seat: 9, name: 'Nine', known_status: { is_alive: true } },
51
+ ],
52
+ you: {
53
+ player: { seat: 1, name: 'Observer' },
54
+ x: 760,
55
+ y: 2200,
56
+ room: '导航仓',
57
+ is_alive: true,
58
+ },
59
+ visible_players: [
60
+ { player: { seat: 7, name: 'Seven' }, x: sevenX, y: 2200, room: '导航仓', distance: 140 },
61
+ ...(nineX === undefined
62
+ ? []
63
+ : [{ player: { seat: 9, name: 'Nine' }, x: nineX, y: 2200, room: '导航仓', distance: 80 }]),
64
+ ],
65
+ visible_corpses: [],
66
+ tick,
67
+ };
68
+ }
69
+
70
+ const replayPlugins = new Set<ClawclawPerceptionPlugin>();
71
+
72
+ function pluginFor(id: string) {
73
+ const plugin = new ClawclawPerceptionPlugin({ modules: [id] });
74
+ replayPlugins.add(plugin);
75
+ return plugin;
76
+ }
77
+
78
+ afterEach(async () => {
79
+ await Promise.allSettled([...replayPlugins].map((plugin) => plugin.stopForReplay()));
80
+ replayPlugins.clear();
81
+ });
82
+
83
+ const journals = new WeakMap<
84
+ ClawclawPerceptionPlugin,
85
+ MemoryStateHistoryRepository<unknown, Record<string, any>>
86
+ >();
87
+
88
+ function pluginContext(
89
+ plugin: ClawclawPerceptionPlugin,
90
+ scope: StoredStateFrame<Record<string, any>>['scope'],
91
+ completedThroughEpochSeq = 0,
92
+ checkpoint?: unknown,
93
+ diagnostic: RuntimeEpochPluginContext<Record<string, any>>['diagnostic'] = () => {},
94
+ ): RuntimeEpochPluginContext<Record<string, any>> {
95
+ let journal = journals.get(plugin);
96
+ if (!journal) {
97
+ journal = new MemoryStateHistoryRepository<unknown, Record<string, any>>();
98
+ journal.openScope(scope);
99
+ journals.set(plugin, journal);
100
+ }
101
+ return {
102
+ scope,
103
+ stateHistory: journal,
104
+ currentSegment: () => ({ kind: 'game' }),
105
+ checkpoint: () => checkpoint,
106
+ progress: () => ({
107
+ pluginId: plugin.id,
108
+ completedThroughEpochSeq,
109
+ eventCursor: 0,
110
+ updatedAt: new Date().toISOString(),
111
+ }),
112
+ capabilities: {
113
+ provideObservation: () => { throw new Error('unused'); },
114
+ provideAction: () => { throw new Error('unused'); },
115
+ queryObservation: () => Promise.reject(new Error('unused')),
116
+ performAction: () => Promise.reject(new Error('unused')),
117
+ releaseActionCaller: () => {},
118
+ },
119
+ diagnostic,
120
+ signal: new AbortController().signal,
121
+ };
122
+ }
123
+
124
+ function epochInput(
125
+ frame: StoredStateFrame<Record<string, any>>,
126
+ previousState: Record<string, any> | null = null,
127
+ ): RuntimeEpochPluginInput<Record<string, any>> {
128
+ return {
129
+ epoch: {
130
+ epochSeq: frame.frameSeq,
131
+ scope: frame.scope,
132
+ sourceId: 'test',
133
+ connectionId: frame.connectionId,
134
+ sourceKey: frame.sourceKey,
135
+ domainTick: frame.backendTick,
136
+ state: frame.state,
137
+ events: [],
138
+ completeness: 'complete',
139
+ receivedAt: new Date(frame.receivedAtMs).toISOString(),
140
+ },
141
+ frame,
142
+ currentState: {
143
+ state: frame.state,
144
+ stateStatus: {
145
+ status: 'fresh',
146
+ semantics: 'latest_received',
147
+ source: 'owner_memory',
148
+ scope: frame.scope,
149
+ connectionId: frame.connectionId,
150
+ connectionState: 'connected',
151
+ receivedAtMs: frame.receivedAtMs,
152
+ ageMs: 0,
153
+ backendTick: frame.backendTick ?? null,
154
+ reason: null,
155
+ },
156
+ },
157
+ previousState,
158
+ epochEvents: [],
159
+ pendingEvents: [],
160
+ upstreamStates: {},
161
+ };
162
+ }
163
+
164
+ async function updatePlugin(
165
+ plugin: ClawclawPerceptionPlugin,
166
+ input: RuntimeEpochPluginInput<Record<string, any>>,
167
+ ) {
168
+ await plugin.startForReplay();
169
+ const context = pluginContext(plugin, input.frame.scope);
170
+ const frame = journals.get(plugin)!.appendStateFrame(input.frame).frame;
171
+ const committedInput = { ...input, frame };
172
+ const computation = await plugin.update(committedInput, context);
173
+ return plugin.commit(committedInput, computation, context);
174
+ }
175
+
176
+ describe('ClawClaw Perception plugin', () => {
177
+ it('cannot resurrect runners when stop overlaps their startup', async () => {
178
+ const plugin = new ClawclawPerceptionPlugin({
179
+ modules: ['visual.visibility'],
180
+ maxBackfillVisualFrames: 1,
181
+ });
182
+ replayPlugins.add(plugin);
183
+ const starting = plugin.startForReplay().then(
184
+ () => undefined,
185
+ (error: unknown) => error,
186
+ );
187
+
188
+ await plugin.stopForReplay();
189
+
190
+ await expect(starting).resolves.toMatchObject({
191
+ message: 'perception_runners_start_cancelled',
192
+ });
193
+ expect((plugin as any).runnersStarted).toBe(false);
194
+ expect((plugin as any).analysisPool).toBeUndefined();
195
+
196
+ await plugin.startForReplay();
197
+ expect((plugin as any).runnersStarted).toBe(true);
198
+ expect((plugin as any).analysisPool.snapshot()).toMatchObject({
199
+ state: 'running',
200
+ workerCount: 1,
201
+ });
202
+ });
203
+
204
+ it('caps the Runtime in-flight perception window at ten', () => {
205
+ expect(() => new ClawclawPerceptionPlugin({ maxBackfillVisualFrames: 11 }))
206
+ .toThrow('maxBackfillVisualFrames must be an integer between 1 and 10');
207
+ expect(new ClawclawPerceptionPlugin({ maxBackfillVisualFrames: 10 }).maxInFlight).toBe(10);
208
+ const official = new ClawclawPerceptionPlugin({
209
+ modules: ['visual.visibility'],
210
+ maxBackfillVisualFrames: 10,
211
+ });
212
+ expect(official.maxInFlight).toBe(10);
213
+ expect(official.catchUp).toBe('every_epoch');
214
+ });
215
+
216
+ it('aggregates every perception module duration into a compact lifecycle timing window', async () => {
217
+ const plugin = new ClawclawPerceptionPlugin({
218
+ modules: ['visual.visibility', 'visual.motion'],
219
+ });
220
+ const diagnostics: Array<{
221
+ name: string;
222
+ attributes?: Readonly<Record<string, unknown>>;
223
+ }> = [];
224
+ const frame = stored(1, 10, stateAt(10, 900));
225
+ const context = pluginContext(
226
+ plugin,
227
+ frame.scope,
228
+ 0,
229
+ undefined,
230
+ (name, attributes) => diagnostics.push({ name, attributes }),
231
+ );
232
+ const persisted = journals.get(plugin)!.appendStateFrame(frame).frame;
233
+
234
+ await plugin.start(context);
235
+ const input = epochInput(persisted);
236
+ const computation = await plugin.update(input, context);
237
+ await plugin.commit(input, computation, context);
238
+ expect(diagnostics.some((entry) => entry.name === 'perception.module.timing_window'))
239
+ .toBe(false);
240
+ await plugin.flush('shutdown', context);
241
+
242
+ const timings = diagnostics.filter((entry) => (
243
+ entry.name === 'perception.module.timing_window'
244
+ && entry.attributes?.operation === 'update'
245
+ ));
246
+ expect(timings).toHaveLength(2);
247
+ expect(timings.map((entry) => entry.attributes?.module_id).sort()).toEqual([
248
+ 'visual.motion',
249
+ 'visual.visibility',
250
+ ]);
251
+ expect(timings).toEqual(expect.arrayContaining([
252
+ expect.objectContaining({
253
+ attributes: expect.objectContaining({
254
+ count: 1,
255
+ average_duration_ms: expect.any(Number),
256
+ p95_duration_ms: expect.any(Number),
257
+ max_duration_ms: expect.any(Number),
258
+ failure_count: 0,
259
+ event_count: expect.any(Number),
260
+ }),
261
+ }),
262
+ ]));
263
+ expect(JSON.stringify(timings)).not.toContain('visible_players');
264
+ });
265
+
266
+ it('projects self and visible players into one explicitly marked visual set', () => {
267
+ const visual = new VisualStateProjector().project(stored(1, 10, stateAt(10, 900)));
268
+ expect(visual?.players).toEqual(expect.arrayContaining([
269
+ expect.objectContaining({ seat: 1, observer: true }),
270
+ expect.objectContaining({ seat: 7, observer: false }),
271
+ ]));
272
+ });
273
+
274
+ it('uses packaged map geometry as the only room authority', () => {
275
+ const visual = new VisualStateProjector().project(stored(1, 10, {
276
+ players: [{ seat: 1, name: 'Observer', known_status: { is_alive: true } }],
277
+ you: {
278
+ player: { seat: 1, name: 'Observer' },
279
+ x: -1,
280
+ y: -1,
281
+ room: '酒吧',
282
+ is_alive: true,
283
+ },
284
+ visible_players: [],
285
+ visible_corpses: [],
286
+ }));
287
+
288
+ expect(visual?.players[0]?.room).toBeNull();
289
+ });
290
+
291
+ it('projects v2 visible_corpses and rejects legacy flat visual identities', () => {
292
+ const projector = new VisualStateProjector();
293
+ const visual = projector.project(stored(1, 10, {
294
+ players: [
295
+ { seat: 1, name: 'Observer', known_status: { is_alive: true } },
296
+ { seat: 7, name: 'Seven', known_status: { is_alive: false } },
297
+ ],
298
+ you: {
299
+ player: { seat: 1, name: 'Observer' },
300
+ x: 760,
301
+ y: 2200,
302
+ room: '导航仓',
303
+ is_alive: true,
304
+ },
305
+ visible_players: [],
306
+ visible_corpses: [{
307
+ player: { seat: 7, name: 'Seven' },
308
+ x: 900,
309
+ y: 2200,
310
+ room: '导航仓',
311
+ distance: 140,
312
+ }],
313
+ }));
314
+ expect(visual?.corpses).toEqual([expect.objectContaining({
315
+ id: 'corpse:7',
316
+ playerId: 'seat:7',
317
+ name: 'Seven',
318
+ seat: 7,
319
+ })]);
320
+
321
+ expect(projector.project(stored(2, 11, {
322
+ you: { name: 'Observer', seat: 1, x: 760, y: 2200, is_alive: true },
323
+ visible_players: [{ name: 'Seven', seat: 7, x: 900, y: 2200 }],
324
+ nearby_corpses: [{ name: 'Seven', seat: 7, x: 900, y: 2200 }],
325
+ }))).toBeNull();
326
+ });
327
+
328
+ it('hosts all official modules behind one Runtime identity and preserves subject scopes', () => {
329
+ const plugin = new ClawclawPerceptionPlugin();
330
+ expect(plugin.id).toBe(CLAWCLAW_PERCEPTION_PLUGIN_ID);
331
+ expect(plugin.moduleDescriptors()).toHaveLength(7);
332
+ expect(new Set(plugin.moduleDescriptors().map((module) => module.pluginId))).toEqual(
333
+ new Set([CLAWCLAW_PERCEPTION_PLUGIN_ID]),
334
+ );
335
+ expect(plugin.moduleDescriptors().every((module) => (
336
+ module.execution === 'parallel_analysis'
337
+ && module.boundaryBaseline === 'current_only'
338
+ ))).toBe(true);
339
+ expect((plugin as any).modules.every(({ runner }: any) => (
340
+ runner instanceof LocalPerceptionModuleRunner
341
+ ))).toBe(true);
342
+ expect(plugin.moduleDescriptors()).toEqual(expect.arrayContaining([
343
+ expect.objectContaining({ id: 'visual.visibility', subjectScope: 'others' }),
344
+ expect.objectContaining({ id: 'visual.motion', subjectScope: 'self_and_others' }),
345
+ expect.objectContaining({ id: 'visual.follow', subjectScope: 'visible_pairs' }),
346
+ ]));
347
+ });
348
+
349
+ it('starts, analyzes, commits, and stops all seven official Worker modules together', async () => {
350
+ const plugin = new ClawclawPerceptionPlugin();
351
+ replayPlugins.add(plugin);
352
+ const outcomes = [];
353
+ for (let tick = 1; tick <= 4; tick += 1) {
354
+ outcomes.push(await updatePlugin(
355
+ plugin,
356
+ epochInput(stored(tick, tick, stateAt(tick, 900 + tick * 6, 840 + tick * 6))),
357
+ ));
358
+ }
359
+
360
+ expect(outcomes).toHaveLength(4);
361
+ expect(outcomes.every((outcome) => outcome.outcome === 'processed')).toBe(true);
362
+ expect(Object.keys(plugin.moduleStateSnapshot()).sort()).toEqual([
363
+ 'visual.co_movement',
364
+ 'visual.follow',
365
+ 'visual.motion',
366
+ 'visual.route',
367
+ 'visual.spatial',
368
+ 'visual.stop',
369
+ 'visual.visibility',
370
+ ]);
371
+ }, 30_000);
372
+
373
+ it('cuts on a tick gap without inventing movement across the gap', async () => {
374
+ const plugin = new ClawclawPerceptionPlugin({
375
+ modules: ['visual.motion'],
376
+ });
377
+ await plugin.inspectFrame(stored(1, 1, stateAt(1, 900)));
378
+ const inspection = await plugin.inspectFrame(stored(2, 10, stateAt(10, 1_000)));
379
+
380
+ expect(inspection.visual).toMatchObject({ tickDelta: 9, continuousFromPrevious: false });
381
+ expect(inspection.proposals).toEqual([]);
382
+ expect((await plugin.flushForEventsQuery()).events ?? []).toEqual([]);
383
+ });
384
+
385
+ it('replaces the latest motion sample for a same-tick State revision', async () => {
386
+ const plugin = pluginFor('visual.motion');
387
+ await plugin.inspectFrame(stored(1, 10, stateAt(10, 900)));
388
+ const revision = await plugin.inspectFrame(stored(2, 10, stateAt(10, 905)));
389
+
390
+ expect(revision.visual).toMatchObject({
391
+ frameSeq: 2,
392
+ tick: 10,
393
+ tickDelta: 0,
394
+ continuousFromPrevious: true,
395
+ });
396
+ expect(plugin.moduleStateSnapshot()).toMatchObject({
397
+ 'visual.motion': {
398
+ tracks: expect.arrayContaining([expect.objectContaining({ point_count: 1 })]),
399
+ },
400
+ });
401
+ });
402
+
403
+ it('finalizes visibility absence on the next distinct tick and invalidates relations', async () => {
404
+ const plugin = new ClawclawPerceptionPlugin({
405
+ modules: ['visual.co_movement', 'visual.visibility'],
406
+ });
407
+ const emitted = [];
408
+ for (let tick = 1; tick <= 13; tick += 1) {
409
+ emitted.push(...(await plugin.inspectFrame(stored(
410
+ tick,
411
+ tick,
412
+ stateAt(tick, 900 + tick * 5, 840 + tick * 5),
413
+ ))).proposals);
414
+ }
415
+ expect(emitted.map((proposal) => proposal.type)).toContain(
416
+ 'visual.players_moving_together',
417
+ );
418
+
419
+ const revision = await plugin.inspectFrame(stored(14, 13, stateAt(13, 965)));
420
+
421
+ expect(revision.visual).toMatchObject({ tick: 13, tickDelta: 0 });
422
+ expect(revision.proposals).toEqual([]);
423
+
424
+ const finalized = await plugin.inspectFrame(stored(15, 14, stateAt(14, 970)));
425
+ expect(finalized.proposals.map((proposal) => proposal.type)).toContain('visual.player_left');
426
+ expect(plugin.moduleStateSnapshot()).toMatchObject({
427
+ 'visual.co_movement': {
428
+ pairs: [],
429
+ },
430
+ });
431
+ });
432
+
433
+ it('keeps each module private state across updates', async () => {
434
+ const plugin = pluginFor('visual.route');
435
+ for (let tick = 1; tick <= 8; tick += 1) {
436
+ const x = tick === 1 ? 900 : 910;
437
+ await plugin.inspectFrame(stored(tick, tick, stateAt(tick, x)));
438
+ }
439
+ expect(plugin.moduleStateSnapshot()).toMatchObject({
440
+ 'visual.route': {
441
+ tracks: expect.arrayContaining([
442
+ expect.objectContaining({ player_id: 'seat:7', start_tick: 7, path_length_px: 0 }),
443
+ ]),
444
+ },
445
+ });
446
+ });
447
+
448
+ it('soft-cuts ongoing movement on ccl events without overlapping the next slice', async () => {
449
+ const plugin = pluginFor('visual.motion');
450
+ for (let tick = 1; tick <= 5; tick += 1) {
451
+ await plugin.inspectFrame(stored(tick, tick, stateAt(tick, 900 + (tick - 1) * 6)));
452
+ }
453
+ const first = (await plugin.flushForEventsQuery()).events ?? [];
454
+ expect(first).toMatchObject([{
455
+ type: 'visual.player_moved',
456
+ payload: { actors: [7], status: 'ongoing', from_tick: 1, to_tick: 4 },
457
+ }]);
458
+ expect((await plugin.flushForEventsQuery()).events ?? []).toEqual([]);
459
+
460
+ for (let tick = 6; tick <= 9; tick += 1) {
461
+ await plugin.inspectFrame(stored(tick, tick, stateAt(tick, 900 + (tick - 1) * 6)));
462
+ }
463
+ expect((await plugin.flushForEventsQuery()).events ?? []).toMatchObject([{
464
+ payload: { actors: [7], status: 'ongoing', from_tick: 5, to_tick: 8 },
465
+ }]);
466
+ });
467
+
468
+ it('hard-cuts the previous phase before the meeting frame enters module history', async () => {
469
+ const plugin = pluginFor('visual.motion');
470
+ for (let tick = 1; tick <= 5; tick += 1) {
471
+ await plugin.inspectFrame(stored(tick, tick, stateAt(tick, 900 + (tick - 1) * 5)));
472
+ }
473
+ const meeting = stored(6, 6, { ...stateAt(6, 925), phase: 'meeting' });
474
+ const result = await plugin.inspectFrame(meeting);
475
+
476
+ expect(result.proposals).toMatchObject([{
477
+ type: 'visual.player_moved',
478
+ payload: { from_tick: 1, to_tick: 5 },
479
+ }]);
480
+ expect(result.proposals[0].payload).not.toHaveProperty('status');
481
+ expect(result.visual?.continuousFromPrevious).toBe(false);
482
+ expect(result.visual?.phase).toBe('meeting');
483
+ });
484
+
485
+ it('lets the module enforce its own maximum open-slice length', async () => {
486
+ const plugin = pluginFor('visual.motion');
487
+ const emitted = [];
488
+ for (let tick = 1; tick <= 22; tick += 1) {
489
+ const result = await plugin.inspectFrame(stored(tick, tick, stateAt(tick, 900 + (tick - 1) * 5)));
490
+ emitted.push(...result.proposals);
491
+ }
492
+ expect(emitted).toEqual([expect.objectContaining({
493
+ type: 'visual.player_moved',
494
+ payload: expect.objectContaining({
495
+ status: 'ongoing',
496
+ from_tick: 1,
497
+ to_tick: 19,
498
+ }),
499
+ })]);
500
+ });
501
+
502
+ it('flushes on the Source events-query boundary but ignores unrelated control input', async () => {
503
+ const plugin = pluginFor('visual.motion');
504
+ for (let tick = 1; tick <= 5; tick += 1) {
505
+ await updatePlugin(plugin, epochInput(stored(tick, tick, stateAt(tick, 900 + (tick - 1) * 6))));
506
+ }
507
+ const controlFrame = stored(6, 5, {
508
+ schema: 'clawclaw.runtime-state.v1',
509
+ stage: 'game',
510
+ connection: 'connected',
511
+ cause: 'control',
512
+ control: { type: 'strategy_parameters_updated' },
513
+ game_snapshot: { status: 'not_updated' },
514
+ });
515
+ expect(await updatePlugin(plugin, epochInput(controlFrame))).toMatchObject({
516
+ outcome: 'noop',
517
+ reason: 'game_snapshot:not_updated',
518
+ });
519
+
520
+ const queryFrame = stored(7, 5, {
521
+ schema: 'clawclaw.runtime-state.v1',
522
+ stage: 'game',
523
+ connection: 'connected',
524
+ cause: 'agent_events_query',
525
+ control: { type: 'events_query', request_id: 'query-1' },
526
+ game_snapshot: { status: 'not_updated' },
527
+ });
528
+ expect(await updatePlugin(plugin, epochInput(queryFrame))).toMatchObject({
529
+ outcome: 'processed',
530
+ reason: 'events_requested',
531
+ events: [expect.objectContaining({ type: 'visual.player_moved' })],
532
+ });
533
+ });
534
+
535
+ it('runs official motion analysis in a warm Worker pool and changes state only in ordered commit', async () => {
536
+ const plugin = pluginFor('visual.motion');
537
+ expect((plugin as any).modules[0].runner).toBeInstanceOf(LocalPerceptionModuleRunner);
538
+ const scope = stored(1, 1, {}).scope;
539
+ const context = pluginContext(plugin, scope);
540
+ const journal = journals.get(plugin)!;
541
+ const first = journal.appendStateFrame(stored(1, 1, stateAt(1, 900))).frame;
542
+ const second = journal.appendStateFrame(stored(2, 2, stateAt(2, 906))).frame;
543
+ const firstInput = epochInput(first);
544
+ const secondInput = epochInput(second);
545
+ await plugin.startForReplay();
546
+ expect((plugin as any).analysisPool.snapshot()).toMatchObject({
547
+ state: 'running',
548
+ minWorkers: 2,
549
+ maxWorkers: 10,
550
+ workerCount: 2,
551
+ idleWorkerCount: 2,
552
+ startedWorkerCount: 2,
553
+ });
554
+ const [firstComputation, secondComputation] = await Promise.all([
555
+ plugin.update(firstInput, context),
556
+ plugin.update(secondInput, context),
557
+ ]);
558
+
559
+ expect(firstComputation).toMatchObject({
560
+ outcome: 'processed',
561
+ proposal: { schema: 'clawclaw.perception-computation.v1' },
562
+ });
563
+ expect(plugin.moduleStateSnapshot()).toMatchObject({
564
+ 'visual.motion': { latest_tick: null, tracks: [] },
565
+ });
566
+ await plugin.commit(firstInput, firstComputation, context);
567
+ expect(plugin.moduleStateSnapshot()).toMatchObject({
568
+ 'visual.motion': { latest_tick: 1 },
569
+ });
570
+ await plugin.commit(secondInput, secondComputation, context);
571
+ expect(plugin.moduleStateSnapshot()).toMatchObject({
572
+ 'visual.motion': { latest_tick: 2 },
573
+ });
574
+ });
575
+
576
+ it('lets frame N+1 analyze immutable frame N before frame N commits', async () => {
577
+ const root = mkdtempSync(join(tmpdir(), 'ccl-perception-lookback-'));
578
+ const perceptions = join(root, 'user-data', 'perceptions');
579
+ mkdirSync(perceptions, { recursive: true });
580
+ writeFileSync(join(perceptions, 'lookback.ts'), `
581
+ import { ClawclawParallelPerception } from '@myclaw163/clawclaw-cli/perception-plugin';
582
+ export default class Lookback extends ClawclawParallelPerception {
583
+ static manifest = {
584
+ id: 'visual.lookback', name: 'Lookback', description: 'Checks immutable lookback.',
585
+ subjectScope: 'others', produces: ['visual.lookback'], execution: 'parallel_analysis',
586
+ };
587
+ committed = 0;
588
+ async analyze(input) {
589
+ await new Promise((resolve) => setTimeout(resolve, input.frame.frameSeq === 1 ? 100 : 5));
590
+ return {
591
+ frame_seq: input.frame.frameSeq,
592
+ history_frame_seqs: input.history.map((frame) => frame.frameSeq),
593
+ tick_delta: input.frame.tickDelta,
594
+ continuous: input.frame.continuousFromPrevious,
595
+ };
596
+ }
597
+ commit(frame, analysis) {
598
+ this.committed += 1;
599
+ return [{
600
+ type: 'visual.lookback', dedupeKey: 'lookback:' + frame.frameSeq,
601
+ payload: { ...analysis, committed: this.committed },
602
+ }];
603
+ }
604
+ reset() { this.committed = 0; }
605
+ debugSnapshot() { return { committed: this.committed }; }
606
+ }
607
+ `, 'utf8');
608
+ vi.stubEnv('CLAWCLAW_WORKSPACE_DIR', root);
609
+ const plugin = new ClawclawPerceptionPlugin({ modules: ['visual.lookback'] });
610
+ expect(plugin.maxInFlight).toBe(10);
611
+ const oneFrameWindow = new ClawclawPerceptionPlugin({
612
+ modules: ['visual.lookback'],
613
+ maxBackfillVisualFrames: 1,
614
+ });
615
+ expect(oneFrameWindow.maxInFlight).toBe(1);
616
+ expect(oneFrameWindow.catchUp).toBe('latest_only');
617
+ const firstStored = stored(1, 1, stateAt(1, 900));
618
+ const context = pluginContext(plugin, firstStored.scope);
619
+ const journal = journals.get(plugin)!;
620
+ const first = journal.appendStateFrame(firstStored).frame;
621
+ const second = journal.appendStateFrame(stored(2, 2, stateAt(2, 906))).frame;
622
+ const firstInput = epochInput(first);
623
+ const secondInput = epochInput(second);
624
+
625
+ try {
626
+ await plugin.startForReplay();
627
+ const firstWork = plugin.update(firstInput, context);
628
+ const secondWork = plugin.update(secondInput, context);
629
+ const [firstComputation, secondComputation] = await Promise.all([firstWork, secondWork]);
630
+ expect(secondComputation.proposal).toMatchObject({
631
+ analyses: [expect.objectContaining({
632
+ outcome: 'fulfilled',
633
+ analysis: {
634
+ frame_seq: 2,
635
+ history_frame_seqs: [1],
636
+ tick_delta: 1,
637
+ continuous: true,
638
+ },
639
+ })],
640
+ });
641
+ expect(plugin.moduleStateSnapshot()).toEqual({ 'visual.lookback': { committed: 0 } });
642
+
643
+ await plugin.commit(firstInput, firstComputation, context);
644
+ const committed = await plugin.commit(secondInput, secondComputation, context);
645
+ expect(committed.events).toEqual([
646
+ expect.objectContaining({ payload: expect.objectContaining({ committed: 2 }) }),
647
+ ]);
648
+
649
+ journal.appendStateFrame(stored(3, 3, stateAt(3, 912)));
650
+ const fourth = journal.appendStateFrame(stored(4, 4, stateAt(4, 918))).frame;
651
+ const fourthInput = epochInput(fourth);
652
+ const fourthComputation = await plugin.update(fourthInput, context);
653
+ expect(fourthComputation.proposal).toMatchObject({
654
+ analyses: [expect.objectContaining({
655
+ analysis: expect.objectContaining({ history_frame_seqs: [1, 2, 3] }),
656
+ })],
657
+ });
658
+ const fifth = journal.appendStateFrame(stored(5, 5, stateAt(5, 924))).frame;
659
+ const fifthInput = epochInput(fifth);
660
+ // This result is already complete before frame 4 establishes the gap
661
+ // boundary, so only a generation barrier can keep it off the reset reducer.
662
+ const fifthComputation = await plugin.update(fifthInput, context);
663
+ const gapCommit = await plugin.commit(fourthInput, fourthComputation, context);
664
+ expect(gapCommit.events ?? []).toEqual([]);
665
+ expect(plugin.moduleStateSnapshot()).toEqual({ 'visual.lookback': { committed: 0 } });
666
+ expect((await plugin.commit(fifthInput, fifthComputation, context)).events ?? []).toEqual([]);
667
+ expect(plugin.moduleStateSnapshot()).toEqual({ 'visual.lookback': { committed: 0 } });
668
+
669
+ const sixth = journal.appendStateFrame(stored(6, 6, stateAt(6, 930))).frame;
670
+ const sixthInput = epochInput(sixth);
671
+ const sixthComputation = await plugin.update(sixthInput, context);
672
+ const sixthCommit = await plugin.commit(sixthInput, sixthComputation, context);
673
+ expect(sixthCommit.events ?? []).toEqual([]);
674
+ expect(plugin.moduleStateSnapshot()).toEqual({ 'visual.lookback': { committed: 1 } });
675
+
676
+ const seventh = journal.appendStateFrame(stored(7, 7, stateAt(7, 936))).frame;
677
+ const seventhInput = epochInput(seventh);
678
+ const seventhCommit = await plugin.commit(
679
+ seventhInput,
680
+ await plugin.update(seventhInput, context),
681
+ context,
682
+ );
683
+ expect(seventhCommit.events).toEqual([
684
+ expect.objectContaining({ payload: expect.objectContaining({
685
+ frame_seq: 7,
686
+ history_frame_seqs: [4, 5, 6],
687
+ committed: 2,
688
+ }) }),
689
+ ]);
690
+ } finally {
691
+ await plugin.stopForReplay();
692
+ vi.unstubAllEnvs();
693
+ rmSync(root, { recursive: true, force: true });
694
+ }
695
+ }, 20_000);
696
+
697
+ it('invalidates already-computed later analyses after a module analyze failure', async () => {
698
+ const root = mkdtempSync(join(tmpdir(), 'ccl-perception-generation-'));
699
+ const perceptions = join(root, 'user-data', 'perceptions');
700
+ mkdirSync(perceptions, { recursive: true });
701
+ writeFileSync(join(perceptions, 'generation.ts'), `
702
+ import { ClawclawParallelPerception } from '@myclaw163/clawclaw-cli/perception-plugin';
703
+ export default class Generation extends ClawclawParallelPerception {
704
+ static manifest = {
705
+ id: 'visual.generation', name: 'Generation', description: 'Checks failure barriers.',
706
+ subjectScope: 'others', produces: ['visual.generation'], execution: 'parallel_analysis',
707
+ };
708
+ async analyze(input) {
709
+ if (input.frame.frameSeq === 1) throw new Error('expected_analysis_failure');
710
+ return {
711
+ frame_seq: input.frame.frameSeq,
712
+ history_frame_seqs: input.history.map((frame) => frame.frameSeq),
713
+ gap_before: input.gapBefore,
714
+ };
715
+ }
716
+ commit(frame, analysis) {
717
+ return [{
718
+ type: 'visual.generation', dedupeKey: 'generation:' + frame.frameSeq,
719
+ payload: analysis,
720
+ }];
721
+ }
722
+ }
723
+ `, 'utf8');
724
+ writeFileSync(join(perceptions, 'healthy.ts'), `
725
+ import { ClawclawParallelPerception } from '@myclaw163/clawclaw-cli/perception-plugin';
726
+ export default class Healthy extends ClawclawParallelPerception {
727
+ static manifest = {
728
+ id: 'visual.healthy', name: 'Healthy', description: 'Stays independent of peer failures.',
729
+ subjectScope: 'others', produces: ['visual.healthy'], execution: 'parallel_analysis',
730
+ };
731
+ analyze(input) { return { frame_seq: input.frame.frameSeq }; }
732
+ commit(frame, analysis) {
733
+ return [{
734
+ type: 'visual.healthy', dedupeKey: 'healthy:' + frame.frameSeq, payload: analysis,
735
+ }];
736
+ }
737
+ }
738
+ `, 'utf8');
739
+ vi.stubEnv('CLAWCLAW_WORKSPACE_DIR', root);
740
+ const plugin = new ClawclawPerceptionPlugin({
741
+ modules: ['visual.generation', 'visual.healthy'],
742
+ });
743
+ const firstStored = stored(1, 1, stateAt(1, 900));
744
+ const context = pluginContext(plugin, firstStored.scope);
745
+ const journal = journals.get(plugin)!;
746
+ const first = journal.appendStateFrame(firstStored).frame;
747
+ const second = journal.appendStateFrame(stored(2, 2, stateAt(2, 906))).frame;
748
+ const firstInput = epochInput(first);
749
+ const secondInput = epochInput(second);
750
+
751
+ try {
752
+ await plugin.startForReplay();
753
+ const [firstComputation, secondComputation] = await Promise.all([
754
+ plugin.update(firstInput, context),
755
+ plugin.update(secondInput, context),
756
+ ]);
757
+ expect(firstComputation.proposal).toMatchObject({
758
+ analyses: expect.arrayContaining([expect.objectContaining({
759
+ moduleId: 'visual.generation', generation: 0, outcome: 'rejected',
760
+ })]),
761
+ });
762
+ expect(secondComputation.proposal).toMatchObject({
763
+ analyses: expect.arrayContaining([expect.objectContaining({
764
+ moduleId: 'visual.generation', generation: 0, outcome: 'fulfilled',
765
+ })]),
766
+ });
767
+
768
+ expect((await plugin.commit(firstInput, firstComputation, context)).events).toEqual([
769
+ expect.objectContaining({ type: 'visual.healthy' }),
770
+ ]);
771
+ expect((await plugin.commit(secondInput, secondComputation, context)).events).toEqual([
772
+ expect.objectContaining({ type: 'visual.healthy' }),
773
+ ]);
774
+
775
+ const third = journal.appendStateFrame(stored(3, 3, stateAt(3, 912))).frame;
776
+ const thirdInput = epochInput(third);
777
+ const thirdComputation = await plugin.update(thirdInput, context);
778
+ expect(thirdComputation.proposal).toMatchObject({
779
+ analyses: expect.arrayContaining([expect.objectContaining({
780
+ moduleId: 'visual.generation',
781
+ generation: 1,
782
+ analysis: {
783
+ frame_seq: 3,
784
+ history_frame_seqs: [2],
785
+ gap_before: true,
786
+ },
787
+ })]),
788
+ });
789
+ expect((await plugin.commit(thirdInput, thirdComputation, context)).events).toEqual([
790
+ expect.objectContaining({ type: 'visual.healthy' }),
791
+ ]);
792
+
793
+ const fourth = journal.appendStateFrame(stored(4, 4, stateAt(4, 918))).frame;
794
+ const fourthInput = epochInput(fourth);
795
+ const fourthComputation = await plugin.update(fourthInput, context);
796
+ expect((await plugin.commit(fourthInput, fourthComputation, context)).events)
797
+ .toEqual(expect.arrayContaining([
798
+ expect.objectContaining({
799
+ type: 'visual.generation',
800
+ payload: expect.objectContaining({ history_frame_seqs: [2, 3] }),
801
+ }),
802
+ expect.objectContaining({ type: 'visual.healthy' }),
803
+ ]));
804
+ } finally {
805
+ await plugin.stopForReplay();
806
+ vi.unstubAllEnvs();
807
+ rmSync(root, { recursive: true, force: true });
808
+ }
809
+ }, 20_000);
810
+
811
+ it('rebaselines after stale successors of a current-only hard boundary', async () => {
812
+ const root = mkdtempSync(join(tmpdir(), 'ccl-perception-boundary-successors-'));
813
+ const perceptions = join(root, 'user-data', 'perceptions');
814
+ mkdirSync(perceptions, { recursive: true });
815
+ writeFileSync(join(perceptions, 'boundary-successors.ts'), `
816
+ import { ClawclawParallelPerception } from '@myclaw163/clawclaw-cli/perception-plugin';
817
+ export default class BoundarySuccessors extends ClawclawParallelPerception {
818
+ static manifest = {
819
+ id: 'visual.boundary_successors', name: 'Boundary successors',
820
+ description: 'Rejects a bridge across discarded reducer frames.',
821
+ subjectScope: 'others', produces: ['visual.boundary_successors'],
822
+ execution: 'parallel_analysis', boundaryBaseline: 'current_only',
823
+ };
824
+ lastFrameSeq = null;
825
+ analyze(input) {
826
+ return { previous_frame_seq: input.history.at(-1)?.frameSeq ?? null };
827
+ }
828
+ commit(frame, analysis) {
829
+ const bridged = this.lastFrameSeq !== null
830
+ && analysis.previous_frame_seq !== this.lastFrameSeq;
831
+ this.lastFrameSeq = frame.frameSeq;
832
+ return bridged ? [{
833
+ type: 'visual.boundary_successors',
834
+ dedupeKey: 'bridge:' + frame.frameSeq,
835
+ payload: {
836
+ reducer_previous_frame_seq: this.lastFrameSeq,
837
+ analysis_previous_frame_seq: analysis.previous_frame_seq,
838
+ },
839
+ }] : [];
840
+ }
841
+ reset() { this.lastFrameSeq = null; }
842
+ debugSnapshot() { return { last_frame_seq: this.lastFrameSeq }; }
843
+ }
844
+ `, 'utf8');
845
+ vi.stubEnv('CLAWCLAW_WORKSPACE_DIR', root);
846
+ const plugin = new ClawclawPerceptionPlugin({ modules: ['visual.boundary_successors'] });
847
+ const firstStored = stored(1, 1, stateAt(1, 900));
848
+ const context = pluginContext(plugin, firstStored.scope);
849
+ const journal = journals.get(plugin)!;
850
+
851
+ try {
852
+ await plugin.startForReplay();
853
+ const first = journal.appendStateFrame(firstStored).frame;
854
+ const firstInput = epochInput(first);
855
+ expect((await plugin.commit(
856
+ firstInput,
857
+ await plugin.update(firstInput, context),
858
+ context,
859
+ )).events ?? []).toEqual([]);
860
+
861
+ journal.appendStateFrame(stored(2, 2, stateAt(2, 906)));
862
+ journal.appendStateFrame(stored(3, 3, stateAt(3, 912)));
863
+ const fourth = journal.appendStateFrame(stored(4, 4, stateAt(4, 918))).frame;
864
+ const fifth = journal.appendStateFrame(stored(5, 5, stateAt(5, 924))).frame;
865
+ const sixth = journal.appendStateFrame(stored(6, 6, stateAt(6, 930))).frame;
866
+ const fourthInput = epochInput(fourth);
867
+ const fifthInput = epochInput(fifth);
868
+ const sixthInput = epochInput(sixth);
869
+ const [fourthComputation, fifthComputation, sixthComputation] = await Promise.all([
870
+ plugin.update(fourthInput, context),
871
+ plugin.update(fifthInput, context),
872
+ plugin.update(sixthInput, context),
873
+ ]);
874
+
875
+ expect((await plugin.commit(fourthInput, fourthComputation, context)).events ?? [])
876
+ .toEqual([]);
877
+ const seventh = journal.appendStateFrame(stored(7, 7, stateAt(7, 936))).frame;
878
+ const seventhInput = epochInput(seventh);
879
+ const seventhComputation = await plugin.update(seventhInput, context);
880
+
881
+ expect((await plugin.commit(fifthInput, fifthComputation, context)).events ?? [])
882
+ .toEqual([]);
883
+ expect((await plugin.commit(sixthInput, sixthComputation, context)).events ?? [])
884
+ .toEqual([]);
885
+ expect((await plugin.commit(seventhInput, seventhComputation, context)).events ?? [])
886
+ .toEqual([]);
887
+ expect(plugin.moduleStateSnapshot()).toEqual({
888
+ 'visual.boundary_successors': { last_frame_seq: 7 },
889
+ });
890
+
891
+ const eighth = journal.appendStateFrame(stored(8, 8, stateAt(8, 942))).frame;
892
+ const eighthInput = epochInput(eighth);
893
+ expect((await plugin.commit(
894
+ eighthInput,
895
+ await plugin.update(eighthInput, context),
896
+ context,
897
+ )).events ?? []).toEqual([]);
898
+ } finally {
899
+ await plugin.stopForReplay();
900
+ vi.unstubAllEnvs();
901
+ rmSync(root, { recursive: true, force: true });
902
+ }
903
+ }, 20_000);
904
+
905
+ it('recovers each parallel module from its persisted failure floor', async () => {
906
+ const root = mkdtempSync(join(tmpdir(), 'ccl-perception-recovery-floor-'));
907
+ const perceptions = join(root, 'user-data', 'perceptions');
908
+ mkdirSync(perceptions, { recursive: true });
909
+ const transientPath = join(perceptions, 'transient.ts');
910
+ const transientSource = (fail: boolean) => `
911
+ import { ClawclawParallelPerception } from '@myclaw163/clawclaw-cli/perception-plugin';
912
+ export default class Transient extends ClawclawParallelPerception {
913
+ static manifest = {
914
+ id: 'visual.transient', name: 'Transient', description: 'Fails one live analysis.',
915
+ subjectScope: 'others', produces: ['visual.transient'], execution: 'parallel_analysis',
916
+ };
917
+ frames = [];
918
+ analyze(input) {
919
+ if (${fail ? 'input.frame.frameSeq === 2' : 'false'}) {
920
+ throw new Error('transient_analysis_failure');
921
+ }
922
+ return {
923
+ frame_seq: input.frame.frameSeq,
924
+ history_frame_seqs: input.history.map((frame) => frame.frameSeq),
925
+ };
926
+ }
927
+ commit(_frame, analysis) { this.frames.push(analysis); }
928
+ reset() { this.frames = []; }
929
+ debugSnapshot() { return { frames: this.frames }; }
930
+ }
931
+ `;
932
+ writeFileSync(transientPath, transientSource(true), 'utf8');
933
+ writeFileSync(join(perceptions, 'recovery-healthy.ts'), `
934
+ import { ClawclawParallelPerception } from '@myclaw163/clawclaw-cli/perception-plugin';
935
+ export default class RecoveryHealthy extends ClawclawParallelPerception {
936
+ static manifest = {
937
+ id: 'visual.recovery_healthy', name: 'Recovery healthy',
938
+ description: 'Keeps its original replay slice.',
939
+ subjectScope: 'others', produces: ['visual.recovery_healthy'], execution: 'parallel_analysis',
940
+ };
941
+ frames = [];
942
+ analyze(input) {
943
+ return {
944
+ frame_seq: input.frame.frameSeq,
945
+ history_frame_seqs: input.history.map((frame) => frame.frameSeq),
946
+ };
947
+ }
948
+ commit(_frame, analysis) { this.frames.push(analysis); }
949
+ reset() { this.frames = []; }
950
+ debugSnapshot() { return { frames: this.frames }; }
951
+ }
952
+ `, 'utf8');
953
+ vi.stubEnv('CLAWCLAW_WORKSPACE_DIR', root);
954
+ const modules = ['visual.recovery_healthy', 'visual.transient'];
955
+ const plugin = new ClawclawPerceptionPlugin({ modules });
956
+ let recovered: ClawclawPerceptionPlugin | undefined;
957
+ const firstStored = stored(1, 1, stateAt(1, 900));
958
+ const context = pluginContext(plugin, firstStored.scope);
959
+ const journal = journals.get(plugin)!;
960
+
961
+ try {
962
+ await plugin.startForReplay();
963
+ const first = journal.appendStateFrame(firstStored).frame;
964
+ const firstInput = epochInput(first);
965
+ await plugin.commit(firstInput, await plugin.update(firstInput, context), context);
966
+
967
+ const second = journal.appendStateFrame(stored(2, 2, stateAt(2, 906))).frame;
968
+ const secondInput = epochInput(second);
969
+ const failed = await plugin.commit(
970
+ secondInput,
971
+ await plugin.update(secondInput, context),
972
+ context,
973
+ );
974
+ expect(failed.checkpoint).toMatchObject({
975
+ schema: 'clawclaw.perception-checkpoint.v1',
976
+ replayFromFrameSeq: 1,
977
+ parallelModuleHistoryFloors: { 'visual.transient': 3 },
978
+ parallelModuleReducerReplayStarts: { 'visual.transient': null },
979
+ });
980
+ expect(plugin.moduleStateSnapshot()).toEqual({
981
+ 'visual.recovery_healthy': {
982
+ frames: [
983
+ expect.objectContaining({ frame_seq: 1 }),
984
+ expect.objectContaining({ frame_seq: 2 }),
985
+ ],
986
+ },
987
+ 'visual.transient': { frames: [] },
988
+ });
989
+
990
+ const third = journal.appendStateFrame(stored(3, 3, stateAt(3, 912))).frame;
991
+ const thirdInput = epochInput(third);
992
+ await plugin.commit(thirdInput, await plugin.update(thirdInput, context), context);
993
+ const liveSnapshot = plugin.moduleStateSnapshot();
994
+ expect(liveSnapshot).toMatchObject({
995
+ 'visual.recovery_healthy': { frames: [{}, {}, {}] },
996
+ 'visual.transient': {
997
+ frames: [{ frame_seq: 3, history_frame_seqs: [] }],
998
+ },
999
+ });
1000
+ await plugin.stopForReplay();
1001
+
1002
+ writeFileSync(transientPath, transientSource(false), 'utf8');
1003
+ recovered = new ClawclawPerceptionPlugin({ modules });
1004
+ journals.set(recovered, journal);
1005
+ const recoveryContext = pluginContext(recovered, first.scope, 2, failed.checkpoint);
1006
+ await recovered.start(recoveryContext);
1007
+ await recovered.recover(recoveryContext);
1008
+ expect(recovered.moduleStateSnapshot()).toEqual({
1009
+ 'visual.recovery_healthy': {
1010
+ frames: [
1011
+ expect.objectContaining({ frame_seq: 1 }),
1012
+ expect.objectContaining({ frame_seq: 2 }),
1013
+ ],
1014
+ },
1015
+ 'visual.transient': { frames: [] },
1016
+ });
1017
+
1018
+ await recovered.commit(
1019
+ thirdInput,
1020
+ await recovered.update(thirdInput, recoveryContext),
1021
+ recoveryContext,
1022
+ );
1023
+ expect(recovered.moduleStateSnapshot()).toEqual(liveSnapshot);
1024
+ } finally {
1025
+ await Promise.allSettled([
1026
+ plugin.stopForReplay(),
1027
+ ...(recovered ? [recovered.stopForReplay()] : []),
1028
+ ]);
1029
+ vi.unstubAllEnvs();
1030
+ rmSync(root, { recursive: true, force: true });
1031
+ }
1032
+ }, 30_000);
1033
+
1034
+ it('persists the reducer commit boundary across stale generations and hard gaps', async () => {
1035
+ const root = mkdtempSync(join(tmpdir(), 'ccl-perception-reducer-replay-'));
1036
+ const perceptions = join(root, 'user-data', 'perceptions');
1037
+ mkdirSync(perceptions, { recursive: true });
1038
+ const sourcePath = join(perceptions, 'replay-exact.ts');
1039
+ const source = (failFirst: boolean) => `
1040
+ import { ClawclawParallelPerception } from '@myclaw163/clawclaw-cli/perception-plugin';
1041
+ export default class ReplayExact extends ClawclawParallelPerception {
1042
+ static manifest = {
1043
+ id: 'visual.replay_exact', name: 'Replay exact',
1044
+ description: 'Records only frames that reached the reducer.',
1045
+ subjectScope: 'others', produces: ['visual.replay_exact'], execution: 'parallel_analysis',
1046
+ };
1047
+ frames = [];
1048
+ analyze(input) {
1049
+ if (${failFirst ? 'input.frame.frameSeq === 1' : 'false'}) {
1050
+ throw new Error('first_analysis_failed');
1051
+ }
1052
+ return { frame_seq: input.frame.frameSeq };
1053
+ }
1054
+ commit(frame) {
1055
+ this.frames.push(frame.frameSeq);
1056
+ return [{
1057
+ type: 'visual.replay_exact',
1058
+ dedupeKey: 'frame:' + frame.frameSeq,
1059
+ payload: { frame_seq: frame.frameSeq },
1060
+ }];
1061
+ }
1062
+ reset() { this.frames = []; }
1063
+ debugSnapshot() { return { frames: this.frames }; }
1064
+ }
1065
+ `;
1066
+ writeFileSync(sourcePath, source(true), 'utf8');
1067
+ vi.stubEnv('CLAWCLAW_WORKSPACE_DIR', root);
1068
+ const modules = ['visual.replay_exact'];
1069
+ const plugin = new ClawclawPerceptionPlugin({ modules });
1070
+ let failureRecovered: ClawclawPerceptionPlugin | undefined;
1071
+ let gapLive: ClawclawPerceptionPlugin | undefined;
1072
+ let gapBoundaryRecovered: ClawclawPerceptionPlugin | undefined;
1073
+ let gapRecovered: ClawclawPerceptionPlugin | undefined;
1074
+ const firstStored = stored(1, 1, stateAt(1, 900));
1075
+ const context = pluginContext(plugin, firstStored.scope);
1076
+ const journal = journals.get(plugin)!;
1077
+
1078
+ try {
1079
+ await plugin.startForReplay();
1080
+ const frames = Array.from({ length: 10 }, (_value, index) => (
1081
+ journal.appendStateFrame(stored(
1082
+ index + 1,
1083
+ index + 1,
1084
+ stateAt(index + 1, 900 + index * 6),
1085
+ )).frame
1086
+ ));
1087
+ const inputs = frames.map((value) => epochInput(value));
1088
+ const computations = await Promise.all(inputs.map((input) => plugin.update(input, context)));
1089
+ let checkpoint: unknown;
1090
+ for (let index = 0; index < inputs.length; index += 1) {
1091
+ checkpoint = (await plugin.commit(inputs[index]!, computations[index]!, context)).checkpoint;
1092
+ }
1093
+ expect(plugin.moduleStateSnapshot()).toEqual({ 'visual.replay_exact': { frames: [] } });
1094
+ expect(checkpoint).toMatchObject({
1095
+ parallelModuleHistoryFloors: { 'visual.replay_exact': 2 },
1096
+ parallelModuleReducerReplayStarts: { 'visual.replay_exact': null },
1097
+ parallelModuleBaselinePending: { 'visual.replay_exact': true },
1098
+ });
1099
+ await plugin.stopForReplay();
1100
+
1101
+ writeFileSync(sourcePath, source(false), 'utf8');
1102
+ failureRecovered = new ClawclawPerceptionPlugin({ modules });
1103
+ journals.set(failureRecovered, journal);
1104
+ const recoveryContext = pluginContext(failureRecovered, firstStored.scope, 10, checkpoint);
1105
+ await failureRecovered.start(recoveryContext);
1106
+ await failureRecovered.recover(recoveryContext);
1107
+ expect(failureRecovered.moduleStateSnapshot()).toEqual({
1108
+ 'visual.replay_exact': { frames: [] },
1109
+ });
1110
+
1111
+ const eleventh = journal.appendStateFrame(stored(11, 11, stateAt(11, 960))).frame;
1112
+ const eleventhInput = epochInput(eleventh);
1113
+ const afterRecovery = await failureRecovered.commit(
1114
+ eleventhInput,
1115
+ await failureRecovered.update(eleventhInput, recoveryContext),
1116
+ recoveryContext,
1117
+ );
1118
+ expect(failureRecovered.moduleStateSnapshot()).toEqual({
1119
+ 'visual.replay_exact': { frames: [11] },
1120
+ });
1121
+ expect(afterRecovery.checkpoint).toMatchObject({
1122
+ parallelModuleHistoryFloors: { 'visual.replay_exact': 2 },
1123
+ parallelModuleReducerReplayStarts: { 'visual.replay_exact': 11 },
1124
+ parallelModuleBaselinePending: { 'visual.replay_exact': false },
1125
+ });
1126
+ await failureRecovered.stopForReplay();
1127
+
1128
+ gapLive = new ClawclawPerceptionPlugin({ modules });
1129
+ const gapContext = pluginContext(gapLive, firstStored.scope);
1130
+ const gapJournal = journals.get(gapLive)!;
1131
+ await gapLive.startForReplay();
1132
+ const gapFirst = gapJournal.appendStateFrame(firstStored).frame;
1133
+ const gapFirstInput = epochInput(gapFirst);
1134
+ await gapLive.commit(
1135
+ gapFirstInput,
1136
+ await gapLive.update(gapFirstInput, gapContext),
1137
+ gapContext,
1138
+ );
1139
+ gapJournal.appendStateFrame(stored(2, 2, stateAt(2, 906)));
1140
+ gapJournal.appendStateFrame(stored(3, 3, stateAt(3, 912)));
1141
+ const gapFourth = gapJournal.appendStateFrame(stored(4, 4, stateAt(4, 918))).frame;
1142
+ const gapFourthInput = epochInput(gapFourth);
1143
+ const gapBoundaryResult = await gapLive.commit(
1144
+ gapFourthInput,
1145
+ await gapLive.update(gapFourthInput, gapContext),
1146
+ gapContext,
1147
+ );
1148
+ expect(gapLive.moduleStateSnapshot()).toEqual({
1149
+ 'visual.replay_exact': { frames: [] },
1150
+ });
1151
+ expect(gapBoundaryResult.checkpoint).toMatchObject({
1152
+ replayFromFrameSeq: 4,
1153
+ parallelModuleHistoryFloors: { 'visual.replay_exact': 4 },
1154
+ parallelModuleReducerReplayStarts: { 'visual.replay_exact': null },
1155
+ parallelModuleBaselinePending: { 'visual.replay_exact': true },
1156
+ });
1157
+
1158
+ gapBoundaryRecovered = new ClawclawPerceptionPlugin({ modules });
1159
+ journals.set(gapBoundaryRecovered, gapJournal);
1160
+ const gapBoundaryRecoveryContext = pluginContext(
1161
+ gapBoundaryRecovered,
1162
+ firstStored.scope,
1163
+ 4,
1164
+ gapBoundaryResult.checkpoint,
1165
+ );
1166
+ await gapBoundaryRecovered.start(gapBoundaryRecoveryContext);
1167
+ await gapBoundaryRecovered.recover(gapBoundaryRecoveryContext);
1168
+ expect(gapBoundaryRecovered.moduleStateSnapshot()).toEqual({
1169
+ 'visual.replay_exact': { frames: [] },
1170
+ });
1171
+
1172
+ const gapFifth = gapJournal.appendStateFrame(stored(5, 5, stateAt(5, 924))).frame;
1173
+ const gapFifthInput = epochInput(gapFifth);
1174
+ const liveFifthComputation = await gapLive.update(gapFifthInput, gapContext);
1175
+ const recoveredFifthComputation = await gapBoundaryRecovered.update(
1176
+ gapFifthInput,
1177
+ gapBoundaryRecoveryContext,
1178
+ );
1179
+ const gapResult = await gapLive.commit(
1180
+ gapFifthInput,
1181
+ liveFifthComputation,
1182
+ gapContext,
1183
+ );
1184
+ const recoveredGapResult = await gapBoundaryRecovered.commit(
1185
+ gapFifthInput,
1186
+ recoveredFifthComputation,
1187
+ gapBoundaryRecoveryContext,
1188
+ );
1189
+ expect(gapLive.moduleStateSnapshot()).toEqual({
1190
+ 'visual.replay_exact': { frames: [5] },
1191
+ });
1192
+ expect(gapBoundaryRecovered.moduleStateSnapshot()).toEqual(
1193
+ gapLive.moduleStateSnapshot(),
1194
+ );
1195
+ expect(recoveredGapResult.events).toEqual(gapResult.events);
1196
+ expect(gapResult.checkpoint).toMatchObject({
1197
+ replayFromFrameSeq: 4,
1198
+ parallelModuleHistoryFloors: { 'visual.replay_exact': 4 },
1199
+ parallelModuleReducerReplayStarts: { 'visual.replay_exact': 5 },
1200
+ parallelModuleBaselinePending: { 'visual.replay_exact': false },
1201
+ });
1202
+ await gapLive.stopForReplay();
1203
+ await gapBoundaryRecovered.stopForReplay();
1204
+
1205
+ gapRecovered = new ClawclawPerceptionPlugin({ modules });
1206
+ journals.set(gapRecovered, gapJournal);
1207
+ const gapRecoveryContext = pluginContext(
1208
+ gapRecovered,
1209
+ firstStored.scope,
1210
+ 5,
1211
+ gapResult.checkpoint,
1212
+ );
1213
+ await gapRecovered.start(gapRecoveryContext);
1214
+ await gapRecovered.recover(gapRecoveryContext);
1215
+ expect(gapRecovered.moduleStateSnapshot()).toEqual({
1216
+ 'visual.replay_exact': { frames: [5] },
1217
+ });
1218
+ } finally {
1219
+ await Promise.allSettled([
1220
+ plugin.stopForReplay(),
1221
+ ...(failureRecovered ? [failureRecovered.stopForReplay()] : []),
1222
+ ...(gapLive ? [gapLive.stopForReplay()] : []),
1223
+ ...(gapBoundaryRecovered ? [gapBoundaryRecovered.stopForReplay()] : []),
1224
+ ...(gapRecovered ? [gapRecovered.stopForReplay()] : []),
1225
+ ]);
1226
+ vi.unstubAllEnvs();
1227
+ rmSync(root, { recursive: true, force: true });
1228
+ }
1229
+ }, 30_000);
1230
+
1231
+ it('replaces a partially-mutated reducer and rejects its old-generation successors', async () => {
1232
+ const root = mkdtempSync(join(tmpdir(), 'ccl-perception-reducer-reset-'));
1233
+ const perceptions = join(root, 'user-data', 'perceptions');
1234
+ mkdirSync(perceptions, { recursive: true });
1235
+ writeFileSync(join(perceptions, 'reducer-reset.ts'), `
1236
+ import { ClawclawParallelPerception } from '@myclaw163/clawclaw-cli/perception-plugin';
1237
+ export default class ReducerReset extends ClawclawParallelPerception {
1238
+ static manifest = {
1239
+ id: 'visual.reducer_reset', name: 'Reducer reset', description: 'Checks dirty reducer reset.',
1240
+ subjectScope: 'others', produces: ['visual.reducer_reset'], execution: 'parallel_analysis',
1241
+ };
1242
+ mutations = 0;
1243
+ analyze(input) { return { frame_seq: input.frame.frameSeq }; }
1244
+ commit(frame, analysis) {
1245
+ this.mutations += 1;
1246
+ if (frame.frameSeq === 1) throw new Error('expected_commit_failure');
1247
+ return [{
1248
+ type: 'visual.reducer_reset', dedupeKey: 'reducer-reset:' + frame.frameSeq,
1249
+ payload: { ...analysis, mutations: this.mutations },
1250
+ }];
1251
+ }
1252
+ reset() {
1253
+ this.mutations = 100;
1254
+ throw new Error('expected_reset_failure');
1255
+ }
1256
+ debugSnapshot() { return { mutations: this.mutations }; }
1257
+ }
1258
+ `, 'utf8');
1259
+ vi.stubEnv('CLAWCLAW_WORKSPACE_DIR', root);
1260
+ const plugin = new ClawclawPerceptionPlugin({ modules: ['visual.reducer_reset'] });
1261
+ const firstStored = stored(1, 1, stateAt(1, 900));
1262
+ const context = pluginContext(plugin, firstStored.scope);
1263
+ const journal = journals.get(plugin)!;
1264
+ const first = journal.appendStateFrame(firstStored).frame;
1265
+ const second = journal.appendStateFrame(stored(2, 2, stateAt(2, 906))).frame;
1266
+ const firstInput = epochInput(first);
1267
+ const secondInput = epochInput(second);
1268
+
1269
+ try {
1270
+ await plugin.startForReplay();
1271
+ const [firstComputation, secondComputation] = await Promise.all([
1272
+ plugin.update(firstInput, context),
1273
+ plugin.update(secondInput, context),
1274
+ ]);
1275
+ expect((await plugin.commit(firstInput, firstComputation, context)).events ?? []).toEqual([]);
1276
+ expect((await plugin.commit(secondInput, secondComputation, context)).events ?? []).toEqual([]);
1277
+
1278
+ const third = journal.appendStateFrame(stored(3, 3, stateAt(3, 912))).frame;
1279
+ const thirdInput = epochInput(third);
1280
+ const thirdComputation = await plugin.update(thirdInput, context);
1281
+ expect((await plugin.commit(thirdInput, thirdComputation, context)).events ?? []).toEqual([]);
1282
+ expect(plugin.moduleStateSnapshot()).toEqual({ 'visual.reducer_reset': { mutations: 1 } });
1283
+
1284
+ const fourth = journal.appendStateFrame(stored(4, 4, stateAt(4, 918))).frame;
1285
+ const fourthInput = epochInput(fourth);
1286
+ const fourthComputation = await plugin.update(fourthInput, context);
1287
+ expect((await plugin.commit(fourthInput, fourthComputation, context)).events).toEqual([
1288
+ expect.objectContaining({
1289
+ type: 'visual.reducer_reset',
1290
+ payload: expect.objectContaining({ frame_seq: 4, mutations: 2 }),
1291
+ }),
1292
+ ]);
1293
+ expect(plugin.moduleStateSnapshot()).toEqual({ 'visual.reducer_reset': { mutations: 2 } });
1294
+ } finally {
1295
+ await plugin.stopForReplay();
1296
+ vi.unstubAllEnvs();
1297
+ rmSync(root, { recursive: true, force: true });
1298
+ }
1299
+ }, 20_000);
1300
+
1301
+ it('turns a skipped computation range into a hard trajectory boundary', async () => {
1302
+ const plugin = new ClawclawPerceptionPlugin({
1303
+ modules: ['visual.motion'],
1304
+ maxBackfillVisualFrames: 5,
1305
+ });
1306
+ const scope = stored(1, 1, {}).scope;
1307
+ const diagnostics: Array<{ name: string; attributes?: Readonly<Record<string, unknown>> }> = [];
1308
+ const context = pluginContext(
1309
+ plugin,
1310
+ scope,
1311
+ 0,
1312
+ undefined,
1313
+ (name, attributes) => diagnostics.push({ name, attributes }),
1314
+ );
1315
+ const journal = journals.get(plugin)!;
1316
+ await plugin.start(context);
1317
+ const first = journal.appendStateFrame(stored(1, 1, stateAt(1, 900))).frame;
1318
+ const firstInput = epochInput(first);
1319
+ const firstComputation = await plugin.update(firstInput, context);
1320
+ await plugin.commit(firstInput, firstComputation, context);
1321
+ let target = first;
1322
+ for (let tick = 1; tick <= 8; tick += 1) {
1323
+ if (tick === 1) continue;
1324
+ target = journal.appendStateFrame(
1325
+ stored(tick, tick, stateAt(tick, 900 + (tick - 1) * 5)),
1326
+ ).frame;
1327
+ }
1328
+
1329
+ const targetInput = epochInput(target);
1330
+ const targetComputation = await plugin.update(targetInput, context);
1331
+ const result = await plugin.commit(targetInput, targetComputation, context);
1332
+ expect(result.checkpoint).toEqual({
1333
+ schema: 'clawclaw.perception-checkpoint.v1',
1334
+ replayFromFrameSeq: 8,
1335
+ parallelModuleHistoryFloors: { 'visual.motion': 8 },
1336
+ parallelModuleReducerReplayStarts: { 'visual.motion': 8 },
1337
+ parallelModuleBaselinePending: { 'visual.motion': false },
1338
+ });
1339
+ expect(plugin.moduleStateSnapshot()).toMatchObject({
1340
+ 'visual.motion': {
1341
+ latest_tick: 8,
1342
+ tracks: expect.arrayContaining([expect.objectContaining({
1343
+ point_count: 1,
1344
+ from_tick: 8,
1345
+ to_tick: 8,
1346
+ })]),
1347
+ },
1348
+ });
1349
+ expect(diagnostics).toContainEqual(expect.objectContaining({
1350
+ name: 'perception.catchup_frames_dropped',
1351
+ attributes: expect.objectContaining({
1352
+ dropped_state_frame_count: 6,
1353
+ retained_from_frame_seq: 8,
1354
+ }),
1355
+ }));
1356
+
1357
+ const recovered = new ClawclawPerceptionPlugin({
1358
+ modules: ['visual.motion'],
1359
+ maxBackfillVisualFrames: 5,
1360
+ });
1361
+ journals.set(recovered, journal);
1362
+ const recoveryContext = pluginContext(recovered, scope, 8, result.checkpoint);
1363
+ await recovered.start(recoveryContext);
1364
+ await recovered.recover(recoveryContext);
1365
+ expect(recovered.moduleStateSnapshot()).toMatchObject({
1366
+ 'visual.motion': {
1367
+ latest_tick: 8,
1368
+ tracks: expect.arrayContaining([expect.objectContaining({
1369
+ point_count: 1,
1370
+ from_tick: 8,
1371
+ to_tick: 8,
1372
+ })]),
1373
+ },
1374
+ });
1375
+
1376
+ const ninth = journal.appendStateFrame(stored(9, 9, stateAt(9, 940))).frame;
1377
+ const ninthInput = epochInput(ninth);
1378
+ const [liveNinthComputation, recoveredNinthComputation] = await Promise.all([
1379
+ plugin.update(ninthInput, context),
1380
+ recovered.update(ninthInput, recoveryContext),
1381
+ ]);
1382
+ const [liveNinth, recoveredNinth] = await Promise.all([
1383
+ plugin.commit(ninthInput, liveNinthComputation, context),
1384
+ recovered.commit(ninthInput, recoveredNinthComputation, recoveryContext),
1385
+ ]);
1386
+ expect(recoveredNinth.events ?? []).toEqual(liveNinth.events ?? []);
1387
+ expect(recovered.moduleStateSnapshot()).toEqual(plugin.moduleStateSnapshot());
1388
+ expect(plugin.moduleStateSnapshot()).toMatchObject({
1389
+ 'visual.motion': {
1390
+ latest_tick: 9,
1391
+ tracks: expect.arrayContaining([
1392
+ expect.objectContaining({ from_tick: 8, to_tick: 9 }),
1393
+ ]),
1394
+ },
1395
+ });
1396
+ await Promise.all([plugin.stopForReplay(), recovered.stopForReplay()]);
1397
+ });
1398
+
1399
+ it('commits a query-cut Event with the aggregate Perception plugin id', async () => {
1400
+ const events = new MemoryEventRepository();
1401
+ const motion = pluginFor('visual.motion');
1402
+ const runtime = new Runtime({
1403
+ adapterId: 'clawclaw',
1404
+ accountId: 'account',
1405
+ eventCatalog: createClawclawEventCatalog({
1406
+ visualEventDelivery: { 'visual.player_moved': 'monitor_and_events' },
1407
+ }),
1408
+ eventRepository: events,
1409
+ stateHistoryRepository: new MemoryStateHistoryRepository(),
1410
+ runtimeEpochPlugins: [motion],
1411
+ initialSegment: { kind: 'game', identity: 'game-1' },
1412
+ });
1413
+ await runtime.start();
1414
+ const scope = runtime.scope();
1415
+
1416
+ for (let tick = 1; tick <= 5; tick += 1) {
1417
+ const accepted = await runtime.acceptInputBatch({
1418
+ scope,
1419
+ sourceId: 'clawclaw.game-ws',
1420
+ connectionId: 'game-ws-1',
1421
+ sourceKey: `game:${tick}`,
1422
+ sourceSeq: tick,
1423
+ domainTick: tick,
1424
+ state: {
1425
+ schema: 'clawclaw.runtime-state.v1',
1426
+ stage: 'game',
1427
+ transport: 'game_ws',
1428
+ connection: 'connected',
1429
+ cause: 'game_snapshot',
1430
+ game_snapshot: {
1431
+ status: 'fresh',
1432
+ state: { phase: 'wandering', ...stateAt(tick, 900 + (tick - 1) * 6) },
1433
+ },
1434
+ },
1435
+ events: [],
1436
+ completeness: 'complete',
1437
+ receivedAt: new Date(tick * 100).toISOString(),
1438
+ });
1439
+ await runtime.waitForEpochReadyView(accepted.epoch.epochSeq);
1440
+ }
1441
+
1442
+ const query = await runtime.acceptInputBatch({
1443
+ scope,
1444
+ sourceId: 'clawclaw.local-control',
1445
+ connectionId: 'game-ws-1',
1446
+ sourceKey: 'events-query:1',
1447
+ sourceSeq: 1,
1448
+ state: {
1449
+ schema: 'clawclaw.runtime-state.v1',
1450
+ stage: 'game',
1451
+ transport: 'game_ws',
1452
+ connection: 'connected',
1453
+ cause: 'agent_events_query',
1454
+ control: { type: 'events_query', request_id: 'query-1' },
1455
+ game_snapshot: { status: 'not_updated' },
1456
+ },
1457
+ events: [],
1458
+ completeness: 'complete',
1459
+ coalescing: 'forbidden',
1460
+ receivedAt: new Date(600).toISOString(),
1461
+ });
1462
+ await runtime.waitForEpochReadyView(query.epoch.epochSeq);
1463
+
1464
+ expect(events.listCommittedEvents({
1465
+ sessionId: scope.sessionId,
1466
+ segmentId: scope.segmentId,
1467
+ types: ['visual.player_moved'],
1468
+ })).toMatchObject([{
1469
+ epochSeq: query.epoch.epochSeq,
1470
+ producerPluginId: CLAWCLAW_PERCEPTION_PLUGIN_ID,
1471
+ deliveryClass: 'monitor_and_events',
1472
+ }]);
1473
+ await runtime.close();
1474
+ });
1475
+
1476
+ it('keeps same-batch follow and co-movement as independently typed canonical facts', async () => {
1477
+ const plugin = new ClawclawPerceptionPlugin({
1478
+ modules: ['visual.co_movement', 'visual.follow'],
1479
+ });
1480
+ const emitted = [];
1481
+ for (let tick = 1; tick <= 13; tick += 1) {
1482
+ const frame = stored(tick, tick, stateAt(tick, 900 + tick * 5, 840 + tick * 5));
1483
+ emitted.push(...(await plugin.inspectFrame(frame)).proposals);
1484
+ }
1485
+ expect(emitted).toContainEqual(expect.objectContaining({
1486
+ type: 'visual.players_moving_together',
1487
+ payload: expect.objectContaining({ actors: [7, 9] }),
1488
+ }));
1489
+ expect(emitted).toContainEqual(expect.objectContaining({
1490
+ type: 'visual.following',
1491
+ payload: expect.objectContaining({
1492
+ actors: [9, 7],
1493
+ }),
1494
+ }));
1495
+ });
1496
+
1497
+ it('rebuilds all module state from the aggregate plugin completion point', async () => {
1498
+ const journal = new MemoryStateHistoryRepository<unknown, Record<string, any>>();
1499
+ const scope = stored(1, 1, {}).scope;
1500
+ journal.openScope(scope);
1501
+ for (let tick = 1; tick <= 3; tick += 1) {
1502
+ journal.appendStateFrame(stored(tick, tick, stateAt(tick, 900 + tick * 5)));
1503
+ }
1504
+ const plugin = pluginFor('visual.motion');
1505
+ const context = {
1506
+ ...pluginContext(plugin, scope, 2),
1507
+ stateHistory: journal,
1508
+ };
1509
+ await plugin.start(context);
1510
+ await plugin.recover(context);
1511
+
1512
+ expect(plugin.moduleStateSnapshot()).toMatchObject({
1513
+ 'visual.motion': { latest_tick: 2 },
1514
+ });
1515
+ });
1516
+ });