@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,1324 @@
1
+ import { normalizeGameState } from '../../lib/normalize.js';
2
+ import { CorpseMemory } from '../../strategies/game-utils.js';
3
+ import { HIDE_SPOTS } from '../../strategies/hide-spots.js';
4
+ import {
5
+ buildRouteEvidence,
6
+ type RouteEvidence,
7
+ } from '../../strategies/pathfind/escape-planner.js';
8
+ import type {
9
+ BehaviorDecision,
10
+ CustomModule,
11
+ RoomTarget,
12
+ Strategy,
13
+ StrategyContext,
14
+ StrategyIntent,
15
+ StrategyIntentActivity,
16
+ } from '../../strategies/types.js';
17
+ import type {
18
+ EmergencyInfo,
19
+ GameState,
20
+ TaskInfo,
21
+ } from '../types.js';
22
+
23
+ export const STRATEGY_PLUGIN_API_VERSION = 1 as const;
24
+
25
+ export interface StrategyScope {
26
+ readonly sessionId: string;
27
+ readonly segmentId: string;
28
+ }
29
+
30
+ export interface StrategyEvent {
31
+ readonly eventId: string;
32
+ readonly epochId?: number;
33
+ readonly type: string;
34
+ readonly occurredAt: string;
35
+ readonly payload: Readonly<Record<string, unknown>>;
36
+ }
37
+
38
+ export interface StrategyFrame<TState = Record<string, unknown>> {
39
+ readonly epochId: number;
40
+ readonly scope: Readonly<StrategyScope>;
41
+ readonly stage: string;
42
+ readonly tick?: number;
43
+ readonly state: Readonly<TState> | null;
44
+ /** Same-epoch State proposals from completed dependencies, keyed by topic. */
45
+ readonly upstreamStates: Readonly<Record<string, unknown>>;
46
+ readonly events: readonly StrategyEvent[];
47
+ readonly parameters: Readonly<Record<string, unknown>>;
48
+ }
49
+
50
+ export interface StrategyControlSpec {
51
+ readonly id: string;
52
+ readonly type: 'string' | 'boolean' | 'number' | 'enum' | 'player_refs' | 'string_list';
53
+ readonly description: string;
54
+ readonly values?: readonly string[];
55
+ readonly default?: unknown;
56
+ }
57
+
58
+ export interface StrategyControlUpdate {
59
+ readonly epochId: number;
60
+ readonly scope: Readonly<StrategyScope>;
61
+ readonly revision: number;
62
+ readonly values: Readonly<Record<string, unknown>>;
63
+ }
64
+
65
+ export interface StrategyControlResult {
66
+ readonly accepted: boolean;
67
+ readonly appliedRevision?: number;
68
+ readonly effectiveValues?: Readonly<Record<string, unknown>>;
69
+ readonly message?: string;
70
+ }
71
+
72
+ export interface StrategyActionAck<T = unknown> {
73
+ readonly status: 'success' | 'partial' | 'deferred' | 'failure';
74
+ readonly value?: T;
75
+ readonly error?: unknown;
76
+ /** Stable action identity supplied by the runtime when available. */
77
+ readonly actionId?: string;
78
+ /** Layer that determined the action result. */
79
+ readonly source?: 'backend' | 'transport' | 'protocol' | 'local';
80
+ /** Whether the backend confirmed the action, it was not submitted, or delivery is unknown. */
81
+ readonly actionOutcome?: 'confirmed' | 'not_submitted' | 'unknown';
82
+ }
83
+
84
+ export interface StrategyPoint {
85
+ readonly x: number;
86
+ readonly y: number;
87
+ }
88
+
89
+ export interface ClawclawStrategyTask extends StrategyPoint {
90
+ readonly name: string;
91
+ readonly room: string;
92
+ readonly status: string;
93
+ readonly is_fake_shrimp?: boolean;
94
+ readonly task_note?: string;
95
+ }
96
+
97
+ export interface ClawclawStrategyTaskLocation extends StrategyPoint {
98
+ readonly name: string;
99
+ readonly room?: string;
100
+ readonly faction?: 'lobster' | 'crab';
101
+ }
102
+
103
+ export interface ClawclawStrategyMapInfo {
104
+ readonly rooms: readonly {
105
+ readonly name: string;
106
+ readonly polygon: readonly (readonly [number, number])[];
107
+ }[];
108
+ readonly all_players: readonly {
109
+ readonly name: string;
110
+ readonly seat: number;
111
+ }[];
112
+ /** Omitted when CCL cannot obtain a current `you.tasks` projection. */
113
+ readonly your_tasks?: readonly ClawclawStrategyTask[];
114
+ readonly all_task_locations: readonly ClawclawStrategyTaskLocation[];
115
+ }
116
+
117
+ export interface ClawclawStrategyPlayerRef {
118
+ readonly seat: number;
119
+ readonly name: string;
120
+ }
121
+
122
+ export interface ClawclawStrategyPlayerActivity {
123
+ readonly kind: 'idle' | 'moving' | 'task';
124
+ readonly task_name?: string;
125
+ readonly remaining_secs?: number;
126
+ }
127
+
128
+ export interface ClawclawStrategySelf extends StrategyPoint {
129
+ readonly player: Readonly<ClawclawStrategyPlayerRef>;
130
+ readonly room: string;
131
+ readonly role: string;
132
+ readonly faction: string;
133
+ readonly is_alive: boolean;
134
+ readonly completed_task_count?: number;
135
+ readonly kill_cooldown_secs?: number;
136
+ readonly kills_remaining?: number | null;
137
+ readonly activity: Readonly<ClawclawStrategyPlayerActivity>;
138
+ readonly crab_teammates?: readonly ClawclawStrategyPlayerRef[];
139
+ }
140
+
141
+ export interface ClawclawStrategyVisiblePlayer extends StrategyPoint {
142
+ readonly player: Readonly<ClawclawStrategyPlayerRef>;
143
+ readonly room: string;
144
+ readonly distance?: number;
145
+ }
146
+
147
+ export interface ClawclawStrategyCorpse extends StrategyPoint {
148
+ readonly player: Readonly<ClawclawStrategyPlayerRef>;
149
+ readonly room: string;
150
+ readonly distance: number;
151
+ }
152
+
153
+ export interface ClawclawStrategyKnownPlayer extends ClawclawStrategyPlayerRef {
154
+ readonly known_status: Readonly<{
155
+ readonly is_alive?: boolean;
156
+ readonly death_cause?: 'killed' | 'exiled' | 'self_destruct';
157
+ readonly reported_in_current_meeting?: boolean;
158
+ }>;
159
+ }
160
+
161
+ export interface ClawclawStrategyEmergency extends StrategyPoint {
162
+ readonly active: boolean;
163
+ readonly task_name: string;
164
+ readonly room: string;
165
+ readonly remaining_secs?: number | null;
166
+ }
167
+
168
+ export interface ClawclawStrategyCrabSabotage {
169
+ readonly status:
170
+ | 'unprepared'
171
+ | 'ready'
172
+ | 'cooldown_unprepared'
173
+ | 'cooldown_charged'
174
+ | 'emergency_active';
175
+ readonly cooldown_remaining_secs?: number;
176
+ }
177
+
178
+ export interface ClawclawStrategyGameState {
179
+ readonly phase?: string;
180
+ readonly tick?: number;
181
+ readonly you?: ClawclawStrategySelf;
182
+ readonly players?: readonly ClawclawStrategyKnownPlayer[];
183
+ readonly visible_players?: readonly ClawclawStrategyVisiblePlayer[];
184
+ readonly visible_corpses?: readonly ClawclawStrategyCorpse[];
185
+ readonly task_progress?: Readonly<{ completed: number; goal: number }>;
186
+ readonly alive_count?: number;
187
+ readonly emergency?: Readonly<ClawclawStrategyEmergency>;
188
+ readonly crab_sabotage?: Readonly<ClawclawStrategyCrabSabotage>;
189
+ readonly meeting?: Readonly<Record<string, unknown>>;
190
+ readonly winner?: string | null;
191
+ readonly settlement?: Readonly<Record<string, unknown>>;
192
+ readonly [key: string]: unknown;
193
+ }
194
+
195
+ interface ClawclawStrategyActionBase {
196
+ readonly thinking_content?: string;
197
+ }
198
+
199
+ export type ClawclawStrategyAction =
200
+ | (ClawclawStrategyActionBase & {
201
+ readonly action: 'move';
202
+ readonly target: string;
203
+ readonly target_x?: never;
204
+ readonly target_y?: never;
205
+ readonly stop_on_player?: boolean;
206
+ })
207
+ | (ClawclawStrategyActionBase & {
208
+ readonly action: 'move';
209
+ readonly target?: never;
210
+ readonly target_x: number;
211
+ readonly target_y: number;
212
+ readonly stop_on_player?: boolean;
213
+ })
214
+ | (ClawclawStrategyActionBase & { readonly action: 'kill'; readonly target: string })
215
+ | (ClawclawStrategyActionBase & { readonly action: 'speech'; readonly text: string })
216
+ | (ClawclawStrategyActionBase & { readonly action: 'vote'; readonly target: string })
217
+ | (ClawclawStrategyActionBase & { readonly action: 'task'; readonly task_name?: string })
218
+ | (ClawclawStrategyActionBase & { readonly action: 'report' })
219
+ | (ClawclawStrategyActionBase & { readonly action: 'think' })
220
+ | (ClawclawStrategyActionBase & { readonly action: 'trigger_alarm' });
221
+
222
+ export interface StrategyGameApi {
223
+ /** Current tasks assigned to this player. Prefer this over getMap() for task planning. */
224
+ getTasks(): Promise<readonly ClawclawStrategyTask[]>;
225
+ /** Player-scoped map and current task assignment from CCL's trusted game adapter. */
226
+ getMap(): Promise<Readonly<ClawclawStrategyMapInfo> | null>;
227
+ /** Local A* route distance over the packaged walkability grid; null means unreachable. */
228
+ pathDistance(from: StrategyPoint, to: StrategyPoint): Promise<number | null>;
229
+ }
230
+
231
+ export interface StrategyApi<TAction = Record<string, unknown>> {
232
+ readonly action: {
233
+ submit<T = unknown>(action: TAction): Promise<StrategyActionAck<T>>;
234
+ };
235
+ readonly game: StrategyGameApi;
236
+ }
237
+
238
+ export interface StrategyStateProposal {
239
+ readonly topic: string;
240
+ readonly value: unknown;
241
+ }
242
+
243
+ export interface StrategyEventProposal {
244
+ readonly type: string;
245
+ readonly payload: Readonly<Record<string, unknown>>;
246
+ readonly occurredAt?: string;
247
+ /** Stable semantic identity when parallel computations can observe the same input Event. */
248
+ readonly dedupeKey?: string;
249
+ }
250
+
251
+ export interface StrategyActionProposal<TAction = Record<string, unknown>> {
252
+ /** Executed by Strategy Plugin only after this computation reaches ordered commit. */
253
+ readonly action: TAction;
254
+ /** Optional stable identity used to suppress the same proposal from overlapping frames. */
255
+ readonly dedupeKey?: string;
256
+ }
257
+
258
+ export interface StrategyResult<TAction = Record<string, unknown>> {
259
+ readonly states?: readonly StrategyStateProposal[];
260
+ readonly events?: readonly StrategyEventProposal[];
261
+ /** Parallel-compute strategies propose Actions; compute() never submits them directly. */
262
+ readonly actions?: readonly StrategyActionProposal<TAction>[];
263
+ }
264
+
265
+ export type ClawclawStrategyActivity = StrategyIntentActivity;
266
+
267
+ /** Recommended semantic value for the `strategy.status` State topic. */
268
+ export interface ClawclawStrategyStatusState {
269
+ readonly activity: ClawclawStrategyActivity;
270
+ /** Human-readable intent for the Agent; do not use coordinates as the explanation. */
271
+ readonly summary: string;
272
+ /** Filled by the trusted host so Agent state identifies its active strategy. */
273
+ readonly strategy?: string;
274
+ /** Filled by the trusted host with the current effective control parameters. */
275
+ readonly parameters?: Readonly<Record<string, unknown>>;
276
+ readonly room?: string;
277
+ readonly task?: string;
278
+ readonly targetPlayer?: string;
279
+ readonly dataAvailability?: Readonly<{
280
+ readonly tasks?: 'available' | 'unavailable';
281
+ }>;
282
+ }
283
+
284
+ export type WanderingStrategyFrame<
285
+ TState extends ClawclawStrategyGameState = ClawclawStrategyGameState,
286
+ > = Omit<StrategyFrame<TState>, 'stage' | 'state'> & {
287
+ readonly stage: 'game';
288
+ readonly state: Readonly<TState & { readonly phase: 'wandering' }>;
289
+ };
290
+
291
+ export interface ClawclawStrategyManifest {
292
+ readonly id: string;
293
+ readonly name: string;
294
+ readonly description: string;
295
+ readonly controls?: readonly StrategyControlSpec[];
296
+ /** Omitted means the stateful, serial update() compatibility contract. */
297
+ readonly execution?: 'parallel_compute' | 'parallel_analyze';
298
+ }
299
+
300
+ /**
301
+ * Canonical authoring surface for ClawClaw strategies.
302
+ *
303
+ * Strategy Plugin creates the instance and calls update() only for fresh
304
+ * wandering epochs. Lifecycle gating does not run inside third-party code.
305
+ */
306
+ export abstract class ClawclawStrategy<
307
+ TState extends ClawclawStrategyGameState = ClawclawStrategyGameState,
308
+ TAction = ClawclawStrategyAction,
309
+ > {
310
+ static readonly apiVersion = STRATEGY_PLUGIN_API_VERSION;
311
+ static readonly manifest?: ClawclawStrategyManifest;
312
+
313
+ protected readonly parameters: Readonly<Record<string, unknown>>;
314
+
315
+ constructor(parameters: Readonly<Record<string, unknown>> = {}) {
316
+ this.parameters = Object.freeze(structuredClone(parameters));
317
+ }
318
+
319
+ /** The only required strategy callback. Runtime supplies fresh wandering input. */
320
+ abstract update(
321
+ frame: WanderingStrategyFrame<TState>,
322
+ api: StrategyApi<TAction>,
323
+ ): StrategyResult<TAction> | void | Promise<StrategyResult<TAction> | void>;
324
+
325
+ /** Produce the one semantic State understood by the ClawClaw Agent surface. */
326
+ protected status(value: ClawclawStrategyStatusState): StrategyResult<TAction> {
327
+ return { states: [{ topic: 'strategy.status', value }] };
328
+ }
329
+ }
330
+
331
+ /**
332
+ * Stateless strategy surface for cross-tick parallel computation.
333
+ *
334
+ * Runtime creates a fresh instance for each compute. There is deliberately
335
+ * no Action submit API here: return Action proposals and let Strategy Plugin
336
+ * execute them later in ordered commit. Authoritative results arrive through a
337
+ * later State frame, exactly like other game Actions.
338
+ */
339
+ export abstract class ClawclawComputeStrategy<
340
+ TState extends ClawclawStrategyGameState = ClawclawStrategyGameState,
341
+ TAction = ClawclawStrategyAction,
342
+ > extends ClawclawStrategy<TState, TAction> {
343
+ abstract compute(
344
+ frame: WanderingStrategyFrame<TState>,
345
+ game: StrategyGameApi,
346
+ ): StrategyResult<TAction> | void | Promise<StrategyResult<TAction> | void>;
347
+
348
+ override update(
349
+ frame: WanderingStrategyFrame<TState>,
350
+ api: StrategyApi<TAction>,
351
+ ): StrategyResult<TAction> | void | Promise<StrategyResult<TAction> | void> {
352
+ return this.compute(frame, api.game);
353
+ }
354
+ }
355
+
356
+ /**
357
+ * Hybrid surface for stateful strategies with an expensive, pure analysis phase.
358
+ *
359
+ * analyze() may run concurrently for different epochs on fresh instances.
360
+ * reduce() runs on one persistent instance in epoch order and is the only phase
361
+ * allowed to mutate Goal state or submit Actions. The serial compatibility path
362
+ * calls the same two methods back-to-back. Finishing analyze() does not promise
363
+ * a reduce() call: CCL may discard a buffered analysis before reduce when that
364
+ * epoch falls outside the bounded catch-up window.
365
+ */
366
+ export abstract class ClawclawHybridStrategy<
367
+ TAnalysis,
368
+ TState extends ClawclawStrategyGameState = ClawclawStrategyGameState,
369
+ TAction = ClawclawStrategyAction,
370
+ > extends ClawclawStrategy<TState, TAction> {
371
+ abstract analyze(
372
+ frame: WanderingStrategyFrame<TState>,
373
+ game: StrategyGameApi,
374
+ ): TAnalysis | Promise<TAnalysis>;
375
+
376
+ abstract reduce(
377
+ frame: WanderingStrategyFrame<TState>,
378
+ analysis: Readonly<TAnalysis>,
379
+ api: StrategyApi<TAction>,
380
+ ): StrategyResult<TAction> | void | Promise<StrategyResult<TAction> | void>;
381
+
382
+ override async update(
383
+ frame: WanderingStrategyFrame<TState>,
384
+ api: StrategyApi<TAction>,
385
+ ): Promise<StrategyResult<TAction> | void> {
386
+ const analysis = await this.analyze(frame, api.game);
387
+ return this.reduce(frame, analysis, api);
388
+ }
389
+ }
390
+
391
+ const RECENT_KILL_IGNORE_MS = 3_000;
392
+ const MOVE_DEDUPE_MS = 15_000;
393
+ const NON_IDEMPOTENT_ACTIONS = new Set(['kill', 'report', 'speech', 'trigger_alarm', 'task']);
394
+ const AUTHORITY_ACK_ACTIONS = new Set(['kill', 'report', 'trigger_alarm', 'task']);
395
+
396
+ export function clawclawStrategyStringList(
397
+ parameters: Readonly<Record<string, unknown>>,
398
+ controlId: string,
399
+ ): string[] {
400
+ const value = parameters[controlId];
401
+ return Array.isArray(value)
402
+ ? value.filter((entry): entry is string => typeof entry === 'string')
403
+ : [];
404
+ }
405
+
406
+ export function clawclawStrategyString(
407
+ parameters: Readonly<Record<string, unknown>>,
408
+ controlId: string,
409
+ ): string {
410
+ const value = parameters[controlId];
411
+ return typeof value === 'string' ? value : '';
412
+ }
413
+
414
+ export interface ClawclawGoalStrategyOptions {
415
+ readonly id: string;
416
+ readonly requiresTasks?: boolean;
417
+ /** Defaults to true. Task-only strategies can avoid copying the static map every epoch. */
418
+ readonly requiresMap?: boolean;
419
+ readonly sidecarSpeech?: boolean;
420
+ /** Static target groups whose current-frame A* routes should be analyzed off-thread. */
421
+ readonly routeEvidenceTargets?: readonly ('tasks' | 'rooms' | 'hide')[];
422
+ /** Return a user-facing reason when named controls are not ready yet. */
423
+ readonly validateParameters?: (parameters: Readonly<Record<string, unknown>>) => string | undefined;
424
+ readonly create: (parameters: Readonly<Record<string, unknown>>) => Strategy;
425
+ }
426
+
427
+ export interface ClawclawGoalStrategyAnalysis {
428
+ readonly resources?: Readonly<{
429
+ readonly tasks: readonly ClawclawStrategyTask[] | null;
430
+ readonly tasksAvailable: boolean;
431
+ readonly map?: Readonly<ClawclawStrategyMapInfo>;
432
+ }>;
433
+ readonly routeEvidence?: Readonly<RouteEvidence> | null;
434
+ }
435
+
436
+ function sameControlValue(left: unknown, right: unknown): boolean {
437
+ if (Object.is(left, right)) return true;
438
+ if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false;
439
+ return left.every((value, index) => Object.is(value, right[index]));
440
+ }
441
+
442
+ function frameEvents(frame: WanderingStrategyFrame): Record<string, any>[] {
443
+ return frame.events.map((event) => {
444
+ const payload = event.payload as Record<string, any>;
445
+ const actor = projectedPlayerRef(payload.actor);
446
+ const target = projectedPlayerRef(payload.target);
447
+ const killer = projectedPlayerRef(payload.killer);
448
+ return {
449
+ ...payload,
450
+ type: event.type,
451
+ ...(typeof actor.name === 'string' ? { actor_name: actor.name } : {}),
452
+ ...(typeof target.name === 'string' ? { target_name: target.name } : {}),
453
+ ...(typeof killer.name === 'string' ? { killer_name: killer.name } : {}),
454
+ ...(event.type === 'corpse_spotted' ? {
455
+ ...(typeof target.name === 'string' ? { corpse_name: target.name } : {}),
456
+ ...(typeof payload.room === 'string' ? { corpse_room: payload.room } : {}),
457
+ ...(Number.isFinite(Number(payload.x)) ? { corpse_x: Number(payload.x) } : {}),
458
+ ...(Number.isFinite(Number(payload.y)) ? { corpse_y: Number(payload.y) } : {}),
459
+ } : {}),
460
+ };
461
+ });
462
+ }
463
+
464
+ function projectedPlayerRef(value: unknown): Record<string, any> {
465
+ return value && typeof value === 'object' && !Array.isArray(value)
466
+ ? value as Record<string, any>
467
+ : {};
468
+ }
469
+
470
+ /** Project the documented GameSync v2 player view into the npm Goal contract. */
471
+ function projectGoalGameState(
472
+ source: Readonly<ClawclawStrategyGameState>,
473
+ events: readonly Record<string, any>[],
474
+ ): GameState {
475
+ const raw = source as Readonly<Record<string, any>>;
476
+ const rawYou = projectedPlayerRef(raw.you);
477
+ const self = projectedPlayerRef(rawYou.player);
478
+ const activity = projectedPlayerRef(rawYou.activity);
479
+ const visiblePlayers = (Array.isArray(raw.visible_players) ? raw.visible_players : [])
480
+ .map((entry: unknown) => {
481
+ const visible = projectedPlayerRef(entry);
482
+ return { ...projectedPlayerRef(visible.player), ...visible };
483
+ })
484
+ .map(({ player: _player, ...visible }) => visible);
485
+ const visibleCorpses = (Array.isArray(raw.visible_corpses) ? raw.visible_corpses : [])
486
+ .map((entry: unknown) => {
487
+ const corpse = projectedPlayerRef(entry);
488
+ return { ...projectedPlayerRef(corpse.player), ...corpse };
489
+ })
490
+ .map(({ player: _player, ...corpse }) => corpse);
491
+ const knownPlayers = (Array.isArray(raw.players) ? raw.players : []).map((entry: unknown) => {
492
+ const player = projectedPlayerRef(entry);
493
+ const knownStatus = projectedPlayerRef(player.known_status);
494
+ return {
495
+ seat: player.seat,
496
+ name: player.name,
497
+ role: 'unknown',
498
+ ...(typeof knownStatus.is_alive === 'boolean'
499
+ ? { is_alive: knownStatus.is_alive }
500
+ : {}),
501
+ };
502
+ });
503
+ const projected = normalizeGameState({
504
+ ...raw,
505
+ you: {
506
+ ...rawYou,
507
+ ...self,
508
+ currently_moving: activity.kind === 'moving',
509
+ doing_task: activity.kind === 'task',
510
+ ...(activity.kind === 'task' && typeof activity.task_name === 'string'
511
+ ? { task_name: activity.task_name }
512
+ : {}),
513
+ ...(typeof activity.remaining_secs === 'number'
514
+ ? { remaining_secs: activity.remaining_secs }
515
+ : {}),
516
+ },
517
+ players: visiblePlayers,
518
+ visible_players: visiblePlayers,
519
+ corpses: visibleCorpses,
520
+ nearby_corpses: visibleCorpses,
521
+ all_players: knownPlayers,
522
+ ...(raw.alive_count === undefined
523
+ ? { alive_count: knownPlayers.filter((player) => player.is_alive === true).length }
524
+ : {}),
525
+ ...(raw.emergency?.active === true
526
+ ? { emergency: raw.emergency }
527
+ : { emergency: undefined }),
528
+ new_events: events,
529
+ stale: false,
530
+ });
531
+ return projected;
532
+ }
533
+
534
+ function point(value: unknown): { x: number; y: number } | null {
535
+ if (!value || typeof value !== 'object') return null;
536
+ const entry = value as Record<string, unknown>;
537
+ const x = Number(entry.x ?? (Array.isArray(value) ? value[0] : undefined));
538
+ const y = Number(entry.y ?? (Array.isArray(value) ? value[1] : undefined));
539
+ return Number.isFinite(x) && Number.isFinite(y) ? { x, y } : null;
540
+ }
541
+
542
+ function roomTarget(
543
+ room: ClawclawStrategyMapInfo['rooms'][number],
544
+ taskLocations: readonly ClawclawStrategyTaskLocation[],
545
+ ): RoomTarget {
546
+ const task = taskLocations.find((candidate) => candidate.room === room.name);
547
+ if (task) return { name: room.name, x: task.x, y: task.y };
548
+ const polygon = room.polygon.map(point).filter((value): value is { x: number; y: number } => !!value);
549
+ if (polygon.length === 0) return { name: room.name, x: 0, y: 0 };
550
+ return {
551
+ name: room.name,
552
+ x: polygon.reduce((sum, value) => sum + value.x, 0) / polygon.length,
553
+ y: polygon.reduce((sum, value) => sum + value.y, 0) / polygon.length,
554
+ };
555
+ }
556
+
557
+ function trimIntentSummary(summary: string): string {
558
+ const normalized = summary.trim().replace(/[.。!!]+$/u, '');
559
+ const activeClause = normalized.lastIndexOf(',正在');
560
+ const phrase = activeClause >= 0
561
+ ? normalized.slice(activeClause + ',正在'.length)
562
+ : normalized;
563
+ return phrase.replace(/^(正在|正|已请求|尝试)/u, '');
564
+ }
565
+
566
+ function intentForAck(intent: StrategyIntent, ack: StrategyActionAck): StrategyIntent {
567
+ if (ack.status === 'success' || ack.status === 'partial') return intent;
568
+ const phrase = trimIntentSummary(intent.summary) || '执行当前策略动作';
569
+ if (ack.status === 'deferred' || ack.actionOutcome === 'not_submitted') {
570
+ return {
571
+ ...intent,
572
+ activity: 'waiting',
573
+ summary: `尚未提交${phrase},稍后重试。`,
574
+ };
575
+ }
576
+ if (ack.actionOutcome === 'unknown') {
577
+ return {
578
+ ...intent,
579
+ activity: 'waiting',
580
+ summary: `${phrase}的结果未知,正在等待权威状态。`,
581
+ };
582
+ }
583
+ return {
584
+ ...intent,
585
+ activity: 'waiting',
586
+ summary: `尝试${phrase}失败,等待重试。`,
587
+ };
588
+ }
589
+
590
+ function fallbackActionIntent(state: GameState, action: Record<string, any>): StrategyIntent {
591
+ const room = state.you.room || undefined;
592
+ if (action.action === 'move') {
593
+ const destination = typeof action.target === 'string' && action.target.trim()
594
+ ? action.target.trim()
595
+ : undefined;
596
+ return {
597
+ activity: 'moving',
598
+ summary: destination ? `正在前往${destination}。` : '正在移动。',
599
+ ...(destination ? { room: destination } : room ? { room } : {}),
600
+ };
601
+ }
602
+ if (action.action === 'task') {
603
+ const task = typeof action.task_name === 'string' && action.task_name.trim()
604
+ ? action.task_name.trim()
605
+ : undefined;
606
+ return {
607
+ activity: 'doing_task',
608
+ summary: task
609
+ ? `正在${room || '当前位置'}开始任务“${task}”。`
610
+ : `正在${room || '当前位置'}开始任务。`,
611
+ ...(room ? { room } : {}),
612
+ ...(task ? { task } : {}),
613
+ };
614
+ }
615
+ if (action.action === 'kill' && typeof action.target === 'string') {
616
+ const knownTarget = [...state.players, ...(state.all_players ?? [])]
617
+ .find(player => player.name === action.target);
618
+ const target = knownTarget?.seat != null
619
+ ? `${knownTarget.seat}号${knownTarget.name}`
620
+ : action.target;
621
+ return {
622
+ activity: 'acting',
623
+ summary: `正在击杀${target}。`,
624
+ ...(room ? { room } : {}),
625
+ targetPlayer: action.target,
626
+ };
627
+ }
628
+ if (action.action === 'report') {
629
+ return {
630
+ activity: 'acting',
631
+ summary: '正在报告尸体并召集会议。',
632
+ ...(room ? { room } : {}),
633
+ };
634
+ }
635
+ if (action.action === 'trigger_alarm') {
636
+ return {
637
+ activity: 'acting',
638
+ summary: '正在触发紧急警报。',
639
+ ...(room ? { room } : {}),
640
+ };
641
+ }
642
+ if (action.action === 'speech') {
643
+ return {
644
+ activity: 'acting',
645
+ summary: '正在与附近玩家交流。',
646
+ ...(room ? { room } : {}),
647
+ };
648
+ }
649
+ return {
650
+ activity: 'acting',
651
+ summary: '正在执行策略动作。',
652
+ ...(room ? { room } : {}),
653
+ };
654
+ }
655
+
656
+ function sameMove(left: Record<string, any>, right: Record<string, any>): boolean {
657
+ if (left.action !== 'move' || right.action !== 'move') return false;
658
+ if (typeof left.target === 'string' || typeof right.target === 'string') {
659
+ return String(left.target ?? '').trim().toLowerCase() === String(right.target ?? '').trim().toLowerCase();
660
+ }
661
+ const dx = Number(left.target_x) - Number(right.target_x);
662
+ const dy = Number(left.target_y) - Number(right.target_y);
663
+ return Number.isFinite(dx) && Number.isFinite(dy) && Math.hypot(dx, dy) <= 10;
664
+ }
665
+
666
+ function isNotSubmitted(ack: StrategyActionAck): boolean {
667
+ return ack.status === 'deferred' || ack.actionOutcome === 'not_submitted';
668
+ }
669
+
670
+ function nonIdempotentActionKey(action: Record<string, any>): string | null {
671
+ const type = String(action.action ?? '');
672
+ if (!NON_IDEMPOTENT_ACTIONS.has(type)) return null;
673
+ switch (type) {
674
+ case 'kill': return `kill:${JSON.stringify(action.target ?? '')}`;
675
+ case 'speech': return `speech:${JSON.stringify(action.text ?? '')}`;
676
+ case 'task': return `task:${JSON.stringify(action.task_name ?? '')}`;
677
+ case 'report': return 'report';
678
+ case 'trigger_alarm': return 'trigger_alarm';
679
+ default: return null;
680
+ }
681
+ }
682
+
683
+ interface AuthorityActionHold {
684
+ payload: Record<string, any>;
685
+ intent: StrategyIntent;
686
+ authoritySignature: string;
687
+ }
688
+
689
+ function authoritativeActionSignature(state: GameState, action: Record<string, any>): string {
690
+ const common = {
691
+ phase: state.phase,
692
+ alive: state.you.is_alive,
693
+ };
694
+ if (action.action === 'kill') {
695
+ const knownTarget = state.all_players?.find(player => player.name === action.target);
696
+ const visibleTarget = state.players.find(player => player.name === action.target);
697
+ return JSON.stringify({
698
+ ...common,
699
+ target_alive: knownTarget?.is_alive ?? (visibleTarget ? true : undefined),
700
+ kills_remaining: state.you.kills_remaining,
701
+ kill_cooldown_secs: state.you.kill_cooldown_secs,
702
+ alive_count: state.alive_count,
703
+ corpses: state.corpses.map(corpse => `${corpse.seat ?? ''}:${corpse.name}`).sort(),
704
+ });
705
+ }
706
+ if (action.action === 'report') {
707
+ return JSON.stringify({
708
+ ...common,
709
+ meeting: state.meeting
710
+ ? `${state.meeting.sub_phase ?? ''}:${state.meeting.caller ?? ''}`
711
+ : null,
712
+ corpses: state.corpses.map(corpse => `${corpse.seat ?? ''}:${corpse.name}`).sort(),
713
+ });
714
+ }
715
+ if (action.action === 'task') {
716
+ return JSON.stringify({
717
+ ...common,
718
+ doing_task: state.you.doing_task,
719
+ task_name: state.you.task_name,
720
+ tasks: (state.your_tasks ?? [])
721
+ .map(task => `${task.task_id || task.task_name}:${task.status}`)
722
+ .sort(),
723
+ });
724
+ }
725
+ if (action.action === 'trigger_alarm') {
726
+ return JSON.stringify({
727
+ ...common,
728
+ emergency: state.emergency
729
+ ? `${state.emergency.task_id || state.emergency.task_name}:${state.emergency.status}`
730
+ : null,
731
+ crab_sabotage: state.crab_sabotage?.status,
732
+ });
733
+ }
734
+ return JSON.stringify(common);
735
+ }
736
+
737
+ /**
738
+ * Stateful CCL Strategy base for Goal-tree strategies.
739
+ *
740
+ * One Goal Strategy and its private Goal tree are retained across update()
741
+ * calls. Game data and Actions cross only StrategyApi; this class never opens
742
+ * HTTP, storage, credentials, or another runtime channel.
743
+ */
744
+ export class ClawclawGoalStrategy extends ClawclawHybridStrategy<
745
+ ClawclawGoalStrategyAnalysis,
746
+ ClawclawStrategyGameState,
747
+ ClawclawStrategyAction
748
+ > {
749
+ private readonly strategyId: string;
750
+ private readonly options: ClawclawGoalStrategyOptions;
751
+ private strategy?: Strategy;
752
+ private readonly context: StrategyContext;
753
+ private readonly corpseMemory = new CorpseMemory();
754
+ private modules: CustomModule[];
755
+ private effectiveParameters: Readonly<Record<string, unknown>>;
756
+ private currentRole = '';
757
+ private configurationError?: string;
758
+ private mapCache?: Readonly<ClawclawStrategyMapInfo>;
759
+ private tasksAvailable = true;
760
+ private activeMove?: {
761
+ payload: Record<string, any>;
762
+ intent?: StrategyIntent;
763
+ until: number;
764
+ epochId: number;
765
+ };
766
+ private readonly authorityPendingActions = new Map<string, AuthorityActionHold>();
767
+
768
+ constructor(
769
+ parameters: Readonly<Record<string, unknown>>,
770
+ options: ClawclawGoalStrategyOptions,
771
+ ) {
772
+ super(parameters);
773
+ this.options = options;
774
+ this.strategyId = options.id;
775
+ this.effectiveParameters = Object.freeze(structuredClone(parameters));
776
+ this.configurationError = options.validateParameters?.(this.effectiveParameters);
777
+ // Goal construction is deliberately lazy: parallel analyzers validate and
778
+ // project frames without rebuilding a private Goal tree for every epoch.
779
+ this.strategy = undefined;
780
+ this.context = {
781
+ taskData: [],
782
+ taskLocations: [],
783
+ emergency: null,
784
+ taskLocalBlockedUntil: 0,
785
+ reportCorpseTarget: null,
786
+ reportBlockedUntil: 0,
787
+ octopusTimeActive: false,
788
+ notifications: [],
789
+ lastProgressNotifyAt: 0,
790
+ teammates: new Set(),
791
+ alarmDone: false,
792
+ alarmOnCooldown: false,
793
+ rooms: [],
794
+ playerNamesBySeat: {},
795
+ forcePatrolAdvance: false,
796
+ blockedMoveTarget: null,
797
+ mySeat: 0,
798
+ speechNotifications: [],
799
+ agentAlerts: [],
800
+ knownCorpses: [],
801
+ recentlyKilledTargets: new Map(),
802
+ };
803
+ this.modules = [];
804
+ }
805
+
806
+ applyControl(update: StrategyControlUpdate): StrategyControlResult {
807
+ const changed = Object.entries(update.values).some(
808
+ ([key, value]) => !sameControlValue(this.effectiveParameters[key], value),
809
+ );
810
+ if (!changed && !this.configurationError) {
811
+ return {
812
+ accepted: true,
813
+ appliedRevision: update.revision,
814
+ effectiveValues: this.effectiveParameters,
815
+ };
816
+ }
817
+ const effectiveParameters = Object.freeze(structuredClone({
818
+ ...this.effectiveParameters,
819
+ ...update.values,
820
+ }));
821
+ const configurationError = this.options.validateParameters?.(effectiveParameters);
822
+ if (configurationError) {
823
+ return { accepted: false, message: configurationError };
824
+ }
825
+ // Construct first so a rejected parameter set leaves the current Goal tree intact.
826
+ const strategy = this.options.create(effectiveParameters);
827
+ const modules = strategy.customModules?.() ?? [];
828
+ this.strategy = strategy;
829
+ this.modules = modules;
830
+ this.effectiveParameters = effectiveParameters;
831
+ this.configurationError = undefined;
832
+ this.currentRole = '';
833
+ this.activeMove = undefined;
834
+ this.authorityPendingActions.clear();
835
+ this.context.intent = undefined;
836
+ if (modules.length > 0) this.context.customModules = modules;
837
+ else delete this.context.customModules;
838
+ if (this.mapCache) {
839
+ for (const module of modules) module.onMapLoaded?.([...this.mapCache.rooms]);
840
+ }
841
+ return {
842
+ accepted: true,
843
+ appliedRevision: update.revision,
844
+ effectiveValues: effectiveParameters,
845
+ };
846
+ }
847
+
848
+ reset(_reason: 'wandering_resumed'): void {
849
+ this.strategy?.onMeetingResume?.();
850
+ for (const module of this.modules) module.onMeetingResume?.();
851
+ this.corpseMemory.reset();
852
+ this.context.knownCorpses = [];
853
+ this.context.taskLocalBlockedUntil = 0;
854
+ this.context.reportCorpseTarget = null;
855
+ this.context.reportBlockedUntil = 0;
856
+ this.context.octopusTimeActive = false;
857
+ this.context.forcePatrolAdvance = false;
858
+ this.context.blockedMoveTarget = null;
859
+ this.activeMove = undefined;
860
+ this.authorityPendingActions.clear();
861
+ this.context.intent = undefined;
862
+ }
863
+
864
+ async analyze(
865
+ frame: WanderingStrategyFrame<ClawclawStrategyGameState>,
866
+ game: StrategyGameApi,
867
+ ): Promise<ClawclawGoalStrategyAnalysis> {
868
+ if (frame.state?.you?.is_alive === false || this.configurationError) return {};
869
+ const resources = await this.loadMapAndTasks(game);
870
+ return {
871
+ resources,
872
+ routeEvidence: this.buildRouteEvidence(frame, resources),
873
+ };
874
+ }
875
+
876
+ override async update(
877
+ frame: WanderingStrategyFrame<ClawclawStrategyGameState>,
878
+ api: StrategyApi<ClawclawStrategyAction>,
879
+ ): Promise<StrategyResult<ClawclawStrategyAction>> {
880
+ return this.reduce(frame, await this.analyze(frame, api.game), api);
881
+ }
882
+
883
+ async reduce(
884
+ frame: WanderingStrategyFrame<ClawclawStrategyGameState>,
885
+ analysis: Readonly<ClawclawGoalStrategyAnalysis>,
886
+ api: StrategyApi<ClawclawStrategyAction>,
887
+ ): Promise<StrategyResult<ClawclawStrategyAction>> {
888
+ // State and Events are deliberately projected from the ordered commit
889
+ // frame. Parallel analysis may have started before an earlier epoch moved
890
+ // the Event cursor, so its frame is evidence for resource queries only.
891
+ const events = frameEvents(frame);
892
+ const state = projectGoalGameState(frame.state, events);
893
+ if (!state.you?.is_alive) {
894
+ return this.status({ activity: 'idle', summary: '当前角色已死亡,策略停止行动。' });
895
+ }
896
+ const strategy = this.ensureStrategy();
897
+ if (!strategy) {
898
+ return this.status({
899
+ activity: 'waiting',
900
+ summary: this.configurationError ?? `${this.strategyId} 正在等待参数配置。`,
901
+ ...(state.you.room ? { room: state.you.room } : {}),
902
+ });
903
+ }
904
+ if (!analysis.resources) {
905
+ throw new Error('STRATEGY_ANALYSIS_INVALID:goal_resources_missing');
906
+ }
907
+
908
+ this.learnRoleAndPlayers(state, events);
909
+ this.applyMapAndTasks(state, analysis.resources);
910
+ this.context.routeEvidence = analysis.routeEvidence ?? null;
911
+ this.context.emergency = this.emergency(state);
912
+ this.refreshAuthorityPendingActions(state);
913
+ this.corpseMemory.observe(state, this.context.recentlyKilledTargets);
914
+ this.context.knownCorpses = this.corpseMemory.list();
915
+ for (const module of this.modules) module.processEvents(events, state.tick, state);
916
+
917
+ // A parallel frame may have captured `idle` before the accepted move's HTTP
918
+ // acknowledgement. Only an explicit movement Event or the bounded TTL can
919
+ // retire this dedupe record; otherwise old frames resubmit the same target.
920
+ if (this.activeMove && (
921
+ events.some((event) => event.type === 'move_end' || event.type === 'move_interrupted')
922
+ || Date.now() >= this.activeMove.until
923
+ )) {
924
+ this.activeMove = undefined;
925
+ }
926
+
927
+ this.context.intent = undefined;
928
+ let decisions = strategy.decide(state, this.context);
929
+ for (const module of this.modules) {
930
+ if (module.afterDecide) decisions = module.afterDecide(decisions, state, this.context);
931
+ }
932
+ const speech = this.options.sidecarSpeech
933
+ ? decisions.filter((decision) => decision.action.toJSON().action === 'speech')
934
+ : [];
935
+ const main = speech.length > 0
936
+ ? decisions.filter((decision) => decision.action.toJSON().action !== 'speech')
937
+ : decisions;
938
+ const decision = main.find((candidate) => (
939
+ !this.repeatsActiveMove(candidate) && !this.repeatsAuthorityPendingAction(candidate)
940
+ ));
941
+ const submitted = decision
942
+ ? await this.submit(decision, frame.epochId, state, api)
943
+ : undefined;
944
+ const sidecarSubmissions: Array<{
945
+ payload: Record<string, any>;
946
+ ack: StrategyActionAck;
947
+ intent?: StrategyIntent;
948
+ }> = [];
949
+ for (const sidecar of speech) {
950
+ if (this.repeatsAuthorityPendingAction(sidecar)) continue;
951
+ sidecarSubmissions.push(await this.submit(sidecar, frame.epochId, state, api));
952
+ }
953
+
954
+ const proposedEvents: StrategyEventProposal[] = [
955
+ ...this.context.agentAlerts.map((message) => ({
956
+ type: 'strategy_alert',
957
+ payload: { message, strategy: this.strategyId, tick: state.tick },
958
+ })),
959
+ ...this.context.speechNotifications.map((message) => ({
960
+ type: 'robot_speak_rule',
961
+ payload: { message },
962
+ })),
963
+ ];
964
+ this.context.agentAlerts.length = 0;
965
+ this.context.speechNotifications.length = 0;
966
+ this.context.notifications.length = 0;
967
+
968
+ const status = this.statusFor(state, submitted ?? sidecarSubmissions[0]);
969
+ return {
970
+ ...status,
971
+ ...(proposedEvents.length > 0 ? { events: proposedEvents } : {}),
972
+ };
973
+ }
974
+
975
+ private learnRoleAndPlayers(state: GameState, events: readonly Record<string, any>[]): void {
976
+ const role = state.you.role ?? '';
977
+ if (role && role !== this.currentRole) {
978
+ this.currentRole = role;
979
+ this.strategy?.updateRole?.(role);
980
+ }
981
+ if (state.you.seat != null) this.context.mySeat = state.you.seat;
982
+ for (const player of state.all_players ?? state.players ?? []) {
983
+ if (player.seat != null && player.name) this.context.playerNamesBySeat[String(player.seat)] = player.name;
984
+ }
985
+ for (const event of events) {
986
+ if (event.type === 'octopus_time_start') this.context.octopusTimeActive = true;
987
+ const eventTeammates = Array.isArray(event.crab_teammates)
988
+ ? event.crab_teammates
989
+ : Array.isArray(event.teammates) ? event.teammates : [];
990
+ for (const teammate of eventTeammates) {
991
+ const name = typeof teammate === 'string'
992
+ ? teammate
993
+ : projectedPlayerRef(teammate).name;
994
+ if (typeof name === 'string' && name) this.context.teammates.add(name);
995
+ }
996
+ }
997
+ const stateTeammates = state.you.crab_teammates;
998
+ for (const teammate of Array.isArray(stateTeammates) ? stateTeammates : []) {
999
+ const name = typeof teammate === 'string'
1000
+ ? teammate
1001
+ : projectedPlayerRef(teammate).name;
1002
+ if (typeof name === 'string' && name) this.context.teammates.add(name);
1003
+ }
1004
+ }
1005
+
1006
+ private ensureStrategy(): Strategy | undefined {
1007
+ if (this.strategy || this.configurationError) return this.strategy;
1008
+ const strategy = this.options.create(this.effectiveParameters);
1009
+ const modules = strategy.customModules?.() ?? [];
1010
+ this.strategy = strategy;
1011
+ this.modules = modules;
1012
+ if (modules.length > 0) this.context.customModules = modules;
1013
+ if (this.mapCache) {
1014
+ for (const module of modules) module.onMapLoaded?.([...this.mapCache.rooms]);
1015
+ }
1016
+ return strategy;
1017
+ }
1018
+
1019
+ private async loadMapAndTasks(
1020
+ game: StrategyGameApi,
1021
+ ): Promise<NonNullable<ClawclawGoalStrategyAnalysis['resources']>> {
1022
+ let tasks: readonly ClawclawStrategyTask[] | null = [];
1023
+ let tasksAvailable = true;
1024
+ if (this.options.requiresTasks) {
1025
+ try {
1026
+ tasks = await game.getTasks();
1027
+ } catch (error) {
1028
+ if (String(error).includes('authoritative_tasks_unavailable')) {
1029
+ tasks = null;
1030
+ tasksAvailable = false;
1031
+ } else {
1032
+ throw new Error(
1033
+ `STRATEGY_CAPABILITY_UNAVAILABLE:tasks:${error instanceof Error ? error.message : String(error)}`,
1034
+ );
1035
+ }
1036
+ }
1037
+ }
1038
+ let map = this.mapCache;
1039
+ if (this.options.requiresMap !== false && !map) {
1040
+ try {
1041
+ map = await game.getMap() ?? undefined;
1042
+ } catch (error) {
1043
+ throw new Error(
1044
+ `STRATEGY_CAPABILITY_UNAVAILABLE:map:${error instanceof Error ? error.message : String(error)}`,
1045
+ );
1046
+ }
1047
+ if (!map) throw new Error('STRATEGY_CAPABILITY_UNAVAILABLE:map:no current map');
1048
+ }
1049
+ return { tasks, tasksAvailable, ...(map ? { map } : {}) };
1050
+ }
1051
+
1052
+ private buildRouteEvidence(
1053
+ frame: WanderingStrategyFrame<ClawclawStrategyGameState>,
1054
+ resources: NonNullable<ClawclawGoalStrategyAnalysis['resources']>,
1055
+ ): RouteEvidence | null | undefined {
1056
+ const targets = this.options.routeEvidenceTargets;
1057
+ const you = frame.state?.you;
1058
+ if (!you || !targets || targets.length === 0) return undefined;
1059
+ const points: Array<{ x: number; y: number }> = [];
1060
+ if (targets.includes('tasks')) {
1061
+ for (const task of resources.tasks ?? []) points.push({ x: task.x, y: task.y });
1062
+ }
1063
+ if (targets.includes('rooms') && resources.map) {
1064
+ for (const room of resources.map.rooms) {
1065
+ const target = roomTarget(room, resources.map.all_task_locations);
1066
+ points.push({ x: target.x, y: target.y });
1067
+ }
1068
+ }
1069
+ if (targets.includes('hide')) {
1070
+ for (const spot of HIDE_SPOTS) points.push({ x: spot.x, y: spot.y });
1071
+ }
1072
+ if (points.length === 0) return undefined;
1073
+ return buildRouteEvidence({ x: you.x, y: you.y }, points);
1074
+ }
1075
+
1076
+ private applyMapAndTasks(
1077
+ state: GameState,
1078
+ resources: NonNullable<ClawclawGoalStrategyAnalysis['resources']>,
1079
+ ): void {
1080
+ const { tasks, map } = resources;
1081
+ const firstMapLoad = map !== undefined && this.mapCache === undefined;
1082
+ if (map) this.mapCache = map;
1083
+ this.tasksAvailable = resources.tasksAvailable;
1084
+ const factionByName = new Map(
1085
+ (map?.all_task_locations ?? []).map((task) => [task.name, task.faction]),
1086
+ );
1087
+ this.context.taskData = (tasks ?? []).map((task): TaskInfo => ({
1088
+ task_id: task.name,
1089
+ task_name: task.name,
1090
+ room: task.room,
1091
+ status: task.status,
1092
+ x: task.x,
1093
+ y: task.y,
1094
+ is_fake_shrimp: task.is_fake_shrimp ?? false,
1095
+ faction: factionByName.get(task.name),
1096
+ }));
1097
+ if (tasks === null) delete state.your_tasks;
1098
+ else state.your_tasks = this.context.taskData;
1099
+ if (map) {
1100
+ this.context.taskLocations = map.all_task_locations.map((task) => ({
1101
+ name: task.name,
1102
+ room: task.room,
1103
+ x: task.x,
1104
+ y: task.y,
1105
+ faction: task.faction,
1106
+ }));
1107
+ this.context.rooms = map.rooms.map((room) => roomTarget(room, map.all_task_locations));
1108
+ if (firstMapLoad) {
1109
+ for (const module of this.modules) module.onMapLoaded?.([...map.rooms]);
1110
+ }
1111
+ for (const player of map.all_players) {
1112
+ this.context.playerNamesBySeat[String(player.seat)] = player.name;
1113
+ }
1114
+ }
1115
+ }
1116
+
1117
+ private emergency(state: GameState): EmergencyInfo | null {
1118
+ const value = state.emergency;
1119
+ if (!value) return null;
1120
+ return {
1121
+ task_id: value.task_name ?? '',
1122
+ task_name: value.task_name ?? '',
1123
+ room: value.room ?? '',
1124
+ status: value.status ?? 'emergency',
1125
+ x: value.x,
1126
+ y: value.y,
1127
+ remaining_secs: Number(value.remaining_secs ?? 0),
1128
+ };
1129
+ }
1130
+
1131
+ private repeatsActiveMove(decision: BehaviorDecision): boolean {
1132
+ if (!this.activeMove || Date.now() >= this.activeMove.until) return false;
1133
+ return sameMove(decision.action.toJSON(), this.activeMove.payload);
1134
+ }
1135
+
1136
+ private repeatsAuthorityPendingAction(decision: BehaviorDecision): boolean {
1137
+ const key = nonIdempotentActionKey(decision.action.toJSON());
1138
+ return key !== null && this.authorityPendingActions.has(key);
1139
+ }
1140
+
1141
+ private refreshAuthorityPendingActions(state: GameState): void {
1142
+ for (const [key, pending] of this.authorityPendingActions) {
1143
+ if (authoritativeActionSignature(state, pending.payload) !== pending.authoritySignature) {
1144
+ this.authorityPendingActions.delete(key);
1145
+ }
1146
+ }
1147
+ }
1148
+
1149
+ private async submit(
1150
+ decision: BehaviorDecision,
1151
+ epochId: number,
1152
+ state: GameState,
1153
+ api: StrategyApi<ClawclawStrategyAction>,
1154
+ ): Promise<{ payload: Record<string, any>; ack: StrategyActionAck; intent?: StrategyIntent }> {
1155
+ const payload = decision.action.toJSON();
1156
+ const intent = decision.intent ?? this.context.intent;
1157
+ delete payload.audio_url;
1158
+ const ack = await api.action.submit(payload as ClawclawStrategyAction);
1159
+ const accepted = ack.status === 'success' || ack.status === 'partial';
1160
+ const definiteFailure = !accepted && ack.actionOutcome !== 'unknown';
1161
+ const failureText = JSON.stringify(ack.error ?? ack.value ?? {});
1162
+ if (payload.action === 'move') {
1163
+ if (accepted) this.activeMove = { payload, intent, epochId, until: Date.now() + MOVE_DEDUPE_MS };
1164
+ else if (failureText.includes('invalid_position_blocked')) {
1165
+ const x = Number(payload.target_x);
1166
+ const y = Number(payload.target_y);
1167
+ if (Number.isFinite(x) && Number.isFinite(y)) this.context.blockedMoveTarget = { x, y };
1168
+ }
1169
+ }
1170
+ if (definiteFailure && payload.action === 'task' && failureText.includes('not_at_task_location')) {
1171
+ this.context.taskLocalBlockedUntil = Date.now() + 5_000;
1172
+ }
1173
+ if (definiteFailure && payload.action === 'report' && !failureText.includes('doing_task')) {
1174
+ this.context.reportBlockedUntil = Date.now() + 5_000;
1175
+ }
1176
+ if (definiteFailure && payload.action === 'report' && failureText.includes('octopus')) {
1177
+ this.context.octopusTimeActive = true;
1178
+ }
1179
+ if (payload.action === 'trigger_alarm') {
1180
+ this.context.alarmOnCooldown = definiteFailure && failureText.includes('on_cooldown');
1181
+ }
1182
+ if (definiteFailure && payload.action === 'kill' && failureText.includes('cannot_kill_teammate')) {
1183
+ if (typeof payload.target === 'string') this.context.teammates.add(payload.target);
1184
+ }
1185
+ if (accepted && payload.action === 'kill' && typeof payload.target === 'string') {
1186
+ this.context.recentlyKilledTargets?.set(
1187
+ payload.target.trim().toLowerCase(),
1188
+ Date.now() + RECENT_KILL_IGNORE_MS,
1189
+ );
1190
+ }
1191
+ const unknownKey = nonIdempotentActionKey(payload);
1192
+ if (unknownKey !== null && (
1193
+ (ack.status === 'failure' && ack.actionOutcome === 'unknown')
1194
+ || ((ack.status === 'success' || ack.status === 'partial')
1195
+ && AUTHORITY_ACK_ACTIONS.has(String(payload.action ?? '')))
1196
+ )) {
1197
+ this.authorityPendingActions.set(unknownKey, {
1198
+ payload,
1199
+ intent: intentForAck(intent ?? fallbackActionIntent(state, payload), ack),
1200
+ authoritySignature: authoritativeActionSignature(state, payload),
1201
+ });
1202
+ }
1203
+ return { payload, ack, intent };
1204
+ }
1205
+
1206
+ private statusFor(
1207
+ state: GameState,
1208
+ submitted?: { payload: Record<string, any>; ack: StrategyActionAck; intent?: StrategyIntent },
1209
+ ): StrategyResult<ClawclawStrategyAction> {
1210
+ const publish = (
1211
+ value: ClawclawStrategyStatusState,
1212
+ ): StrategyResult<ClawclawStrategyAction> => this.status({
1213
+ ...value,
1214
+ ...(this.options.requiresTasks ? {
1215
+ dataAvailability: {
1216
+ tasks: this.tasksAvailable ? 'available' : 'unavailable',
1217
+ },
1218
+ } : {}),
1219
+ });
1220
+ const taskStatus = (): ClawclawStrategyStatusState => ({
1221
+ activity: 'doing_task',
1222
+ summary: state.you.task_name
1223
+ ? `正在${state.you.room || '当前位置'}执行任务“${state.you.task_name}”。`
1224
+ : `正在${state.you.room || '当前位置'}执行任务。`,
1225
+ ...(state.you.room ? { room: state.you.room } : {}),
1226
+ ...(state.you.task_name ? { task: state.you.task_name } : {}),
1227
+ });
1228
+ if (submitted) {
1229
+ if (
1230
+ state.you.doing_task
1231
+ && (
1232
+ isNotSubmitted(submitted.ack)
1233
+ || (submitted.ack.status === 'failure' && submitted.ack.actionOutcome !== 'unknown')
1234
+ )
1235
+ ) return publish(taskStatus());
1236
+ const intent = submitted.intent ?? fallbackActionIntent(state, submitted.payload);
1237
+ return publish(intentForAck(intent, submitted.ack));
1238
+ }
1239
+ const unknownPhysical = [...this.authorityPendingActions.values()]
1240
+ .find(unknown => unknown.payload.action !== 'speech');
1241
+ if (unknownPhysical) {
1242
+ return publish(unknownPhysical.intent);
1243
+ }
1244
+ if (state.you.doing_task) {
1245
+ return publish(taskStatus());
1246
+ }
1247
+ if (this.activeMove) {
1248
+ return publish(this.activeMove.intent ?? fallbackActionIntent(state, this.activeMove.payload));
1249
+ }
1250
+ const unknownSidecar = this.authorityPendingActions.values().next().value as AuthorityActionHold | undefined;
1251
+ if (unknownSidecar) return publish(unknownSidecar.intent);
1252
+ if (this.context.intent) return publish(this.context.intent);
1253
+ if (state.you.currently_moving) {
1254
+ return publish({
1255
+ activity: 'moving',
1256
+ summary: '正在继续移动。',
1257
+ ...(state.you.room ? { room: state.you.room } : {}),
1258
+ });
1259
+ }
1260
+ return publish({
1261
+ activity: 'idle',
1262
+ summary: `当前没有可执行动作,正在${state.you.room || '当前位置'}等待。`,
1263
+ ...(state.you.room ? { room: state.you.room } : {}),
1264
+ });
1265
+ }
1266
+ }
1267
+
1268
+ export interface StrategyInstance<
1269
+ TState = Record<string, unknown>,
1270
+ TAction = Record<string, unknown>,
1271
+ > {
1272
+ /** Marks private plans stale before the next wandering update. */
1273
+ reset?(reason: 'wandering_resumed'): void | Promise<void>;
1274
+ update(
1275
+ frame: StrategyFrame<TState>,
1276
+ api: StrategyApi<TAction>,
1277
+ ): StrategyResult<TAction> | void | Promise<StrategyResult<TAction> | void>;
1278
+ /** Pure per-epoch phase for manifest.execution='parallel_analyze'. */
1279
+ analyze?(
1280
+ frame: StrategyFrame<TState>,
1281
+ game: StrategyGameApi,
1282
+ ): unknown | Promise<unknown>;
1283
+ /** Persistent ordered phase paired with analyze(). */
1284
+ reduce?(
1285
+ frame: StrategyFrame<TState>,
1286
+ analysis: unknown,
1287
+ api: StrategyApi<TAction>,
1288
+ ): StrategyResult<TAction> | void | Promise<StrategyResult<TAction> | void>;
1289
+ /** Applies a manifest-declared hot control before update() for the same epoch. */
1290
+ applyControl?(
1291
+ update: StrategyControlUpdate,
1292
+ ): StrategyControlResult | Promise<StrategyControlResult>;
1293
+ stop?(reason: 'switched' | 'scope_ended' | 'shutdown'): void | Promise<void>;
1294
+ }
1295
+
1296
+ // Goal authoring surface used by materialized official strategies. The public
1297
+ // authoring API does not export GameClient, transport, SQLite, or Runtime
1298
+ // internals. Strategy source is still trusted same-process code, not sandboxed.
1299
+ export { parseGreetingArgs } from '../../strategies/greeting.js';
1300
+ export { parseTargetArgs } from '../../strategies/player-targets.js';
1301
+ export { SpeechModule, getSpeechConfigForRole } from '../../strategies/speech-module.js';
1302
+ export { GoalRootStrategy } from '../../strategies/goals/goal-root-strategy.js';
1303
+ export { TaskOnlyTop } from '../../strategies/goals/task-only-top.js';
1304
+ export { TaskReportTop } from '../../strategies/goals/task-report-top.js';
1305
+ export { TaskKillReportTop } from '../../strategies/goals/task-kill-report-top.js';
1306
+ export { KillFrenzyTop } from '../../strategies/goals/kill-frenzy-top.js';
1307
+ export { KillLoneTop } from '../../strategies/goals/kill-lone-top.js';
1308
+ export { KillTargetTop } from '../../strategies/goals/kill-target-top.js';
1309
+ export { LoneKillTaskTop } from '../../strategies/goals/lone-kill-task-top.js';
1310
+ export { CrabSabotageTop } from '../../strategies/goals/crab-sabotage-top.js';
1311
+ export { CorpsePatrolTop } from '../../strategies/goals/corpse-patrol-top.js';
1312
+ export { ReportPatrolTop } from '../../strategies/goals/report-patrol-top.js';
1313
+ export { PatrolTop } from '../../strategies/goals/patrol-top.js';
1314
+ export { NormalShrimpTop } from '../../strategies/goals/normal-shrimp-top.js';
1315
+ export { WarriorShrimpTop } from '../../strategies/goals/warrior-shrimp-top.js';
1316
+ export { ParadiseFishTop } from '../../strategies/goals/paradise-fish-top.js';
1317
+ export { FindPlayerTop } from '../../strategies/goals/find-player-top.js';
1318
+ export { SocialTaskTop } from '../../strategies/goals/social-task-top.js';
1319
+ export { AvoidLoneTop } from '../../strategies/goals/avoid-lone-top.js';
1320
+ export { AvoidPlayersTop } from '../../strategies/goals/avoid-players-top.js';
1321
+ export { HideTop } from '../../strategies/goals/hide-top.js';
1322
+ export { MoveRoomGoal } from '../../strategies/goals/move-room-goal.js';
1323
+ export { ConversationGoal } from '../../strategies/goals/conversation-goal.js';
1324
+ export type { SocialTarget } from '../../strategies/goals/social-task-top.js';