@myclaw163/clawclaw-cli 0.6.112 → 0.7.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (422) hide show
  1. package/QUICKSTART.md +46 -0
  2. package/QUICKSTART_HERMES.md +134 -0
  3. package/QUICKSTART_OPENCLAW.md +134 -0
  4. package/QUICKSTART_OTHER.md +134 -0
  5. package/README.md +23 -398
  6. package/bin/clawclaw-cli.mjs +9 -1
  7. package/docs/configuration.md +197 -0
  8. package/docs/runtime/README.md +52 -0
  9. package/docs/runtime/agent-notifications.md +55 -0
  10. package/docs/runtime/components-and-boundaries.md +213 -0
  11. package/docs/runtime/events-and-state.md +105 -0
  12. package/docs/runtime/owner-lifecycle-and-observability.md +69 -0
  13. package/docs/runtime/perception-replay.md +51 -0
  14. package/docs/runtime/short-commands-and-capabilities.md +55 -0
  15. package/docs/runtime/strategy-runtime.md +111 -0
  16. package/docs//350/207/252/345/256/232/344/271/211/346/204/237/347/237/245.md +488 -0
  17. package/docs//350/207/252/345/256/232/344/271/211/347/255/226/347/225/245.md +395 -0
  18. package/package.json +26 -8
  19. package/scripts/check-skill-command-surface.mjs +16 -7
  20. package/scripts/compare-perception-replays.test.ts +188 -0
  21. package/scripts/compare-perception-replays.ts +589 -0
  22. package/scripts/generate-spatial-facts.py +246 -0
  23. package/scripts/package-readme.mjs +48 -0
  24. package/scripts/replay-perception.ts +347 -0
  25. package/scripts/sync-frontend-map.mjs +195 -0
  26. package/scripts/watch-perception-events.test.ts +43 -0
  27. package/scripts/watch-perception-events.ts +162 -0
  28. package/skills/clawclaw/SKILL.md +121 -65
  29. package/skills/clawclaw/references/CHATTERBOX.md +2 -4
  30. package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +1 -1
  31. package/skills/clawclaw/references/COMMANDS.md +95 -61
  32. package/skills/clawclaw/references/GAME-MECHANICS.md +19 -9
  33. package/skills/clawclaw/references/HUB.md +5 -5
  34. package/skills/clawclaw/references/STRATEGIES.md +34 -17
  35. package/skills/clawclaw/references/STREAM.md +82 -46
  36. package/src/assets/clawclaw-map.json +1692 -0
  37. package/src/assets/clawclaw-spatial-facts.json +1291 -0
  38. package/src/assets/clawclaw-spatial-model.txt +142 -0
  39. package/src/cli.ts +21 -47
  40. package/src/commands/account.test.ts +229 -50
  41. package/src/commands/account.ts +456 -223
  42. package/src/commands/communication.test.ts +259 -0
  43. package/src/commands/communication.ts +391 -0
  44. package/src/commands/competition.test.ts +116 -0
  45. package/src/commands/competition.ts +50 -28
  46. package/src/commands/data.test.ts +57 -1
  47. package/src/commands/data.ts +79 -4
  48. package/src/commands/events-canonical-state.test.ts +187 -0
  49. package/src/commands/events.test.ts +50 -136
  50. package/src/commands/events.ts +175 -241
  51. package/src/commands/game/index.test.ts +510 -0
  52. package/src/commands/game/index.ts +556 -0
  53. package/src/commands/game-map.test.ts +48 -7
  54. package/src/commands/hub.test.ts +2 -23
  55. package/src/commands/hub.ts +4 -16
  56. package/src/commands/load.test.ts +10 -22
  57. package/src/commands/load.ts +15 -2
  58. package/src/commands/peek.ts +2 -3
  59. package/src/commands/perception.test.ts +46 -0
  60. package/src/commands/perception.ts +92 -0
  61. package/src/commands/setup/codex.ts +0 -1
  62. package/src/commands/strategy.test.ts +139 -102
  63. package/src/commands/strategy.ts +175 -103
  64. package/src/commands/upgrade.ts +0 -21
  65. package/src/lib/auth.test.ts +35 -0
  66. package/src/lib/auth.ts +45 -6
  67. package/src/lib/diagnostics-config.test.ts +59 -0
  68. package/src/lib/diagnostics-config.ts +76 -0
  69. package/src/lib/game-client.test.ts +166 -0
  70. package/src/lib/game-client.ts +316 -87
  71. package/src/lib/game-context.ts +33 -4
  72. package/src/lib/gameplay-config.test.ts +66 -0
  73. package/src/lib/gameplay-config.ts +151 -0
  74. package/src/lib/http-transport.test.ts +63 -0
  75. package/src/lib/http-transport.ts +76 -10
  76. package/src/lib/init-command.test.ts +25 -1
  77. package/src/lib/init-command.ts +66 -1
  78. package/src/lib/participation-leave.ts +78 -0
  79. package/src/lib/perception-config.test.ts +138 -0
  80. package/src/lib/perception-config.ts +101 -0
  81. package/src/lib/room.test.ts +14 -0
  82. package/src/lib/room.ts +28 -2
  83. package/src/lib/server-registry.test.ts +15 -5
  84. package/src/lib/server-registry.ts +9 -10
  85. package/src/lib/strategy-export.test.ts +123 -44
  86. package/src/lib/strategy-export.ts +110 -81
  87. package/src/lib/user-data.test.ts +2 -0
  88. package/src/lib/user-data.ts +17 -16
  89. package/src/pipeline/canonical-event-presentation.test.ts +196 -0
  90. package/src/pipeline/canonical-event-presentation.ts +71 -0
  91. package/src/pipeline/event-format.test.ts +357 -59
  92. package/src/pipeline/event-format.ts +365 -80
  93. package/src/pipeline/event-hints.test.ts +241 -0
  94. package/src/pipeline/event-hints.ts +202 -51
  95. package/src/pipeline/game-sync-event-normalization.test.ts +239 -0
  96. package/src/pipeline/game-sync-event-normalization.ts +215 -0
  97. package/src/pipeline/player-projection.test.ts +164 -102
  98. package/src/pipeline/player-projection.ts +194 -235
  99. package/src/runtime/canonical-event-emitter.test.ts +70 -0
  100. package/src/runtime/canonical-event-emitter.ts +78 -0
  101. package/src/runtime/canonical-monitor.test.ts +575 -0
  102. package/src/runtime/canonical-monitor.ts +388 -0
  103. package/src/runtime/clawclaw/agent-event-policy.test.ts +27 -0
  104. package/src/runtime/clawclaw/agent-event-policy.ts +35 -0
  105. package/src/runtime/clawclaw/index.ts +4 -0
  106. package/src/runtime/clawclaw/notifications.test.ts +47 -0
  107. package/src/runtime/clawclaw/notifications.ts +65 -0
  108. package/src/runtime/clawclaw/owner-lock.test.ts +221 -0
  109. package/src/runtime/clawclaw/owner.ts +945 -0
  110. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +299 -0
  111. package/src/runtime/clawclaw/plugins/action/index.ts +1 -0
  112. package/src/runtime/clawclaw/plugins/assembly.test.ts +81 -0
  113. package/src/runtime/clawclaw/plugins/assembly.ts +116 -0
  114. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.test.ts +150 -0
  115. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +100 -0
  116. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +162 -0
  117. package/src/runtime/clawclaw/plugins/derived-event/index.ts +2 -0
  118. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.test.ts +223 -0
  119. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +236 -0
  120. package/src/runtime/clawclaw/plugins/game-query/index.ts +1 -0
  121. package/src/runtime/clawclaw/plugins/index.ts +7 -0
  122. package/src/runtime/clawclaw/plugins/mailbox/index.ts +3 -0
  123. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +77 -0
  124. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +91 -0
  125. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.test.ts +1008 -0
  126. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +475 -0
  127. package/src/runtime/clawclaw/plugins/perception/contracts.ts +32 -0
  128. package/src/runtime/clawclaw/plugins/perception/index.ts +8 -0
  129. package/src/runtime/clawclaw/plugins/perception/module-runner.test.ts +204 -0
  130. package/src/runtime/clawclaw/plugins/perception/module-runner.ts +290 -0
  131. package/src/runtime/clawclaw/plugins/perception/modules/co-movement-module.ts +324 -0
  132. package/src/runtime/clawclaw/plugins/perception/modules/follow-module.ts +365 -0
  133. package/src/runtime/clawclaw/plugins/perception/modules/index.ts +7 -0
  134. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.test.ts +341 -0
  135. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.ts +447 -0
  136. package/src/runtime/clawclaw/plugins/perception/modules/parallel-module-test-helpers.ts +30 -0
  137. package/src/runtime/clawclaw/plugins/perception/modules/relation-stability.test.ts +289 -0
  138. package/src/runtime/clawclaw/plugins/perception/modules/route-module.test.ts +180 -0
  139. package/src/runtime/clawclaw/plugins/perception/modules/route-module.ts +329 -0
  140. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.test.ts +82 -0
  141. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.ts +172 -0
  142. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.test.ts +212 -0
  143. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.ts +256 -0
  144. package/src/runtime/clawclaw/plugins/perception/modules/temporal-evidence.test.ts +121 -0
  145. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.test.ts +106 -0
  146. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.ts +225 -0
  147. package/src/runtime/clawclaw/plugins/perception/official-module-ids.ts +11 -0
  148. package/src/runtime/clawclaw/plugins/perception/official-modules.ts +31 -0
  149. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.test.ts +759 -0
  150. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +707 -0
  151. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +215 -0
  152. package/src/runtime/clawclaw/plugins/perception/perception-module-loader.ts +61 -0
  153. package/src/runtime/clawclaw/plugins/perception/perception-plugin.test.ts +1516 -0
  154. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1529 -0
  155. package/src/runtime/clawclaw/plugins/perception/perception-source.test.ts +119 -0
  156. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +244 -0
  157. package/src/runtime/clawclaw/plugins/perception/replay.test.ts +65 -0
  158. package/src/runtime/clawclaw/plugins/perception/replay.ts +86 -0
  159. package/src/runtime/clawclaw/plugins/perception/shared/math.ts +107 -0
  160. package/src/runtime/clawclaw/plugins/perception/spatial-facts.ts +114 -0
  161. package/src/runtime/clawclaw/plugins/perception/visual-state-projector.ts +98 -0
  162. package/src/runtime/clawclaw/plugins/runtime-plugins.test.ts +1019 -0
  163. package/src/runtime/clawclaw/plugins/source/game-transport.test.ts +287 -0
  164. package/src/runtime/clawclaw/plugins/source/game-transport.ts +281 -0
  165. package/src/runtime/clawclaw/plugins/source/index.ts +5 -0
  166. package/src/runtime/clawclaw/plugins/source/player-change-tracker.test.ts +270 -0
  167. package/src/runtime/clawclaw/plugins/source/player-change-tracker.ts +151 -0
  168. package/src/runtime/clawclaw/plugins/source/room-transport.test.ts +307 -0
  169. package/src/runtime/clawclaw/plugins/source/room-transport.ts +480 -0
  170. package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +1909 -0
  171. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +2055 -0
  172. package/src/runtime/clawclaw/plugins/source/source-transports.ts +30 -0
  173. package/src/runtime/clawclaw/plugins/source/types.ts +79 -0
  174. package/src/runtime/clawclaw/plugins/strategy/context-capabilities.ts +5 -0
  175. package/src/runtime/clawclaw/plugins/strategy/examples/task-only-strategy.test.ts +177 -0
  176. package/src/runtime/clawclaw/plugins/strategy/examples/task-only-strategy.ts +185 -0
  177. package/src/runtime/clawclaw/plugins/strategy/index.ts +8 -0
  178. package/src/runtime/clawclaw/plugins/strategy/local-strategy-executor.ts +412 -0
  179. package/src/runtime/clawclaw/plugins/strategy/strategy-action.ts +73 -0
  180. package/src/runtime/clawclaw/plugins/strategy/strategy-analysis-thread-host.ts +183 -0
  181. package/src/runtime/clawclaw/plugins/strategy/strategy-executor-types.ts +25 -0
  182. package/src/runtime/clawclaw/plugins/strategy/strategy-executor.test.ts +693 -0
  183. package/src/runtime/clawclaw/plugins/strategy/strategy-game-api.ts +57 -0
  184. package/src/runtime/clawclaw/plugins/strategy/strategy-module-loader.ts +164 -0
  185. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.test.ts +1936 -0
  186. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.ts +1557 -0
  187. package/src/runtime/clawclaw/plugins/strategy/strategy-source.test.ts +131 -0
  188. package/src/runtime/clawclaw/plugins/strategy/strategy-source.ts +413 -0
  189. package/src/runtime/clawclaw/plugins/strategy/thread-strategy-executor.ts +792 -0
  190. package/src/runtime/clawclaw/runtime-data-export.test.ts +249 -0
  191. package/src/runtime/clawclaw/runtime-data-export.ts +402 -0
  192. package/src/runtime/clawclaw/runtime-state.ts +98 -0
  193. package/src/runtime/clawclaw/runtime.ts +133 -0
  194. package/src/runtime/clawclaw-event-catalog.test.ts +74 -0
  195. package/src/runtime/clawclaw-event-catalog.ts +266 -0
  196. package/src/runtime/clawclaw-position.ts +4 -0
  197. package/src/runtime/clawclaw-room-state.ts +51 -0
  198. package/src/runtime/framework/action-diagnostics.test.ts +81 -0
  199. package/src/runtime/framework/action-diagnostics.ts +146 -0
  200. package/src/runtime/framework/capability-registry.test.ts +282 -0
  201. package/src/runtime/framework/capability-registry.ts +283 -0
  202. package/src/runtime/framework/contracts.ts +118 -0
  203. package/src/runtime/framework/control/control-scheduler.ts +1260 -0
  204. package/src/runtime/framework/control/domain-set.ts +81 -0
  205. package/src/runtime/framework/control/index.ts +3 -0
  206. package/src/runtime/framework/control/types.ts +184 -0
  207. package/src/runtime/framework/control-coordinator.test.ts +660 -0
  208. package/src/runtime/framework/control-coordinator.ts +11 -0
  209. package/src/runtime/framework/events/event-catalog.ts +74 -0
  210. package/src/runtime/framework/events/event-delivery-service.test.ts +84 -0
  211. package/src/runtime/framework/events/event-delivery-service.ts +198 -0
  212. package/src/runtime/framework/events/event-ingress.test.ts +178 -0
  213. package/src/runtime/framework/events/event-ingress.ts +97 -0
  214. package/src/runtime/framework/events/event-repository.ts +59 -0
  215. package/src/runtime/framework/events/index.ts +7 -0
  216. package/src/runtime/framework/events/mailbox-event-repositories.test.ts +594 -0
  217. package/src/runtime/framework/events/memory-event-repository.ts +928 -0
  218. package/src/runtime/framework/events/sqlite-event-repository.test.ts +200 -0
  219. package/src/runtime/framework/events/sqlite-event-repository.ts +1681 -0
  220. package/src/runtime/framework/events/test-helpers.ts +78 -0
  221. package/src/runtime/framework/events/types.ts +286 -0
  222. package/src/runtime/framework/index.ts +7 -0
  223. package/src/runtime/framework/load-node-sqlite.ts +17 -0
  224. package/src/runtime/framework/mailbox/coalescer.test.ts +55 -0
  225. package/src/runtime/framework/mailbox/coalescer.ts +83 -0
  226. package/src/runtime/framework/mailbox/host-notification-sink.ts +44 -0
  227. package/src/runtime/framework/mailbox/identity.test.ts +38 -0
  228. package/src/runtime/framework/mailbox/identity.ts +38 -0
  229. package/src/runtime/framework/mailbox/index.ts +7 -0
  230. package/src/runtime/framework/mailbox/mailbox-dispatcher.test.ts +513 -0
  231. package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +282 -0
  232. package/src/runtime/framework/mailbox/mailbox-repository.ts +44 -0
  233. package/src/runtime/framework/mailbox/notification-projector.test.ts +77 -0
  234. package/src/runtime/framework/mailbox/notification-projector.ts +65 -0
  235. package/src/runtime/framework/mailbox/types.ts +139 -0
  236. package/src/runtime/framework/modules/runtime-module-loader-hooks.d.mts +19 -0
  237. package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +117 -0
  238. package/src/runtime/framework/modules/runtime-module-loader.test.ts +209 -0
  239. package/src/runtime/framework/modules/runtime-module-loader.ts +71 -0
  240. package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +23 -0
  241. package/src/runtime/framework/participation-manager.test.ts +108 -0
  242. package/src/runtime/framework/participation-manager.ts +244 -0
  243. package/src/runtime/framework/plugins/contracts.ts +382 -0
  244. package/src/runtime/framework/plugins/index.ts +4 -0
  245. package/src/runtime/framework/plugins/runtime-event-identity.ts +17 -0
  246. package/src/runtime/framework/plugins/runtime-input-journal.test.ts +179 -0
  247. package/src/runtime/framework/plugins/runtime-input-journal.ts +693 -0
  248. package/src/runtime/framework/plugins/runtime-plugin-scheduler.test.ts +1994 -0
  249. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +1860 -0
  250. package/src/runtime/framework/runtime.ts +1756 -0
  251. package/src/runtime/framework/serial-task-queue.ts +14 -0
  252. package/src/runtime/framework/state/contracts.ts +49 -0
  253. package/src/runtime/framework/state/current-state-store.ts +184 -0
  254. package/src/runtime/framework/state/durable-agent-state-snapshot.test.ts +144 -0
  255. package/src/runtime/framework/state/durable-agent-state-snapshot.ts +209 -0
  256. package/src/runtime/framework/state/freshness.ts +72 -0
  257. package/src/runtime/framework/state/history/contracts.ts +150 -0
  258. package/src/runtime/framework/state/history/history-writer.ts +194 -0
  259. package/src/runtime/framework/state/history/memory-state-history-repository.ts +178 -0
  260. package/src/runtime/framework/state/history/sqlite-state-history-repository.test.ts +157 -0
  261. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +629 -0
  262. package/src/runtime/framework/state/history/state-history.test.ts +251 -0
  263. package/src/runtime/framework/state/history/trajectory-projector.ts +209 -0
  264. package/src/runtime/framework/state/index.ts +13 -0
  265. package/src/runtime/framework/state/state-core.test.ts +197 -0
  266. package/src/runtime/framework/state/state-ingress.ts +95 -0
  267. package/src/runtime/framework/state/state-provider.ts +62 -0
  268. package/src/runtime/framework/state/types.ts +155 -0
  269. package/src/runtime/game-sync-protocol.test.ts +123 -0
  270. package/src/runtime/game-sync-protocol.ts +261 -0
  271. package/src/runtime/mailbox-host-relay.test.ts +248 -0
  272. package/src/runtime/mailbox-host-relay.ts +300 -0
  273. package/src/runtime/observability/factory.ts +188 -0
  274. package/src/runtime/observability/index.ts +6 -0
  275. package/src/runtime/observability/observability.test.ts +561 -0
  276. package/src/runtime/observability/recorder.ts +209 -0
  277. package/src/runtime/observability/redaction.ts +154 -0
  278. package/src/runtime/observability/reporter.ts +154 -0
  279. package/src/runtime/observability/sinks.ts +135 -0
  280. package/src/runtime/observability/types.ts +92 -0
  281. package/src/runtime/owner-control.test.ts +153 -0
  282. package/src/runtime/owner-control.ts +206 -42
  283. package/src/runtime/parent-process-watch.test.ts +27 -0
  284. package/src/runtime/parent-process-watch.ts +51 -0
  285. package/src/runtime/pending-event-handoff.test.ts +29 -0
  286. package/src/runtime/pending-event-handoff.ts +61 -0
  287. package/src/runtime/raw-ws-log.test.ts +86 -17
  288. package/src/runtime/raw-ws-log.ts +230 -21
  289. package/src/runtime/runtime-logger.test.ts +58 -0
  290. package/src/runtime/runtime-logger.ts +10 -13
  291. package/src/runtime/runtime-persistence.test.ts +26 -0
  292. package/src/runtime/runtime.test.ts +1704 -0
  293. package/src/runtime/ws-client.test.ts +496 -103
  294. package/src/runtime/ws-client.ts +546 -166
  295. package/src/sdk/action.ts +3 -1
  296. package/src/sdk/index.ts +4 -19
  297. package/src/sdk/perception-plugin/index.test.ts +22 -0
  298. package/src/sdk/perception-plugin/index.ts +285 -0
  299. package/src/sdk/strategy-plugin/index.test.ts +952 -0
  300. package/src/sdk/strategy-plugin/index.ts +1324 -0
  301. package/src/sdk/types.ts +3 -1
  302. package/src/short-command/classifier.test.ts +107 -0
  303. package/src/short-command/classifier.ts +169 -0
  304. package/src/short-command/index.ts +7 -0
  305. package/src/short-command/presenter.test.ts +119 -0
  306. package/src/short-command/presenter.ts +308 -0
  307. package/src/short-command/process-io.ts +13 -0
  308. package/src/short-command/response-contract.ts +58 -0
  309. package/src/short-command/runner.test.ts +78 -0
  310. package/src/short-command/runner.ts +164 -0
  311. package/src/short-command/sensitive-data-filter.test.ts +56 -0
  312. package/src/short-command/sensitive-data-filter.ts +123 -0
  313. package/src/short-command/transport-response.test.ts +39 -0
  314. package/src/short-command/transport-response.ts +89 -0
  315. package/src/short-command/types.ts +92 -0
  316. package/src/strategies/avoid-lone.ts +18 -11
  317. package/src/strategies/avoid-players.ts +29 -13
  318. package/src/strategies/corpse-patrol.ts +29 -11
  319. package/src/strategies/crab-sabotage.ts +31 -18
  320. package/src/strategies/custom-module.test.ts +3 -5
  321. package/src/strategies/find-player.ts +34 -15
  322. package/src/strategies/game-utils.test.ts +42 -0
  323. package/src/strategies/game-utils.ts +143 -53
  324. package/src/strategies/goals/avoid-lone-top.ts +22 -1
  325. package/src/strategies/goals/avoid-players-top.test.ts +13 -0
  326. package/src/strategies/goals/avoid-players-top.ts +6 -5
  327. package/src/strategies/goals/corpse-patrol-top.ts +9 -2
  328. package/src/strategies/goals/crab-octopus-reflexes.ts +6 -2
  329. package/src/strategies/goals/crab-sabotage-top.ts +7 -1
  330. package/src/strategies/goals/emergency-hunt-goal.ts +15 -3
  331. package/src/strategies/goals/find-player-top.ts +47 -3
  332. package/src/strategies/goals/flee-players-goal.ts +2 -0
  333. package/src/strategies/goals/follow-companion-goal.ts +27 -3
  334. package/src/strategies/goals/hide-top.ts +47 -5
  335. package/src/strategies/goals/keep-away-goal.ts +24 -2
  336. package/src/strategies/goals/kill-frenzy-top.ts +12 -2
  337. package/src/strategies/goals/kill-lone-top.test.ts +72 -0
  338. package/src/strategies/goals/kill-lone-top.ts +8 -6
  339. package/src/strategies/goals/kill-target-goal.ts +16 -7
  340. package/src/strategies/goals/kill-target-top.ts +16 -2
  341. package/src/strategies/goals/linger-corpse-goal.ts +11 -3
  342. package/src/strategies/goals/lone-kill-core.ts +4 -2
  343. package/src/strategies/goals/move-room-goal.ts +46 -4
  344. package/src/strategies/goals/normal-shrimp-top.test.ts +16 -0
  345. package/src/strategies/goals/normal-shrimp-top.ts +18 -18
  346. package/src/strategies/goals/paradise-fish-top.test.ts +78 -0
  347. package/src/strategies/goals/paradise-fish-top.ts +16 -6
  348. package/src/strategies/goals/patrol-top.ts +14 -3
  349. package/src/strategies/goals/report-patrol-top.ts +14 -3
  350. package/src/strategies/goals/safe-task-goal.ts +32 -4
  351. package/src/strategies/goals/social-task-top.ts +39 -8
  352. package/src/strategies/goals/task-kill-report-top.ts +33 -10
  353. package/src/strategies/goals/task-only-top.test.ts +89 -0
  354. package/src/strategies/goals/task-only-top.ts +9 -2
  355. package/src/strategies/goals/task-or-patrol-goal.ts +21 -3
  356. package/src/strategies/goals/warrior-shrimp-top.test.ts +75 -23
  357. package/src/strategies/goals/warrior-shrimp-top.ts +34 -13
  358. package/src/strategies/greeting.ts +10 -3
  359. package/src/strategies/hide-spots.ts +4 -0
  360. package/src/strategies/hide.ts +35 -20
  361. package/src/strategies/kill-frenzy.ts +18 -12
  362. package/src/strategies/kill-lone.ts +43 -12
  363. package/src/strategies/kill-target.ts +34 -17
  364. package/src/strategies/lone-kill-task.ts +31 -18
  365. package/src/strategies/move-room.ts +32 -15
  366. package/src/strategies/off-route-points.ts +12 -4
  367. package/src/strategies/paradise-fish.ts +49 -14
  368. package/src/strategies/pathfind/astar-path.test.ts +73 -0
  369. package/src/strategies/pathfind/astar-path.ts +196 -0
  370. package/src/strategies/pathfind/escape-planner.test.ts +27 -1
  371. package/src/strategies/pathfind/escape-planner.ts +108 -0
  372. package/src/strategies/patrol.ts +18 -11
  373. package/src/strategies/report-patrol.ts +18 -11
  374. package/src/strategies/shrimp-memory.ts +66 -14
  375. package/src/strategies/social-task.ts +49 -45
  376. package/src/strategies/task-kill-report.ts +34 -16
  377. package/src/strategies/task-only.test.ts +124 -0
  378. package/src/strategies/task-only.ts +20 -11
  379. package/src/strategies/task-report.ts +29 -11
  380. package/src/strategies/types.ts +29 -62
  381. package/src/strategies/warrior-memory.ts +44 -14
  382. package/scripts/check_monitor.test.mjs +0 -212
  383. package/skills/clawclaw/references/KNOWLEDGE.md +0 -42
  384. package/src/assets/clawclaw-ascii-map.txt +0 -40
  385. package/src/commands/do.test.ts +0 -117
  386. package/src/commands/do.ts +0 -195
  387. package/src/commands/game-monitor-status.test.ts +0 -58
  388. package/src/commands/game-start-plan.test.ts +0 -356
  389. package/src/commands/game.ts +0 -2046
  390. package/src/commands/history-player.test.ts +0 -105
  391. package/src/commands/history.ts +0 -573
  392. package/src/commands/knowledge.test.ts +0 -13
  393. package/src/commands/knowledge.ts +0 -176
  394. package/src/commands/meeting-history.test.ts +0 -106
  395. package/src/commands/state.ts +0 -46
  396. package/src/commands/watch.test.ts +0 -1313
  397. package/src/commands/watch.ts +0 -824
  398. package/src/lib/knowledge-store.test.ts +0 -170
  399. package/src/lib/knowledge-store.ts +0 -369
  400. package/src/perception/player-history-store.test.ts +0 -177
  401. package/src/perception/player-history-store.ts +0 -262
  402. package/src/pipeline/event-store.test.ts +0 -28
  403. package/src/pipeline/event-store.ts +0 -193
  404. package/src/pipeline/pipeline.ts +0 -35
  405. package/src/runtime/event-daemon.test.ts +0 -268
  406. package/src/runtime/event-daemon.ts +0 -531
  407. package/src/runtime/room-lobby-runtime.test.ts +0 -95
  408. package/src/runtime/room-lobby-runtime.ts +0 -367
  409. package/src/strategies/avoid-players.knowledge.md +0 -19
  410. package/src/strategies/kill-lone.knowledge.md +0 -17
  411. package/src/strategies/knowledge-contract.ts +0 -85
  412. package/src/strategies/loader.test.ts +0 -710
  413. package/src/strategies/loader.ts +0 -183
  414. package/src/strategies/new-events-backfill.ts +0 -98
  415. package/src/strategies/paradise-fish.knowledge.md +0 -19
  416. package/src/strategies/scanner.ts +0 -238
  417. package/src/strategies/shrimp-memory.knowledge.md +0 -19
  418. package/src/strategies/social-task.test.ts +0 -28
  419. package/src/strategies/spawn.ts +0 -82
  420. package/src/strategies/strategy-loop.test.ts +0 -15
  421. package/src/strategies/strategy-loop.ts +0 -748
  422. package/src/strategies/warrior-memory.knowledge.md +0 -21
