@myclaw163/clawclaw-cli 0.7.15 → 0.8.1

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