@@ -0,0 +1,1557 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import type {
3
+ StrategyActionAck,
4
+ StrategyControlSpec,
5
+ StrategyControlResult,
6
+ StrategyControlUpdate,
7
+ StrategyFrame,
8
+ StrategyResult,
9
+ } from '../../../../sdk/strategy-plugin/index.js';
10
+ import type {
11
+ RuntimeEpochCatchUp,
12
+ RuntimeDiagnosticSeverity,
13
+ RuntimeEpochPlugin,
14
+ RuntimeEpochPluginContext,
15
+ RuntimeEpochPluginInput,
16
+ RuntimeEpochPluginResult,
17
+ } from '../../../framework/plugins/index.js';
18
+ import { isClawclawRuntimeState } from '../../runtime-state.js';
19
+ import { CLAWCLAW_ACTION_CAPABILITY } from '../action/index.js';
20
+ import {
21
+ clawclawMapFromGameState,
22
+ clawclawTasksFromGameState,
23
+ type ClawclawPathDistanceRequest,
24
+ } from '../game-query/index.js';
25
+ import {
26
+ CLAWCLAW_MAP_CAPABILITY,
27
+ CLAWCLAW_PATH_DISTANCE_CAPABILITY,
28
+ CLAWCLAW_TASKS_CAPABILITY,
29
+ } from './context-capabilities.js';
30
+ import { normalizeClawclawStrategyAction } from './strategy-action.js';
31
+ import {
32
+ LocalStrategyExecutor,
33
+ type LocalStrategyExecutorOptions,
34
+ } from './local-strategy-executor.js';
35
+ import { ThreadStrategyExecutor } from './thread-strategy-executor.js';
36
+ import type {
37
+ StrategyGameQuery,
38
+ StrategyGameQueryResult,
39
+ StrategySource,
40
+ } from './strategy-executor-types.js';
41
+
42
+ export const CLAWCLAW_STRATEGY_PLUGIN_ID = 'clawclaw.strategy';
43
+ export const CLAWCLAW_STRATEGY_STATE_TOPIC = 'strategy.status';
44
+ export const CLAWCLAW_STRATEGY_EVENT_TYPES = ['strategy_alert', 'robot_speak_rule'] as const;
45
+
46
+ export interface ClawclawStrategySelection extends StrategySource {
47
+ readonly parameters?: Readonly<Record<string, unknown>>;
48
+ readonly controls?: readonly StrategyControlSpec[];
49
+ }
50
+
51
+ export interface ClawclawStrategyExecutor {
52
+ readonly runtimeInstanceId: string;
53
+ readonly isAlive: boolean;
54
+ start(parameters: Readonly<Record<string, unknown>>, signal: AbortSignal): Promise<void>;
55
+ applyControl?(
56
+ update: StrategyControlUpdate,
57
+ signal: AbortSignal,
58
+ ): Promise<StrategyControlResult>;
59
+ reset(signal: AbortSignal): Promise<void>;
60
+ update(frame: StrategyFrame<Record<string, unknown>>, signal: AbortSignal): Promise<StrategyResult>;
61
+ analyze?(frame: StrategyFrame<Record<string, unknown>>, signal: AbortSignal): Promise<unknown>;
62
+ reduce?(
63
+ frame: StrategyFrame<Record<string, unknown>>,
64
+ analysis: unknown,
65
+ signal: AbortSignal,
66
+ ): Promise<StrategyResult>;
67
+ stop(reason: 'switched' | 'scope_ended' | 'shutdown'): Promise<void>;
68
+ }
69
+
70
+ export interface ClawclawStrategyExecutorHost {
71
+ action(action: Record<string, unknown>): Promise<StrategyActionAck>;
72
+ gameQuery(
73
+ query: StrategyGameQuery,
74
+ frame?: StrategyFrame<Record<string, unknown>>,
75
+ ): Promise<StrategyGameQueryResult>;
76
+ diagnostic(
77
+ name: string,
78
+ attributes?: Readonly<Record<string, unknown>>,
79
+ severity?: RuntimeDiagnosticSeverity,
80
+ ): void;
81
+ }
82
+
83
+ export type ClawclawStrategyExecutorFactory = (
84
+ selection: ClawclawStrategySelection,
85
+ host: ClawclawStrategyExecutorHost,
86
+ purpose?: 'serial' | 'parallel',
87
+ ) => ClawclawStrategyExecutor;
88
+
89
+ export interface ClawclawStrategyPluginOptions {
90
+ after?: readonly string[];
91
+ consumes?: RuntimeEpochPlugin<Record<string, any>>['consumes'];
92
+ produces?: RuntimeEpochPlugin<Record<string, any>>['produces'];
93
+ timeoutMs?: number;
94
+ catchUp?: RuntimeEpochCatchUp;
95
+ executorFactory?: ClawclawStrategyExecutorFactory;
96
+ defaultSelectionForRole?: (role: string) => ClawclawStrategySelection;
97
+ }
98
+
99
+ export interface ClawclawStrategyStatus {
100
+ readonly selected?: string;
101
+ readonly pending?: string;
102
+ readonly running: boolean;
103
+ }
104
+
105
+ export interface ClawclawStrategyControlAck extends StrategyControlResult {
106
+ readonly strategy: string;
107
+ readonly revision: number;
108
+ readonly appliedEpochId: number;
109
+ }
110
+
111
+ interface PendingStrategyControl {
112
+ readonly strategyId: string;
113
+ readonly revision: number;
114
+ readonly values: Readonly<Record<string, unknown>>;
115
+ readonly preAppliedValues?: Readonly<Record<string, unknown>>;
116
+ readonly resolve: (ack: ClawclawStrategyControlAck) => void;
117
+ readonly reject: (error: Error) => void;
118
+ }
119
+
120
+ interface StrategyComputationBase {
121
+ readonly generation: number;
122
+ /** Invalidates hybrid analyses computed with an older parameter snapshot. */
123
+ readonly parameterGeneration: number;
124
+ readonly actionBarrierGeneration: number;
125
+ readonly actionSafetyGeneration?: number;
126
+ readonly selection?: ClawclawStrategySelection;
127
+ readonly cursor?: number;
128
+ }
129
+
130
+ type StrategyComputationProposal = StrategyComputationBase & (
131
+ | {
132
+ readonly kind: 'noop';
133
+ readonly reason: string;
134
+ readonly resetBeforeNextWandering: boolean;
135
+ }
136
+ | {
137
+ readonly kind: 'legacy';
138
+ readonly frame: StrategyFrame<Record<string, unknown>>;
139
+ }
140
+ | {
141
+ readonly kind: 'parallel_compute';
142
+ readonly frame: StrategyFrame<Record<string, unknown>>;
143
+ readonly result: StrategyResult;
144
+ }
145
+ | {
146
+ readonly kind: 'parallel_analyze';
147
+ readonly frame: StrategyFrame<Record<string, unknown>>;
148
+ readonly analysis: unknown;
149
+ }
150
+ );
151
+
152
+ function strategyProposal(value: unknown): StrategyComputationProposal {
153
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
154
+ throw new Error('strategy_computation_proposal_invalid');
155
+ }
156
+ const proposal = value as StrategyComputationProposal;
157
+ if (!['noop', 'legacy', 'parallel_compute', 'parallel_analyze'].includes(proposal.kind)) {
158
+ throw new Error('strategy_computation_proposal_invalid');
159
+ }
160
+ return proposal;
161
+ }
162
+
163
+ function awaitWithAbort<T>(operation: Promise<T>, signal: AbortSignal): Promise<T> {
164
+ if (signal.aborted) {
165
+ return Promise.reject(signal.reason instanceof Error
166
+ ? signal.reason
167
+ : new Error('strategy_epoch_aborted'));
168
+ }
169
+ return new Promise<T>((resolve, reject) => {
170
+ const onAbort = (): void => reject(signal.reason instanceof Error
171
+ ? signal.reason
172
+ : new Error('strategy_epoch_aborted'));
173
+ signal.addEventListener('abort', onAbort, { once: true });
174
+ void operation.then(resolve, reject).finally(() => {
175
+ signal.removeEventListener('abort', onAbort);
176
+ });
177
+ });
178
+ }
179
+
180
+ function validStrategyControlValue(spec: StrategyControlSpec, value: unknown): boolean {
181
+ if (spec.type === 'boolean') return typeof value === 'boolean';
182
+ if (spec.type === 'number') return typeof value === 'number' && Number.isFinite(value);
183
+ if (spec.type === 'string') return typeof value === 'string';
184
+ if (spec.type === 'enum') return typeof value === 'string' && !!spec.values?.includes(value);
185
+ return Array.isArray(value) && value.every((entry) => typeof entry === 'string');
186
+ }
187
+
188
+ function validateParallelControls(
189
+ selection: ClawclawStrategySelection,
190
+ values: Readonly<Record<string, unknown>>,
191
+ ): void {
192
+ const controls = new Map((selection.controls ?? []).map((control) => [control.id, control]));
193
+ if (controls.size === 0) throw new Error('strategy_controls_not_supported');
194
+ for (const [key, value] of Object.entries(values)) {
195
+ const spec = controls.get(key);
196
+ if (!spec) throw new Error(`unsupported_strategy_control:${key}`);
197
+ if (!validStrategyControlValue(spec, value)) {
198
+ throw new Error(`invalid_strategy_control:${key}`);
199
+ }
200
+ }
201
+ }
202
+
203
+ function diagnosticErrorCode(error: unknown, fallback: string): string {
204
+ const code = error && typeof error === 'object' && typeof (error as any).code === 'string'
205
+ ? (error as any).code.trim()
206
+ : '';
207
+ if (/^[A-Za-z][A-Za-z0-9_.-]{0,119}$/.test(code)) return code;
208
+ const message = error instanceof Error ? error.message : typeof error === 'string' ? error : '';
209
+ return /^([A-Za-z][A-Za-z0-9_.-]{0,119})(?::|$)/.exec(message.trim())?.[1] ?? fallback;
210
+ }
211
+
212
+ function strategyActionControllerId(strategyId: string, generation: number): string {
213
+ return `${strategyId}@activation-${generation}`;
214
+ }
215
+
216
+ function isStaleStrategyActionResult(value: unknown): boolean {
217
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
218
+ const result = value as Record<string, unknown>;
219
+ if (
220
+ result.status !== 'failure'
221
+ || result.source !== 'local'
222
+ || result.actionOutcome !== 'not_submitted'
223
+ ) return false;
224
+ const outer = result.error;
225
+ if (!outer || typeof outer !== 'object' || Array.isArray(outer)) return false;
226
+ const inner = (outer as Record<string, unknown>).error;
227
+ return !!inner
228
+ && typeof inner === 'object'
229
+ && !Array.isArray(inner)
230
+ && (inner as Record<string, unknown>).code === 'STALE_STRATEGY_ACTION';
231
+ }
232
+
233
+ function strategyBackendTick(
234
+ input: RuntimeEpochPluginInput<Record<string, any>>,
235
+ ): number | undefined {
236
+ if (input.epoch.domainTick === undefined) return undefined;
237
+ const tick = Number(input.epoch.domainTick);
238
+ return Number.isFinite(tick) ? tick : undefined;
239
+ }
240
+
241
+ function strategyFrame(
242
+ input: RuntimeEpochPluginInput<Record<string, any>>,
243
+ parameters: Readonly<Record<string, unknown>>,
244
+ ): StrategyFrame<Record<string, unknown>> {
245
+ const runtimeState = input.epoch.state;
246
+ const gameState = isClawclawRuntimeState(runtimeState)
247
+ && runtimeState.game_snapshot.status === 'fresh'
248
+ ? runtimeState.game_snapshot.state
249
+ : input.currentState.state;
250
+ const backendTick = strategyBackendTick(input);
251
+ const tick = backendTick ?? (gameState && Number.isFinite(gameState.tick)
252
+ ? Number(gameState.tick)
253
+ : undefined);
254
+ const state = gameState ? structuredClone(gameState) : null;
255
+ if (state && backendTick !== undefined) state.tick = backendTick;
256
+ return {
257
+ epochId: input.epoch.epochSeq,
258
+ scope: {
259
+ sessionId: input.epoch.scope.sessionId,
260
+ segmentId: input.epoch.scope.segmentId,
261
+ },
262
+ stage: isClawclawRuntimeState(runtimeState) ? runtimeState.stage : String(gameState?.phase ?? 'unknown'),
263
+ ...(tick === undefined ? {} : { tick }),
264
+ state,
265
+ upstreamStates: structuredClone(input.upstreamStates),
266
+ events: input.pendingEvents.map((event) => ({
267
+ eventId: event.eventId,
268
+ ...(event.epochSeq === undefined ? {} : { epochId: event.epochSeq }),
269
+ type: event.type,
270
+ occurredAt: event.occurredAt,
271
+ payload: structuredClone(event.payload),
272
+ })),
273
+ parameters: structuredClone(parameters),
274
+ };
275
+ }
276
+
277
+ function gameEpochNeedsFreshState(
278
+ input: RuntimeEpochPluginInput<Record<string, any>>,
279
+ ): boolean {
280
+ const state = input.epoch.state;
281
+ return isClawclawRuntimeState(state)
282
+ && state.stage === 'game'
283
+ && state.game_snapshot.status !== 'fresh';
284
+ }
285
+
286
+ function freshWanderingEpoch(
287
+ input: RuntimeEpochPluginInput<Record<string, any>>,
288
+ ): boolean {
289
+ const state = input.epoch.state;
290
+ return isClawclawRuntimeState(state)
291
+ && state.stage === 'game'
292
+ && state.game_snapshot.status === 'fresh'
293
+ && state.game_snapshot.state.phase === 'wandering';
294
+ }
295
+
296
+ function authoritativeActionDisposition(
297
+ input: RuntimeEpochPluginInput<Record<string, any>>,
298
+ ): boolean | undefined {
299
+ const state = input.epoch.state;
300
+ if (!isClawclawRuntimeState(state)) return undefined;
301
+ if (state.connection !== 'connected') return false;
302
+ if (state.stage !== 'game') return false;
303
+ if (state.game_snapshot.status !== 'fresh') return undefined;
304
+ return state.game_snapshot.state.phase === 'wandering'
305
+ && state.game_snapshot.state.you?.is_alive !== false;
306
+ }
307
+
308
+ function inputActionSafetyGeneration(
309
+ input: RuntimeEpochPluginInput<Record<string, any>>,
310
+ ): number | undefined {
311
+ const state = input.epoch.state;
312
+ if (!isClawclawRuntimeState(state)) return undefined;
313
+ const value = state.action_safety_generation;
314
+ return Number.isInteger(value) && (value as number) >= 0 ? value as number : undefined;
315
+ }
316
+
317
+ function inputRequiresStrategyReset(
318
+ input: RuntimeEpochPluginInput<Record<string, any>>,
319
+ ): boolean {
320
+ const state = input.epoch.state;
321
+ return isClawclawRuntimeState(state)
322
+ && (state.connection !== 'connected' || state.stage !== 'game');
323
+ }
324
+
325
+ function hostedStrategyState(
326
+ topic: string,
327
+ value: unknown,
328
+ selection: ClawclawStrategySelection,
329
+ ): unknown {
330
+ if (
331
+ topic !== CLAWCLAW_STRATEGY_STATE_TOPIC
332
+ || !value
333
+ || typeof value !== 'object'
334
+ || Array.isArray(value)
335
+ ) return value;
336
+ return {
337
+ ...value,
338
+ strategy: selection.id,
339
+ parameters: structuredClone(selection.parameters ?? {}),
340
+ };
341
+ }
342
+
343
+ function defaultExecutorFactory(
344
+ selection: ClawclawStrategySelection,
345
+ host: ClawclawStrategyExecutorHost,
346
+ purpose: 'serial' | 'parallel' = 'serial',
347
+ ): ClawclawStrategyExecutor {
348
+ const options: LocalStrategyExecutorOptions = {
349
+ source: selection,
350
+ onAction: host.action,
351
+ diagnostic: host.diagnostic,
352
+ };
353
+ return purpose === 'parallel'
354
+ ? new ThreadStrategyExecutor({ source: selection, diagnostic: host.diagnostic })
355
+ : new LocalStrategyExecutor(options);
356
+ }
357
+
358
+ /** Trusted adapter between one Runtime epoch and one restricted strategy instance. */
359
+ export class ClawclawStrategyPlugin
360
+ implements RuntimeEpochPlugin<Record<string, any>> {
361
+ readonly kind = 'epoch' as const;
362
+ readonly id = CLAWCLAW_STRATEGY_PLUGIN_ID;
363
+ readonly version = '1';
364
+ readonly after: readonly string[];
365
+ readonly consumes: NonNullable<RuntimeEpochPlugin<Record<string, any>>['consumes']>;
366
+ readonly produces: NonNullable<RuntimeEpochPlugin<Record<string, any>>['produces']>;
367
+ readonly capabilities = {
368
+ uses: [
369
+ CLAWCLAW_ACTION_CAPABILITY,
370
+ CLAWCLAW_TASKS_CAPABILITY,
371
+ CLAWCLAW_MAP_CAPABILITY,
372
+ CLAWCLAW_PATH_DISTANCE_CAPABILITY,
373
+ ],
374
+ } as const;
375
+ readonly timeoutMs: number;
376
+ readonly catchUp: RuntimeEpochCatchUp;
377
+ readonly failurePolicy = 'failed_completion' as const;
378
+
379
+ private readonly executorFactory: ClawclawStrategyExecutorFactory;
380
+ private readonly defaultSelectionForRole?: (role: string) => ClawclawStrategySelection;
381
+ private selected?: ClawclawStrategySelection;
382
+ private pendingSelection?: ClawclawStrategySelection;
383
+ private readonly pendingControls: PendingStrategyControl[] = [];
384
+ private controlRevision = 0;
385
+ private executor?: ClawclawStrategyExecutor;
386
+ private parallelExecutor?: ClawclawStrategyExecutor;
387
+ private parallelExecutorReady?: Promise<void>;
388
+ private parallelExecutorLifecycle?: AbortController;
389
+ private parallelExecutorGeneration = 0;
390
+ private readonly parallelContexts = new Map<
391
+ number,
392
+ RuntimeEpochPluginContext<Record<string, any>>
393
+ >();
394
+ private activeContext?: RuntimeEpochPluginContext<Record<string, any>>;
395
+ private activeActionOriginEpochSeq?: number;
396
+ private activeActionSafetyGeneration?: number;
397
+ private activeActionAllowed = false;
398
+ private selectedActionControllerId?: string;
399
+ private latestFrameAllowsActions = false;
400
+ private actionBarrierGeneration = 0;
401
+ private wanderingResetRequired = false;
402
+ private lastInvokedEpochSeq: number | null = null;
403
+ private lastDispatchedBackendTick: number | null = null;
404
+ private selectionGeneration = 0;
405
+ private pendingSelectionGeneration = 0;
406
+ private selectedGeneration = 0;
407
+ private parameterGeneration = 0;
408
+ private readonly committedActionDedupeKeys = new Map<string, number>();
409
+
410
+ constructor(options: ClawclawStrategyPluginOptions = {}) {
411
+ this.after = [...(options.after ?? [])];
412
+ this.consumes = options.consumes ?? { states: ['*'], events: ['*'] };
413
+ this.produces = options.produces ?? {
414
+ states: [CLAWCLAW_STRATEGY_STATE_TOPIC],
415
+ events: CLAWCLAW_STRATEGY_EVENT_TYPES,
416
+ };
417
+ this.timeoutMs = options.timeoutMs ?? 5_000;
418
+ this.catchUp = options.catchUp ?? 'every_epoch';
419
+ this.executorFactory = options.executorFactory ?? defaultExecutorFactory;
420
+ this.defaultSelectionForRole = options.defaultSelectionForRole;
421
+ }
422
+
423
+ get maxInFlight(): number {
424
+ const selection = this.pendingSelection ?? this.selected;
425
+ return selection?.execution === undefined ? 1 : 10;
426
+ }
427
+
428
+ /** A control request changes configuration from the next actual epoch. */
429
+ select(selection: ClawclawStrategySelection): void {
430
+ if (!selection.id.trim()) throw new Error('strategy_id_invalid');
431
+ this.selectionGeneration += 1;
432
+ this.parameterGeneration += 1;
433
+ this.pendingSelectionGeneration = this.selectionGeneration;
434
+ this.pendingSelection = {
435
+ ...selection,
436
+ parameters: structuredClone(selection.parameters ?? {}),
437
+ };
438
+ this.rejectAllPendingControls('strategy_switched_before_control_applied');
439
+ }
440
+
441
+ /** Queues controls for the selected strategy; they apply before its next update(). */
442
+ control(values: Readonly<Record<string, unknown>>): Promise<ClawclawStrategyControlAck> {
443
+ if (!values || typeof values !== 'object' || Array.isArray(values)) {
444
+ throw new Error('invalid_strategy_control');
445
+ }
446
+ const target = this.pendingSelection ?? this.selected;
447
+ if (!target) throw new Error('no_active_strategy');
448
+ const revision = ++this.controlRevision;
449
+ const cloned = structuredClone(values);
450
+ let preAppliedValues: Readonly<Record<string, unknown>> | undefined;
451
+ if (target.execution === 'parallel_compute') {
452
+ validateParallelControls(target, cloned);
453
+ preAppliedValues = structuredClone({
454
+ ...(target.parameters ?? {}),
455
+ ...cloned,
456
+ });
457
+ this.selectionGeneration += 1;
458
+ this.pendingSelectionGeneration = this.selectionGeneration;
459
+ this.pendingSelection = {
460
+ ...target,
461
+ parameters: preAppliedValues,
462
+ };
463
+ }
464
+ return new Promise<ClawclawStrategyControlAck>((resolve, reject) => {
465
+ this.pendingControls.push({
466
+ strategyId: target.id,
467
+ revision,
468
+ values: cloned,
469
+ ...(preAppliedValues === undefined ? {} : { preAppliedValues }),
470
+ resolve,
471
+ reject,
472
+ });
473
+ });
474
+ }
475
+
476
+ status(): ClawclawStrategyStatus {
477
+ return {
478
+ ...(this.selected ? { selected: this.selected.id } : {}),
479
+ ...(this.pendingSelection ? { pending: this.pendingSelection.id } : {}),
480
+ running: (this.executor?.isAlive ?? false) || (this.parallelExecutor?.isAlive ?? false),
481
+ };
482
+ }
483
+
484
+ async update(
485
+ input: RuntimeEpochPluginInput<Record<string, any>>,
486
+ context: RuntimeEpochPluginContext<Record<string, any>>,
487
+ ): Promise<RuntimeEpochPluginResult> {
488
+ this.selectDefaultForAssignedRole(input);
489
+ const actionDisposition = authoritativeActionDisposition(input);
490
+ if (actionDisposition !== undefined) {
491
+ if (this.latestFrameAllowsActions && !actionDisposition) {
492
+ this.actionBarrierGeneration += 1;
493
+ }
494
+ this.latestFrameAllowsActions = actionDisposition;
495
+ }
496
+ const actionBarrierGeneration = this.actionBarrierGeneration;
497
+ const actionSafetyGeneration = inputActionSafetyGeneration(input);
498
+ const cursor = input.pendingEvents.at(-1)?.commitSeq;
499
+ const selection = this.pendingSelection ?? this.selected;
500
+ const generation = this.pendingSelection
501
+ ? this.pendingSelectionGeneration
502
+ : this.selectedGeneration;
503
+ const parameterGeneration = this.parameterGeneration;
504
+ if (gameEpochNeedsFreshState(input)) {
505
+ return {
506
+ outcome: 'processed',
507
+ proposal: {
508
+ kind: 'noop',
509
+ reason: selection ? 'strategy_waiting_for_current_state' : 'strategy_not_selected',
510
+ resetBeforeNextWandering: inputRequiresStrategyReset(input),
511
+ generation,
512
+ parameterGeneration,
513
+ actionBarrierGeneration,
514
+ ...(selection ? { selection: structuredClone(selection) } : {}),
515
+ ...(!selection && cursor !== undefined ? { cursor } : {}),
516
+ } satisfies StrategyComputationProposal,
517
+ };
518
+ }
519
+ if (!freshWanderingEpoch(input)) {
520
+ return {
521
+ outcome: 'processed',
522
+ proposal: {
523
+ kind: 'noop',
524
+ reason: 'strategy_inactive_stage',
525
+ resetBeforeNextWandering: true,
526
+ generation,
527
+ parameterGeneration,
528
+ actionBarrierGeneration,
529
+ ...(selection ? { selection: structuredClone(selection) } : {}),
530
+ ...(cursor === undefined ? {} : { cursor }),
531
+ } satisfies StrategyComputationProposal,
532
+ };
533
+ }
534
+ if (!selection) {
535
+ return {
536
+ outcome: 'processed',
537
+ proposal: {
538
+ kind: 'noop',
539
+ reason: 'strategy_not_selected',
540
+ resetBeforeNextWandering: false,
541
+ generation,
542
+ parameterGeneration,
543
+ actionBarrierGeneration,
544
+ ...(cursor === undefined ? {} : { cursor }),
545
+ } satisfies StrategyComputationProposal,
546
+ };
547
+ }
548
+ const backendTick = strategyBackendTick(input);
549
+ if (
550
+ backendTick !== undefined
551
+ && this.lastDispatchedBackendTick !== null
552
+ && backendTick <= this.lastDispatchedBackendTick
553
+ ) {
554
+ return {
555
+ outcome: 'processed',
556
+ proposal: {
557
+ kind: 'noop',
558
+ reason: 'strategy_update_interval',
559
+ resetBeforeNextWandering: false,
560
+ generation,
561
+ parameterGeneration,
562
+ actionBarrierGeneration,
563
+ ...(actionSafetyGeneration === undefined ? {} : { actionSafetyGeneration }),
564
+ selection: structuredClone(selection),
565
+ } satisfies StrategyComputationProposal,
566
+ };
567
+ }
568
+ if (backendTick !== undefined) this.lastDispatchedBackendTick = backendTick;
569
+ const frame = strategyFrame(input, selection.parameters ?? {});
570
+ if (selection.execution === undefined) {
571
+ return {
572
+ outcome: 'processed',
573
+ proposal: {
574
+ kind: 'legacy',
575
+ generation,
576
+ parameterGeneration,
577
+ actionBarrierGeneration,
578
+ ...(actionSafetyGeneration === undefined ? {} : { actionSafetyGeneration }),
579
+ selection: structuredClone(selection),
580
+ frame,
581
+ ...(cursor === undefined ? {} : { cursor }),
582
+ } satisfies StrategyComputationProposal,
583
+ };
584
+ }
585
+
586
+ const executor = await this.ensureParallelExecutor(selection, generation, context);
587
+ this.parallelContexts.set(frame.epochId, context);
588
+ try {
589
+ if (selection.execution === 'parallel_analyze') {
590
+ if (!executor.analyze) throw new Error('strategy_parallel_analyze_handler_missing');
591
+ const analysis = structuredClone(await executor.analyze(frame, context.signal));
592
+ return {
593
+ outcome: 'processed',
594
+ proposal: {
595
+ kind: 'parallel_analyze',
596
+ generation,
597
+ parameterGeneration,
598
+ actionBarrierGeneration,
599
+ ...(actionSafetyGeneration === undefined ? {} : { actionSafetyGeneration }),
600
+ selection: structuredClone(selection),
601
+ frame,
602
+ analysis,
603
+ ...(cursor === undefined ? {} : { cursor }),
604
+ } satisfies StrategyComputationProposal,
605
+ };
606
+ }
607
+ const result = await executor.update(frame, context.signal);
608
+ return {
609
+ outcome: 'processed',
610
+ proposal: {
611
+ kind: 'parallel_compute',
612
+ generation,
613
+ parameterGeneration,
614
+ actionBarrierGeneration,
615
+ ...(actionSafetyGeneration === undefined ? {} : { actionSafetyGeneration }),
616
+ selection: structuredClone(selection),
617
+ frame,
618
+ result: structuredClone(result),
619
+ ...(cursor === undefined ? {} : { cursor }),
620
+ } satisfies StrategyComputationProposal,
621
+ };
622
+ } finally {
623
+ this.parallelContexts.delete(frame.epochId);
624
+ }
625
+ }
626
+
627
+ async commit(
628
+ input: RuntimeEpochPluginInput<Record<string, any>>,
629
+ computation: Readonly<RuntimeEpochPluginResult>,
630
+ context: RuntimeEpochPluginContext<Record<string, any>>,
631
+ ): Promise<RuntimeEpochPluginResult> {
632
+ const proposal = strategyProposal(computation.proposal);
633
+ const previousInvokedEpochSeq = this.lastInvokedEpochSeq;
634
+ this.lastInvokedEpochSeq = input.epoch.epochSeq;
635
+ if (previousInvokedEpochSeq !== null && input.epoch.epochSeq > previousInvokedEpochSeq + 1) {
636
+ this.wanderingResetRequired = true;
637
+ context.diagnostic('strategy.catchup_gap', {
638
+ previous_invoked_epoch_seq: previousInvokedEpochSeq,
639
+ current_epoch_seq: input.epoch.epochSeq,
640
+ skipped_from_epoch_seq: previousInvokedEpochSeq + 1,
641
+ skipped_through_epoch_seq: input.epoch.epochSeq - 1,
642
+ skipped_epoch_count: input.epoch.epochSeq - previousInvokedEpochSeq - 1,
643
+ }, 'debug');
644
+ }
645
+ if (proposal.kind === 'noop') {
646
+ if (proposal.selection && proposal.generation !== this.selectionGeneration) {
647
+ return { outcome: 'noop', reason: 'strategy_computation_superseded' };
648
+ }
649
+ if (proposal.resetBeforeNextWandering) this.wanderingResetRequired = true;
650
+ return {
651
+ outcome: 'noop',
652
+ reason: proposal.reason,
653
+ ...(proposal.cursor === undefined ? {} : { consumeEventsThroughCommitSeq: proposal.cursor }),
654
+ };
655
+ }
656
+ if (!proposal.selection || proposal.generation !== this.selectionGeneration) {
657
+ return { outcome: 'noop', reason: 'strategy_computation_superseded' };
658
+ }
659
+ await this.applyPendingSelection(context);
660
+ if (!this.selected || this.selectedGeneration !== proposal.generation) {
661
+ return { outcome: 'noop', reason: 'strategy_computation_superseded' };
662
+ }
663
+ await this.applyPendingControls(input, context);
664
+ if (
665
+ proposal.kind === 'parallel_analyze'
666
+ && proposal.parameterGeneration !== this.parameterGeneration
667
+ ) {
668
+ context.diagnostic('strategy.result.discarded', {
669
+ strategy_id: this.selected.id,
670
+ epoch_id: proposal.frame.epochId,
671
+ reason: 'strategy_parameters_changed_before_reduce',
672
+ }, 'debug');
673
+ return { outcome: 'noop', reason: 'strategy_parameters_changed_before_reduce' };
674
+ }
675
+
676
+ if (proposal.kind === 'legacy') {
677
+ if (!this.executor) this.executor = this.createExecutor(this.selected, context);
678
+ if (!this.executor.isAlive) {
679
+ await this.executor.start(this.selected.parameters ?? {}, context.signal);
680
+ }
681
+ if (this.wanderingResetRequired) {
682
+ await this.executor.reset(context.signal);
683
+ this.wanderingResetRequired = false;
684
+ }
685
+ this.activeContext = context;
686
+ this.activeActionOriginEpochSeq = proposal.frame.epochId;
687
+ this.activeActionSafetyGeneration = proposal.actionSafetyGeneration;
688
+ this.activeActionAllowed = this.latestFrameAllowsActions;
689
+ try {
690
+ const result = await this.executor.update(proposal.frame, context.signal);
691
+ return this.commitResult(proposal, result, context);
692
+ } finally {
693
+ this.activeContext = undefined;
694
+ this.activeActionOriginEpochSeq = undefined;
695
+ this.activeActionSafetyGeneration = undefined;
696
+ this.activeActionAllowed = false;
697
+ }
698
+ }
699
+ if (proposal.kind === 'parallel_analyze') {
700
+ if (
701
+ !this.latestFrameAllowsActions
702
+ || proposal.actionBarrierGeneration !== this.actionBarrierGeneration
703
+ ) {
704
+ context.diagnostic('strategy.result.discarded', {
705
+ strategy_id: this.selected.id,
706
+ epoch_id: proposal.frame.epochId,
707
+ reason: 'strategy_action_barrier_advanced',
708
+ }, 'debug');
709
+ return { outcome: 'noop', reason: 'strategy_action_barrier_advanced' };
710
+ }
711
+ const commitFrame = strategyFrame(input, this.selected.parameters ?? {});
712
+ const commitCursor = input.pendingEvents.at(-1)?.commitSeq;
713
+ const {
714
+ frame: _analysisFrame,
715
+ cursor: _analysisCursor,
716
+ ...proposalWithoutStaleFrame
717
+ } = proposal;
718
+ const committedProposal = {
719
+ ...proposalWithoutStaleFrame,
720
+ frame: commitFrame,
721
+ ...(commitCursor === undefined ? {} : { cursor: commitCursor }),
722
+ } satisfies Extract<StrategyComputationProposal, { kind: 'parallel_analyze' }>;
723
+ if (!this.executor) this.executor = this.createExecutor(this.selected, context);
724
+ if (!this.executor.isAlive) {
725
+ await this.executor.start(this.selected.parameters ?? {}, context.signal);
726
+ }
727
+ if (this.wanderingResetRequired) {
728
+ await this.executor.reset(context.signal);
729
+ this.wanderingResetRequired = false;
730
+ }
731
+ if (!this.executor.reduce) throw new Error('strategy_ordered_reduce_handler_missing');
732
+ this.activeContext = context;
733
+ this.activeActionOriginEpochSeq = commitFrame.epochId;
734
+ this.activeActionSafetyGeneration = proposal.actionSafetyGeneration;
735
+ this.activeActionAllowed = this.latestFrameAllowsActions
736
+ && proposal.actionBarrierGeneration === this.actionBarrierGeneration;
737
+ const reducer = this.executor;
738
+ try {
739
+ const result = await reducer.reduce!(
740
+ commitFrame,
741
+ structuredClone(proposal.analysis),
742
+ context.signal,
743
+ );
744
+ return await this.commitResult(committedProposal, result, context);
745
+ } catch (error) {
746
+ // reduce() owns persistent Goal state. Once it throws (including after
747
+ // mutating state but before returning a valid result), that state can no
748
+ // longer be trusted. Replace the worker instead of leaking a half-applied
749
+ // tick into the next ordered commit.
750
+ if (this.executor === reducer) this.executor = undefined;
751
+ try {
752
+ await reducer.stop('switched');
753
+ } catch (stopError) {
754
+ context.diagnostic('strategy.executor.stop_failed', {
755
+ strategy_id: this.selected.id,
756
+ execution: 'parallel_analyze',
757
+ error_code: diagnosticErrorCode(stopError, 'STRATEGY_EXECUTOR_STOP_FAILED'),
758
+ }, 'warn');
759
+ }
760
+ context.diagnostic('strategy.reducer.discarded', {
761
+ strategy_id: this.selected.id,
762
+ epoch_id: commitFrame.epochId,
763
+ error_code: diagnosticErrorCode(error, 'STRATEGY_REDUCER_FAILED'),
764
+ }, 'error');
765
+ throw error;
766
+ } finally {
767
+ this.activeContext = undefined;
768
+ this.activeActionOriginEpochSeq = undefined;
769
+ this.activeActionSafetyGeneration = undefined;
770
+ this.activeActionAllowed = false;
771
+ }
772
+ }
773
+ this.wanderingResetRequired = false;
774
+ return this.commitResult(proposal, proposal.result, context);
775
+ }
776
+
777
+ async stop(reason: 'segment_ending' | 'shutdown'): Promise<void> {
778
+ const executor = this.executor;
779
+ this.executor = undefined;
780
+ const parallelExecutor = this.parallelExecutor;
781
+ const parallelExecutorReady = this.parallelExecutorReady;
782
+ this.parallelExecutor = undefined;
783
+ this.parallelExecutorReady = undefined;
784
+ this.parallelExecutorLifecycle?.abort(new Error(`strategy_parallel_executor_stopped:${reason}`));
785
+ this.parallelExecutorLifecycle = undefined;
786
+ this.parallelExecutorGeneration = 0;
787
+ this.parallelContexts.clear();
788
+ this.activeContext = undefined;
789
+ this.activeActionOriginEpochSeq = undefined;
790
+ this.activeActionSafetyGeneration = undefined;
791
+ this.activeActionAllowed = false;
792
+ this.selectedActionControllerId = undefined;
793
+ this.latestFrameAllowsActions = false;
794
+ this.actionBarrierGeneration = 0;
795
+ this.wanderingResetRequired = false;
796
+ this.lastInvokedEpochSeq = null;
797
+ this.lastDispatchedBackendTick = null;
798
+ this.committedActionDedupeKeys.clear();
799
+ this.rejectAllPendingControls(
800
+ reason === 'shutdown' ? 'strategy_runtime_shutdown' : 'strategy_scope_ended',
801
+ );
802
+ if (parallelExecutor) {
803
+ try {
804
+ await parallelExecutor.stop(reason === 'shutdown' ? 'shutdown' : 'scope_ended');
805
+ } finally {
806
+ await parallelExecutorReady?.catch(() => {});
807
+ }
808
+ }
809
+ if (executor) await executor.stop(reason === 'shutdown' ? 'shutdown' : 'scope_ended');
810
+ if (reason === 'segment_ending' && this.selected && !this.defaultSelectionForRole) {
811
+ this.pendingSelection = this.selected;
812
+ this.pendingSelectionGeneration = this.selectedGeneration;
813
+ } else {
814
+ this.selected = undefined;
815
+ this.pendingSelection = undefined;
816
+ this.selectedGeneration = 0;
817
+ this.pendingSelectionGeneration = 0;
818
+ }
819
+ }
820
+
821
+ private selectDefaultForAssignedRole(
822
+ input: RuntimeEpochPluginInput<Record<string, any>>,
823
+ ): void {
824
+ if (this.selected || this.pendingSelection || !this.defaultSelectionForRole) return;
825
+ const runtimeState = input.epoch.state;
826
+ const stateRole = isClawclawRuntimeState(runtimeState)
827
+ && runtimeState.game_snapshot.status === 'fresh'
828
+ && typeof runtimeState.game_snapshot.state.you?.role === 'string'
829
+ ? runtimeState.game_snapshot.state.you.role.trim()
830
+ : '';
831
+ const assignment = [...input.pendingEvents].reverse().find((event) => (
832
+ event.type === 'role_assigned'
833
+ && typeof event.payload?.role === 'string'
834
+ && event.payload.role.trim().length > 0
835
+ ));
836
+ const role = stateRole || (typeof assignment?.payload.role === 'string'
837
+ ? assignment.payload.role.trim()
838
+ : '');
839
+ if (!role) return;
840
+ this.select(this.defaultSelectionForRole(role));
841
+ }
842
+
843
+ private async applyPendingSelection(
844
+ context: RuntimeEpochPluginContext<Record<string, any>>,
845
+ ): Promise<void> {
846
+ const pending = this.pendingSelection;
847
+ if (!pending) return;
848
+ this.pendingSelection = undefined;
849
+ const previousStrategyId = this.selected?.id;
850
+ const previousActionControllerId = this.selectedActionControllerId;
851
+ const previous = this.executor;
852
+ const previousParallel = this.parallelExecutor;
853
+ const previousParallelReady = this.parallelExecutorReady;
854
+ const previousParallelLifecycle = this.parallelExecutorLifecycle;
855
+ const keepParallel = pending.execution !== undefined
856
+ && previousParallel !== undefined
857
+ && this.parallelExecutorGeneration === this.pendingSelectionGeneration;
858
+ this.executor = undefined;
859
+ if (!keepParallel) {
860
+ this.parallelExecutor = undefined;
861
+ this.parallelExecutorReady = undefined;
862
+ this.parallelExecutorLifecycle = undefined;
863
+ this.parallelExecutorGeneration = 0;
864
+ this.parallelContexts.clear();
865
+ }
866
+ if (previous) await previous.stop('switched');
867
+ if (previousParallel && !keepParallel) {
868
+ previousParallelLifecycle?.abort(new Error('strategy_parallel_executor_switched'));
869
+ try {
870
+ await previousParallel.stop('switched');
871
+ } finally {
872
+ await previousParallelReady?.catch(() => {});
873
+ }
874
+ }
875
+ if (previousActionControllerId) {
876
+ context.capabilities.releaseActionCaller(
877
+ CLAWCLAW_ACTION_CAPABILITY,
878
+ { kind: 'strategy', id: previousActionControllerId },
879
+ 'strategy_switched',
880
+ );
881
+ }
882
+ this.selected = pending;
883
+ this.selectedGeneration = this.pendingSelectionGeneration;
884
+ this.selectedActionControllerId = strategyActionControllerId(
885
+ pending.id,
886
+ this.selectedGeneration,
887
+ );
888
+ if (pending.execution !== 'parallel_compute') {
889
+ this.executor = this.createExecutor(pending, context);
890
+ }
891
+ this.wanderingResetRequired = false;
892
+ this.committedActionDedupeKeys.clear();
893
+ context.diagnostic('strategy.selection.applied', {
894
+ strategy_id: pending.id,
895
+ ...(previousStrategyId ? { previous_strategy_id: previousStrategyId } : {}),
896
+ parameter_count: Object.keys(pending.parameters ?? {}).length,
897
+ }, 'info');
898
+ }
899
+
900
+ private async applyPendingControls(
901
+ input: RuntimeEpochPluginInput<Record<string, any>>,
902
+ context: RuntimeEpochPluginContext<Record<string, any>>,
903
+ ): Promise<void> {
904
+ const controls = this.pendingControls.splice(0);
905
+ for (const control of controls) {
906
+ const selected = this.selected;
907
+ const executor = this.executor;
908
+ context.diagnostic('strategy.control.started', {
909
+ strategy_id: control.strategyId,
910
+ revision: control.revision,
911
+ parameter_count: Object.keys(control.values).length,
912
+ }, 'info');
913
+ if (!selected || selected.id !== control.strategyId) {
914
+ context.diagnostic('strategy.control.rejected', {
915
+ strategy_id: control.strategyId,
916
+ revision: control.revision,
917
+ reason: 'strategy_switched_before_control_applied',
918
+ }, 'warn');
919
+ control.reject(new Error('strategy_switched_before_control_applied'));
920
+ continue;
921
+ }
922
+ if (control.preAppliedValues !== undefined) {
923
+ control.resolve({
924
+ accepted: true,
925
+ appliedRevision: control.revision,
926
+ effectiveValues: structuredClone(control.preAppliedValues),
927
+ strategy: selected.id,
928
+ revision: control.revision,
929
+ appliedEpochId: input.epoch.epochSeq,
930
+ });
931
+ context.diagnostic('strategy.control.completed', {
932
+ strategy_id: selected.id,
933
+ revision: control.revision,
934
+ accepted: true,
935
+ effective_parameter_count: Object.keys(control.preAppliedValues).length,
936
+ }, 'info');
937
+ continue;
938
+ }
939
+ if (selected.execution === 'parallel_compute') {
940
+ try {
941
+ validateParallelControls(selected, control.values);
942
+ const result = this.parallelExecutor?.applyControl
943
+ ? await this.parallelExecutor.applyControl({
944
+ epochId: input.epoch.epochSeq,
945
+ scope: {
946
+ sessionId: input.epoch.scope.sessionId,
947
+ segmentId: input.epoch.scope.segmentId,
948
+ },
949
+ revision: control.revision,
950
+ values: control.values,
951
+ }, context.signal)
952
+ : {
953
+ accepted: true,
954
+ appliedRevision: control.revision,
955
+ effectiveValues: {
956
+ ...(selected.parameters ?? {}),
957
+ ...control.values,
958
+ },
959
+ };
960
+ if (!result.accepted) {
961
+ control.resolve({
962
+ ...result,
963
+ strategy: selected.id,
964
+ revision: control.revision,
965
+ appliedEpochId: input.epoch.epochSeq,
966
+ });
967
+ continue;
968
+ }
969
+ const effectiveValues = result.effectiveValues ?? {
970
+ ...(selected.parameters ?? {}),
971
+ ...control.values,
972
+ };
973
+ this.selected = {
974
+ ...selected,
975
+ parameters: structuredClone(effectiveValues),
976
+ };
977
+ control.resolve({
978
+ accepted: true,
979
+ appliedRevision: result.appliedRevision ?? control.revision,
980
+ effectiveValues: structuredClone(effectiveValues),
981
+ strategy: selected.id,
982
+ revision: control.revision,
983
+ appliedEpochId: input.epoch.epochSeq,
984
+ });
985
+ context.diagnostic('strategy.control.completed', {
986
+ strategy_id: selected.id,
987
+ revision: control.revision,
988
+ accepted: true,
989
+ effective_parameter_count: Object.keys(effectiveValues).length,
990
+ }, 'info');
991
+ } catch (error) {
992
+ const failure = error instanceof Error ? error : new Error(String(error));
993
+ control.reject(failure);
994
+ context.diagnostic('strategy.control.rejected', {
995
+ strategy_id: selected.id,
996
+ revision: control.revision,
997
+ reason: diagnosticErrorCode(failure, 'INVALID_STRATEGY_CONTROL'),
998
+ }, 'warn');
999
+ }
1000
+ continue;
1001
+ }
1002
+ if (selected.execution === 'parallel_analyze') {
1003
+ if (!executor?.applyControl) {
1004
+ context.diagnostic('strategy.control.rejected', {
1005
+ strategy_id: selected.id,
1006
+ revision: control.revision,
1007
+ reason: 'strategy_controls_not_supported',
1008
+ }, 'warn');
1009
+ control.reject(new Error('strategy_controls_not_supported'));
1010
+ continue;
1011
+ }
1012
+ try {
1013
+ const result = await executor.applyControl({
1014
+ epochId: input.epoch.epochSeq,
1015
+ scope: {
1016
+ sessionId: input.epoch.scope.sessionId,
1017
+ segmentId: input.epoch.scope.segmentId,
1018
+ },
1019
+ revision: control.revision,
1020
+ values: control.values,
1021
+ }, context.signal);
1022
+ if (result.accepted) {
1023
+ const previousValues = selected.parameters ?? {};
1024
+ const effectiveValues = {
1025
+ ...previousValues,
1026
+ ...control.values,
1027
+ ...(result.effectiveValues ?? {}),
1028
+ };
1029
+ const parametersChanged = !isDeepStrictEqual(previousValues, effectiveValues);
1030
+ this.selected = {
1031
+ ...selected,
1032
+ parameters: structuredClone(effectiveValues),
1033
+ };
1034
+ if (parametersChanged) {
1035
+ this.parameterGeneration += 1;
1036
+ await this.retireParallelAnalyzerPool(context, 'strategy_parameters_changed');
1037
+ }
1038
+ }
1039
+ const effectiveValues = result.accepted
1040
+ ? this.selected?.parameters ?? selected.parameters ?? {}
1041
+ : result.effectiveValues;
1042
+ control.resolve({
1043
+ ...result,
1044
+ ...(effectiveValues === undefined
1045
+ ? {}
1046
+ : { effectiveValues: structuredClone(effectiveValues) }),
1047
+ strategy: selected.id,
1048
+ revision: control.revision,
1049
+ appliedEpochId: input.epoch.epochSeq,
1050
+ });
1051
+ context.diagnostic('strategy.control.completed', {
1052
+ strategy_id: selected.id,
1053
+ revision: control.revision,
1054
+ accepted: result.accepted,
1055
+ effective_parameter_count: Object.keys(effectiveValues ?? control.values).length,
1056
+ }, result.accepted ? 'info' : 'warn');
1057
+ } catch (error) {
1058
+ const failure = error instanceof Error ? error : new Error(String(error));
1059
+ control.reject(failure);
1060
+ context.diagnostic('strategy.control.failed', {
1061
+ strategy_id: selected.id,
1062
+ revision: control.revision,
1063
+ error_code: diagnosticErrorCode(failure, 'STRATEGY_CONTROL_FAILED'),
1064
+ }, 'error');
1065
+ }
1066
+ continue;
1067
+ }
1068
+ if (!executor?.applyControl) {
1069
+ context.diagnostic('strategy.control.rejected', {
1070
+ strategy_id: selected.id,
1071
+ revision: control.revision,
1072
+ reason: 'strategy_controls_not_supported',
1073
+ }, 'warn');
1074
+ control.reject(new Error('strategy_controls_not_supported'));
1075
+ continue;
1076
+ }
1077
+ try {
1078
+ const result = await executor.applyControl({
1079
+ epochId: input.epoch.epochSeq,
1080
+ scope: {
1081
+ sessionId: input.epoch.scope.sessionId,
1082
+ segmentId: input.epoch.scope.segmentId,
1083
+ },
1084
+ revision: control.revision,
1085
+ values: control.values,
1086
+ }, context.signal);
1087
+ if (result.accepted) {
1088
+ const effectiveValues = result.effectiveValues ?? control.values;
1089
+ this.selected = {
1090
+ ...selected,
1091
+ parameters: structuredClone({
1092
+ ...(selected.parameters ?? {}),
1093
+ ...effectiveValues,
1094
+ }),
1095
+ };
1096
+ }
1097
+ control.resolve({
1098
+ ...result,
1099
+ strategy: selected.id,
1100
+ revision: control.revision,
1101
+ appliedEpochId: input.epoch.epochSeq,
1102
+ });
1103
+ context.diagnostic('strategy.control.completed', {
1104
+ strategy_id: selected.id,
1105
+ revision: control.revision,
1106
+ accepted: result.accepted,
1107
+ effective_parameter_count: Object.keys(result.effectiveValues ?? control.values).length,
1108
+ }, result.accepted ? 'info' : 'warn');
1109
+ } catch (error) {
1110
+ const failure = error instanceof Error ? error : new Error(String(error));
1111
+ control.reject(failure);
1112
+ context.diagnostic('strategy.control.failed', {
1113
+ strategy_id: selected.id,
1114
+ revision: control.revision,
1115
+ error_code: diagnosticErrorCode(failure, 'STRATEGY_CONTROL_FAILED'),
1116
+ }, 'error');
1117
+ }
1118
+ }
1119
+ }
1120
+
1121
+ private rejectAllPendingControls(reason: string): void {
1122
+ const pending = this.pendingControls.splice(0);
1123
+ for (const control of pending) control.reject(new Error(reason));
1124
+ }
1125
+
1126
+ private async retireParallelAnalyzerPool(
1127
+ context: RuntimeEpochPluginContext<Record<string, any>>,
1128
+ reason: string,
1129
+ ): Promise<void> {
1130
+ const executor = this.parallelExecutor;
1131
+ const ready = this.parallelExecutorReady;
1132
+ const lifecycle = this.parallelExecutorLifecycle;
1133
+ this.parallelExecutor = undefined;
1134
+ this.parallelExecutorReady = undefined;
1135
+ this.parallelExecutorLifecycle = undefined;
1136
+ this.parallelExecutorGeneration = 0;
1137
+ this.parallelContexts.clear();
1138
+ if (!executor) return;
1139
+ lifecycle?.abort(new Error(reason));
1140
+ try {
1141
+ await executor.stop('switched');
1142
+ } catch (error) {
1143
+ context.diagnostic('strategy.executor.stop_failed', {
1144
+ strategy_id: this.selected?.id ?? 'unknown',
1145
+ execution: 'parallel_analyze',
1146
+ error_code: diagnosticErrorCode(error, 'STRATEGY_EXECUTOR_STOP_FAILED'),
1147
+ }, 'warn');
1148
+ } finally {
1149
+ await ready?.catch(() => {});
1150
+ }
1151
+ }
1152
+
1153
+ private createExecutor(
1154
+ selection: ClawclawStrategySelection,
1155
+ context: RuntimeEpochPluginContext<Record<string, any>>,
1156
+ ): ClawclawStrategyExecutor {
1157
+ const selectionGeneration = this.selectedGeneration;
1158
+ const actionControllerId = this.selectedActionControllerId;
1159
+ if (!actionControllerId) throw new Error('strategy_action_controller_not_active');
1160
+ return this.executorFactory(selection, {
1161
+ action: (action) => this.performAction(
1162
+ selection.id,
1163
+ selectionGeneration,
1164
+ actionControllerId,
1165
+ action,
1166
+ ),
1167
+ gameQuery: (query, frame) => this.performGameQuery(this.activeContext, query, frame),
1168
+ diagnostic: (name, attributes = {}, severity = 'debug') => {
1169
+ const diagnosticContext = this.activeContext ?? context;
1170
+ diagnosticContext.diagnostic(name, {
1171
+ strategy_id: selection.id,
1172
+ ...attributes,
1173
+ }, severity);
1174
+ },
1175
+ }, 'serial');
1176
+ }
1177
+
1178
+ private createParallelExecutor(
1179
+ selection: ClawclawStrategySelection,
1180
+ context: RuntimeEpochPluginContext<Record<string, any>>,
1181
+ ): ClawclawStrategyExecutor {
1182
+ return this.executorFactory(selection, {
1183
+ action: async () => ({
1184
+ status: 'failure',
1185
+ source: 'local',
1186
+ actionOutcome: 'not_submitted',
1187
+ error: {
1188
+ code: 'STRATEGY_PARALLEL_ACTION_MUST_BE_PROPOSED',
1189
+ message: 'Parallel strategy compute cannot submit Actions directly.',
1190
+ },
1191
+ }),
1192
+ gameQuery: (query, frame) => frame
1193
+ ? this.performGameQuery(this.parallelContexts.get(frame.epochId), query, frame)
1194
+ : Promise.resolve({
1195
+ status: 'failure' as const,
1196
+ error: {
1197
+ code: 'STRATEGY_QUERY_FRAME_MISSING',
1198
+ message: 'Parallel strategy query is missing its bound frame.',
1199
+ },
1200
+ }),
1201
+ diagnostic: (name, attributes = {}, severity = 'debug') => {
1202
+ const epochId = attributes.epoch_id;
1203
+ const diagnosticContext = typeof epochId === 'number'
1204
+ ? this.parallelContexts.get(epochId) ?? context
1205
+ : context;
1206
+ diagnosticContext.diagnostic(name, {
1207
+ strategy_id: selection.id,
1208
+ execution: selection.execution,
1209
+ ...attributes,
1210
+ }, severity);
1211
+ },
1212
+ }, 'parallel');
1213
+ }
1214
+
1215
+ private async ensureParallelExecutor(
1216
+ selection: ClawclawStrategySelection,
1217
+ generation: number,
1218
+ context: RuntimeEpochPluginContext<Record<string, any>>,
1219
+ ): Promise<ClawclawStrategyExecutor> {
1220
+ if (
1221
+ !this.parallelExecutor
1222
+ || (!this.parallelExecutor.isAlive && !this.parallelExecutorReady)
1223
+ || this.parallelExecutorGeneration !== generation
1224
+ ) {
1225
+ const previous = this.parallelExecutor;
1226
+ const previousReady = this.parallelExecutorReady;
1227
+ const previousLifecycle = this.parallelExecutorLifecycle;
1228
+ const executor = this.createParallelExecutor(selection, context);
1229
+ const lifecycle = new AbortController();
1230
+ this.parallelExecutor = executor;
1231
+ this.parallelExecutorLifecycle = lifecycle;
1232
+ this.parallelExecutorGeneration = generation;
1233
+ const ready = (async () => {
1234
+ if (previous) {
1235
+ previousLifecycle?.abort(new Error('strategy_parallel_executor_replaced'));
1236
+ let stopFailure: unknown;
1237
+ try {
1238
+ await previous.stop('switched');
1239
+ } catch (error) {
1240
+ stopFailure = error;
1241
+ }
1242
+ // A superseded transition can own an even older pool. Its ready task
1243
+ // does not settle until that older pool is fully retired.
1244
+ await previousReady?.catch(() => {});
1245
+ if (stopFailure !== undefined) throw stopFailure;
1246
+ }
1247
+ await executor.start(selection.parameters ?? {}, lifecycle.signal);
1248
+ })();
1249
+ this.parallelExecutorReady = ready;
1250
+ void ready.then(
1251
+ () => {
1252
+ if (this.parallelExecutor === executor && this.parallelExecutorReady === ready) {
1253
+ this.parallelExecutorReady = undefined;
1254
+ }
1255
+ },
1256
+ () => {
1257
+ if (this.parallelExecutor === executor && this.parallelExecutorReady === ready) {
1258
+ this.parallelExecutorReady = undefined;
1259
+ }
1260
+ },
1261
+ );
1262
+ }
1263
+ const expected = this.parallelExecutor;
1264
+ const ready = this.parallelExecutorReady;
1265
+ try {
1266
+ if (ready) await awaitWithAbort(ready, context.signal);
1267
+ } catch (error) {
1268
+ if (context.signal.aborted) throw error;
1269
+ if (this.parallelExecutor === expected) {
1270
+ this.parallelExecutorLifecycle?.abort(new Error('strategy_parallel_executor_start_failed'));
1271
+ this.parallelExecutor = undefined;
1272
+ this.parallelExecutorReady = undefined;
1273
+ this.parallelExecutorLifecycle = undefined;
1274
+ this.parallelExecutorGeneration = 0;
1275
+ try {
1276
+ await expected.stop('switched');
1277
+ } catch (stopError) {
1278
+ context.diagnostic('strategy.executor.stop_failed', {
1279
+ strategy_id: selection.id,
1280
+ execution: selection.execution,
1281
+ error_code: diagnosticErrorCode(stopError, 'STRATEGY_EXECUTOR_STOP_FAILED'),
1282
+ }, 'warn');
1283
+ }
1284
+ }
1285
+ throw error;
1286
+ }
1287
+ if (
1288
+ !this.parallelExecutor
1289
+ || !this.parallelExecutor.isAlive
1290
+ || this.parallelExecutorGeneration !== generation
1291
+ ) {
1292
+ throw new Error('strategy_parallel_executor_superseded');
1293
+ }
1294
+ return this.parallelExecutor;
1295
+ }
1296
+
1297
+ private async commitResult(
1298
+ proposal: Extract<StrategyComputationProposal, {
1299
+ kind: 'legacy' | 'parallel_compute' | 'parallel_analyze';
1300
+ }>,
1301
+ result: StrategyResult,
1302
+ context: RuntimeEpochPluginContext<Record<string, any>>,
1303
+ ): Promise<RuntimeEpochPluginResult> {
1304
+ const selection = this.selected!;
1305
+ const validated = structuredClone(result);
1306
+ if (validated.states !== undefined && !Array.isArray(validated.states)) {
1307
+ throw new Error('strategy_states_invalid');
1308
+ }
1309
+ for (const state of validated.states ?? []) {
1310
+ if (
1311
+ !state
1312
+ || typeof state !== 'object'
1313
+ || typeof state.topic !== 'string'
1314
+ || !this.produces.states?.includes(state.topic)
1315
+ ) throw new Error('strategy_state_output_invalid');
1316
+ }
1317
+ if (validated.events !== undefined && !Array.isArray(validated.events)) {
1318
+ throw new Error('strategy_events_invalid');
1319
+ }
1320
+ for (const event of validated.events ?? []) {
1321
+ if (
1322
+ !event
1323
+ || typeof event !== 'object'
1324
+ || typeof event.type !== 'string'
1325
+ || !this.produces.events?.includes(event.type)
1326
+ || !event.payload
1327
+ || typeof event.payload !== 'object'
1328
+ || Array.isArray(event.payload)
1329
+ || (event.dedupeKey !== undefined && typeof event.dedupeKey !== 'string')
1330
+ || (event.occurredAt !== undefined && typeof event.occurredAt !== 'string')
1331
+ ) throw new Error('strategy_event_output_invalid');
1332
+ }
1333
+ if (validated.actions !== undefined && !Array.isArray(validated.actions)) {
1334
+ throw new Error('strategy_actions_invalid');
1335
+ }
1336
+ const actions = (validated.actions ?? []).map((candidate) => {
1337
+ if (
1338
+ !candidate
1339
+ || typeof candidate !== 'object'
1340
+ || !candidate.action
1341
+ || typeof candidate.action !== 'object'
1342
+ || Array.isArray(candidate.action)
1343
+ || (candidate.dedupeKey !== undefined && typeof candidate.dedupeKey !== 'string')
1344
+ ) throw new Error('strategy_action_proposal_invalid');
1345
+ return {
1346
+ candidate,
1347
+ request: normalizeClawclawStrategyAction(
1348
+ candidate.action,
1349
+ proposal.frame.epochId,
1350
+ proposal.actionSafetyGeneration,
1351
+ ),
1352
+ };
1353
+ });
1354
+ const actionControllerId = this.selectedActionControllerId;
1355
+ if (actions.length > 0 && !actionControllerId) {
1356
+ throw new Error('strategy_action_controller_not_active');
1357
+ }
1358
+ if (
1359
+ actions.length > 0
1360
+ && (
1361
+ !this.latestFrameAllowsActions
1362
+ || proposal.generation !== this.selectionGeneration
1363
+ || proposal.actionBarrierGeneration !== this.actionBarrierGeneration
1364
+ )
1365
+ ) {
1366
+ context.diagnostic('strategy.result.discarded', {
1367
+ strategy_id: selection.id,
1368
+ epoch_id: proposal.frame.epochId,
1369
+ reason: 'strategy_action_barrier_advanced',
1370
+ }, 'debug');
1371
+ return { outcome: 'noop', reason: 'strategy_action_barrier_advanced' };
1372
+ }
1373
+ let anEarlierActionMayHaveBeenSubmitted = false;
1374
+ for (const [actionIndex, { candidate, request }] of actions.entries()) {
1375
+ if (candidate.dedupeKey && this.committedActionDedupeKeys.has(candidate.dedupeKey)) {
1376
+ context.diagnostic('strategy.action.deduplicated', {
1377
+ strategy_id: selection.id,
1378
+ epoch_id: proposal.frame.epochId,
1379
+ dedupe_key: candidate.dedupeKey,
1380
+ }, 'debug');
1381
+ continue;
1382
+ }
1383
+ try {
1384
+ const actionResult = await context.capabilities.performAction(
1385
+ CLAWCLAW_ACTION_CAPABILITY,
1386
+ request,
1387
+ { kind: 'strategy', id: actionControllerId! },
1388
+ );
1389
+ if (isStaleStrategyActionResult(actionResult)) {
1390
+ if (!anEarlierActionMayHaveBeenSubmitted) {
1391
+ context.diagnostic('strategy.result.discarded', {
1392
+ strategy_id: selection.id,
1393
+ epoch_id: proposal.frame.epochId,
1394
+ reason: 'strategy_action_safety_superseded',
1395
+ }, 'debug');
1396
+ return { outcome: 'noop', reason: 'strategy_action_safety_superseded' };
1397
+ }
1398
+ context.diagnostic('strategy.action.batch_truncated', {
1399
+ strategy_id: selection.id,
1400
+ epoch_id: proposal.frame.epochId,
1401
+ reason: 'strategy_action_safety_superseded',
1402
+ rejected_action_index: actionIndex,
1403
+ skipped_action_count: actions.length - actionIndex - 1,
1404
+ }, 'debug');
1405
+ break;
1406
+ }
1407
+ if (actionResult.actionOutcome !== 'not_submitted') {
1408
+ anEarlierActionMayHaveBeenSubmitted = true;
1409
+ }
1410
+ if (
1411
+ candidate.dedupeKey
1412
+ && (actionResult.status === 'success' || actionResult.status === 'partial')
1413
+ ) {
1414
+ this.committedActionDedupeKeys.set(candidate.dedupeKey, proposal.frame.epochId);
1415
+ while (this.committedActionDedupeKeys.size > 2_048) {
1416
+ const oldest = this.committedActionDedupeKeys.keys().next().value as string | undefined;
1417
+ if (oldest === undefined) break;
1418
+ this.committedActionDedupeKeys.delete(oldest);
1419
+ }
1420
+ }
1421
+ } catch (error) {
1422
+ // A throwing capability cannot prove that submission never started. Keep
1423
+ // the rest of this commit observable instead of hiding a possible effect.
1424
+ anEarlierActionMayHaveBeenSubmitted = true;
1425
+ context.diagnostic('strategy.action.failed', {
1426
+ strategy_id: selection.id,
1427
+ epoch_id: proposal.frame.epochId,
1428
+ error_code: diagnosticErrorCode(error, 'STRATEGY_ACTION_FAILED'),
1429
+ }, 'error');
1430
+ }
1431
+ }
1432
+ return {
1433
+ outcome: 'processed',
1434
+ states: validated.states?.map((state) => ({
1435
+ topic: state.topic,
1436
+ value: hostedStrategyState(state.topic, state.value, selection),
1437
+ })),
1438
+ events: validated.events?.map((event, index) => ({
1439
+ type: event.type,
1440
+ dedupeKey: event.dedupeKey
1441
+ ?? `${selection.id}:${proposal.frame.tick ?? proposal.frame.epochId}:${event.type}:${index}`,
1442
+ payload: { ...event.payload },
1443
+ ...(event.occurredAt ? { occurredAt: event.occurredAt } : {}),
1444
+ })),
1445
+ ...(proposal.cursor === undefined ? {} : { consumeEventsThroughCommitSeq: proposal.cursor }),
1446
+ };
1447
+ }
1448
+
1449
+ private async performAction(
1450
+ strategyId: string,
1451
+ selectionGeneration: number,
1452
+ actionControllerId: string,
1453
+ action: Record<string, unknown>,
1454
+ ): Promise<StrategyActionAck> {
1455
+ const context = this.activeContext;
1456
+ if (
1457
+ this.selected?.id !== strategyId
1458
+ || this.selectedGeneration !== selectionGeneration
1459
+ || this.selectedActionControllerId !== actionControllerId
1460
+ ) {
1461
+ return {
1462
+ status: 'deferred',
1463
+ source: 'local',
1464
+ actionOutcome: 'not_submitted',
1465
+ error: {
1466
+ code: 'STRATEGY_GENERATION_SUPERSEDED',
1467
+ message: 'The Strategy Action belongs to a replaced strategy generation.',
1468
+ },
1469
+ };
1470
+ }
1471
+ if (!context || context.signal.aborted || !this.activeActionAllowed) {
1472
+ return {
1473
+ status: 'deferred',
1474
+ error: {
1475
+ code: this.activeActionAllowed ? 'STRATEGY_UPDATE_NOT_ACTIVE' : 'STRATEGY_NOT_WANDERING',
1476
+ message: this.activeActionAllowed
1477
+ ? 'The strategy update is no longer active.'
1478
+ : 'Strategy Actions are only available during the wandering phase.',
1479
+ },
1480
+ };
1481
+ }
1482
+ const result = await context.capabilities.performAction(
1483
+ CLAWCLAW_ACTION_CAPABILITY,
1484
+ normalizeClawclawStrategyAction(
1485
+ action,
1486
+ this.activeActionOriginEpochSeq!,
1487
+ this.activeActionSafetyGeneration,
1488
+ ),
1489
+ { kind: 'strategy', id: actionControllerId },
1490
+ );
1491
+ const ack = {
1492
+ status: result.status,
1493
+ actionId: result.actionId,
1494
+ ...(result.source === undefined ? {} : { source: result.source }),
1495
+ ...(result.actionOutcome === undefined ? {} : { actionOutcome: result.actionOutcome }),
1496
+ ...(result.value === undefined ? {} : { value: result.value }),
1497
+ ...(result.error === undefined ? {} : { error: result.error }),
1498
+ };
1499
+ return ack;
1500
+ }
1501
+
1502
+ private async performGameQuery(
1503
+ context: RuntimeEpochPluginContext<Record<string, any>> | undefined,
1504
+ query: StrategyGameQuery,
1505
+ frame?: StrategyFrame<Record<string, unknown>>,
1506
+ ): Promise<StrategyGameQueryResult> {
1507
+ if (!context || context.signal.aborted) {
1508
+ return {
1509
+ status: 'failure',
1510
+ error: {
1511
+ code: 'STRATEGY_UPDATE_NOT_ACTIVE',
1512
+ message: 'The strategy update is no longer active.',
1513
+ },
1514
+ };
1515
+ }
1516
+ try {
1517
+ if (query.kind === 'tasks') {
1518
+ if (frame) {
1519
+ const tasks = clawclawTasksFromGameState(frame.state);
1520
+ if (tasks === null) throw new Error('authoritative_tasks_unavailable');
1521
+ return { status: 'success', value: tasks };
1522
+ }
1523
+ const observed = await context.capabilities.queryObservation<unknown, unknown>(
1524
+ CLAWCLAW_TASKS_CAPABILITY,
1525
+ {},
1526
+ );
1527
+ return { status: 'success', value: observed.value };
1528
+ }
1529
+ if (query.kind === 'map') {
1530
+ if (frame) {
1531
+ return { status: 'success', value: clawclawMapFromGameState(frame.state) };
1532
+ }
1533
+ const observed = await context.capabilities.queryObservation<unknown, unknown>(
1534
+ CLAWCLAW_MAP_CAPABILITY,
1535
+ {},
1536
+ );
1537
+ return { status: 'success', value: observed.value };
1538
+ }
1539
+ const observed = await context.capabilities.queryObservation<
1540
+ ClawclawPathDistanceRequest,
1541
+ number | null
1542
+ >(CLAWCLAW_PATH_DISTANCE_CAPABILITY, {
1543
+ from: query.from,
1544
+ to: query.to,
1545
+ });
1546
+ return { status: 'success', value: observed.value };
1547
+ } catch (error) {
1548
+ return {
1549
+ status: 'failure',
1550
+ error: {
1551
+ code: 'STRATEGY_GAME_QUERY_FAILED',
1552
+ message: error instanceof Error ? error.message : String(error),
1553
+ },
1554
+ };
1555
+ }
1556
+ }
1557
+ }