@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
@@ -0,0 +1,848 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import {
3
+ ClawclawBehavior,
4
+ type BehaviorDecision,
5
+ type BehaviorInput,
6
+ type ClawclawBehaviorClass,
7
+ type ClawclawBehaviorManifest,
8
+ } from '../../../../sdk/behavior-plugin/index.js';
9
+ import type { CanonicalEvent } from '../../../framework/events/types.js';
10
+ import type {
11
+ RuntimeEpochPluginContext,
12
+ RuntimeEpochPluginInput,
13
+ RuntimeEpochPluginResult,
14
+ } from '../../../framework/plugins/contracts.js';
15
+ import type { StoredStateFrame } from '../../../framework/state/history/contracts.js';
16
+ import { MemoryStateHistoryRepository } from '../../../framework/state/history/memory-state-history-repository.js';
17
+ import { BehaviorActivationManager } from './activation-manager.js';
18
+ import {
19
+ CLAWCLAW_BEHAVIOR_STATE_TOPIC,
20
+ ClawclawBehaviorPlugin,
21
+ } from './behavior-plugin.js';
22
+ import type { ClawclawBehaviorControlDriver } from './control-driver.js';
23
+ import { prepareClawclawBehavior } from './behavior-normalization.js';
24
+
25
+ const scope = {
26
+ adapterId: 'clawclaw', accountId: 'account', sessionId: 'session', segmentId: 'game',
27
+ };
28
+
29
+ function manifest(
30
+ id: string,
31
+ options: Partial<ClawclawBehaviorManifest> = {},
32
+ ): ClawclawBehaviorManifest {
33
+ return {
34
+ apiVersion: 3,
35
+ id,
36
+ name: id,
37
+ description: `${id} fixture`,
38
+ inputs: [],
39
+ execution: 'serial',
40
+ ...options,
41
+ };
42
+ }
43
+
44
+ function catalog(classes: readonly ClawclawBehaviorClass[]) {
45
+ const byId = new Map(classes.map((BehaviorClass) => [
46
+ BehaviorClass.manifest!.id,
47
+ BehaviorClass,
48
+ ]));
49
+ return {
50
+ has: (id: string) => byId.has(id),
51
+ prepare: async (id: string, input: unknown) => {
52
+ const BehaviorClass = byId.get(id);
53
+ if (!BehaviorClass) throw new Error(`Unknown behavior module '${id}'.`);
54
+ return prepareClawclawBehavior(BehaviorClass, BehaviorClass.manifest!, input);
55
+ },
56
+ };
57
+ }
58
+
59
+ function driver(
60
+ authorization: (activationId: string) => boolean = () => true,
61
+ ): ClawclawBehaviorControlDriver {
62
+ return {
63
+ acquire: activation => ({
64
+ caller: {
65
+ kind: 'behavior',
66
+ activationId: activation.activationId,
67
+ layer: activation.layer,
68
+ activationGeneration: activation.instanceGeneration,
69
+ },
70
+ scope,
71
+ controllerId: `behavior:${activation.activationId}:${activation.instanceGeneration}`,
72
+ isAuthorized: () => authorization(activation.activationId),
73
+ release: vi.fn(),
74
+ }),
75
+ };
76
+ }
77
+
78
+ function event(commitSeq: number): CanonicalEvent {
79
+ return {
80
+ commitSeq,
81
+ epochSeq: commitSeq,
82
+ eventId: `event-${commitSeq}`,
83
+ sessionId: scope.sessionId,
84
+ segmentId: scope.segmentId,
85
+ type: `event_${commitSeq}`,
86
+ producer: 'backend_push',
87
+ deliveryClass: 'monitor_and_events',
88
+ occurredAt: new Date(commitSeq * 100).toISOString(),
89
+ receivedAt: new Date(commitSeq * 100).toISOString(),
90
+ payload: { commitSeq },
91
+ sourceId: 'test',
92
+ replayed: false,
93
+ };
94
+ }
95
+
96
+ function input(
97
+ epochSeq: number,
98
+ options: Readonly<{
99
+ tick?: number;
100
+ nowMs?: number;
101
+ phase?: string;
102
+ role?: string;
103
+ alive?: boolean;
104
+ pendingEvents?: readonly CanonicalEvent[];
105
+ }> = {},
106
+ ): RuntimeEpochPluginInput<Record<string, any>> {
107
+ const tick = options.tick ?? epochSeq;
108
+ const gameState = {
109
+ game_id: 'game',
110
+ phase: options.phase ?? 'wandering',
111
+ tick,
112
+ you: {
113
+ player: { name: 'self', seat: 1 },
114
+ role: options.role ?? 'shrimp_generic',
115
+ faction: 'lobster',
116
+ x: 0,
117
+ y: 0,
118
+ room: 'navigation',
119
+ is_alive: options.alive ?? true,
120
+ activity: { kind: 'idle' },
121
+ tasks: [],
122
+ },
123
+ players: [],
124
+ visible_players: [],
125
+ visible_corpses: [],
126
+ };
127
+ const state = {
128
+ schema: 'clawclaw.runtime-state.v1',
129
+ action_safety_generation: 7,
130
+ stage: gameState.phase === 'meeting' ? 'meeting' : 'game',
131
+ transport: 'game_ws',
132
+ connection: 'connected',
133
+ cause: 'game_snapshot',
134
+ game_snapshot: { status: 'fresh', state: gameState },
135
+ };
136
+ const receivedAtMs = options.nowMs ?? epochSeq * 100;
137
+ const frame: StoredStateFrame<Record<string, any>> = {
138
+ frameSeq: epochSeq,
139
+ epochSeq,
140
+ scope,
141
+ sourceId: 'test',
142
+ connectionId: 'ws',
143
+ sourceKey: `state:${epochSeq}`,
144
+ backendTick: tick,
145
+ receivedAtMs,
146
+ state,
147
+ };
148
+ return {
149
+ epoch: {
150
+ epochSeq,
151
+ scope,
152
+ sourceId: 'test',
153
+ connectionId: 'ws',
154
+ sourceKey: `state:${epochSeq}`,
155
+ domainTick: tick,
156
+ state,
157
+ events: [],
158
+ completeness: 'complete',
159
+ receivedAt: new Date(receivedAtMs).toISOString(),
160
+ },
161
+ frame,
162
+ currentState: {
163
+ state: gameState,
164
+ stateStatus: {
165
+ status: 'fresh', semantics: 'latest_received', source: 'owner_memory', scope,
166
+ connectionId: 'ws', connectionState: 'connected', receivedAtMs,
167
+ ageMs: 0, backendTick: tick, reason: null,
168
+ },
169
+ },
170
+ previousState: null,
171
+ epochEvents: [],
172
+ pendingEvents: options.pendingEvents ?? [],
173
+ upstreamStates: {},
174
+ };
175
+ }
176
+
177
+ function context(
178
+ actions: Array<Record<string, any>> = [],
179
+ ): RuntimeEpochPluginContext<Record<string, any>> {
180
+ const history = new MemoryStateHistoryRepository<unknown, Record<string, any>>();
181
+ history.openScope(scope);
182
+ return {
183
+ scope,
184
+ stateHistory: history,
185
+ currentSegment: () => ({ kind: 'game', identity: 'game' }),
186
+ checkpoint: () => undefined,
187
+ progress: () => ({
188
+ pluginId: 'clawclaw.behavior', completedThroughEpochSeq: 0, eventCursor: 0,
189
+ updatedAt: new Date(0).toISOString(),
190
+ }),
191
+ capabilities: {
192
+ provideObservation: () => { throw new Error('unused'); },
193
+ provideAction: () => { throw new Error('unused'); },
194
+ queryObservation: () => Promise.reject(new Error('unused')),
195
+ performAction: (async (_capability: string, action: unknown) => {
196
+ const request = action as Record<string, any>;
197
+ if (request.action?.action === 'strategy') {
198
+ return {
199
+ scope,
200
+ actionId: 'strategy-report-action',
201
+ status: 'success',
202
+ source: 'backend',
203
+ actionOutcome: 'confirmed',
204
+ value: { success: true, data: { ok: true } },
205
+ };
206
+ }
207
+ actions.push(request);
208
+ return {
209
+ scope,
210
+ actionId: `action-${actions.length}`,
211
+ status: 'success',
212
+ source: 'local',
213
+ actionOutcome: 'unknown',
214
+ value: { accepted: true, status: 'queued' },
215
+ };
216
+ }) as RuntimeEpochPluginContext<Record<string, any>>['capabilities']['performAction'],
217
+ },
218
+ diagnostic: () => {},
219
+ signal: new AbortController().signal,
220
+ };
221
+ }
222
+
223
+ function successfulStrategyReportResult() {
224
+ return {
225
+ scope,
226
+ actionId: 'strategy-report-action',
227
+ status: 'success' as const,
228
+ source: 'backend' as const,
229
+ actionOutcome: 'confirmed' as const,
230
+ value: { success: true, data: { ok: true } },
231
+ };
232
+ }
233
+
234
+ function contextWithPerformAction(
235
+ performAction: RuntimeEpochPluginContext<Record<string, any>>['capabilities']['performAction'],
236
+ ): RuntimeEpochPluginContext<Record<string, any>> {
237
+ const base = context();
238
+ return {
239
+ ...base,
240
+ capabilities: { ...base.capabilities, performAction },
241
+ };
242
+ }
243
+
244
+ async function step(
245
+ plugin: ClawclawBehaviorPlugin,
246
+ epoch: RuntimeEpochPluginInput<Record<string, any>>,
247
+ ctx: RuntimeEpochPluginContext<Record<string, any>>,
248
+ ): Promise<RuntimeEpochPluginResult> {
249
+ const computation = await plugin.update(epoch, ctx);
250
+ return plugin.commit(epoch, computation, ctx);
251
+ }
252
+
253
+ class LongBehavior extends ClawclawBehavior {
254
+ static override readonly manifest = manifest('long');
255
+ static instances = 0;
256
+ readonly instance = ++LongBehavior.instances;
257
+
258
+ override decide(input: Readonly<BehaviorInput>): BehaviorDecision {
259
+ return {
260
+ status: { summary: `long instance ${this.instance}` },
261
+ actions: [{ action: 'move', target_x: input.epochId, target_y: 1 }],
262
+ };
263
+ }
264
+ }
265
+
266
+ class ReportingLongBehavior extends ClawclawBehavior {
267
+ static override readonly manifest = manifest('reporting-long', {
268
+ name: 'Task only',
269
+ description: 'Complete assigned tasks.',
270
+ localizations: {
271
+ 'zh-CN': { name: '纯任务', description: '专心完成分配的任务。' },
272
+ },
273
+ });
274
+
275
+ override decide(): BehaviorDecision {
276
+ return { status: { summary: 'working' } };
277
+ }
278
+ }
279
+
280
+ class ReplacementLongBehavior extends ClawclawBehavior {
281
+ static override readonly manifest = manifest('replacement-long', {
282
+ name: '替代策略',
283
+ description: '替代策略描述。',
284
+ });
285
+
286
+ override decide(): BehaviorDecision {
287
+ return { status: { summary: 'replacement working' } };
288
+ }
289
+ }
290
+
291
+ class ReportingOverlayBehavior extends ClawclawBehavior {
292
+ static override readonly manifest = manifest('reporting-overlay', {
293
+ name: '短任务',
294
+ description: '不应上报为长程策略。',
295
+ runtime: { defaultMs: 10_000, deadlineOutcome: 'failed' },
296
+ });
297
+
298
+ override decide(): BehaviorDecision {
299
+ return { status: { summary: 'overlay working' } };
300
+ }
301
+ }
302
+
303
+ class FinishingShortBehavior extends ClawclawBehavior {
304
+ static override readonly manifest = manifest('short', {
305
+ runtime: { defaultMs: 10_000, deadlineOutcome: 'failed' },
306
+ });
307
+
308
+ override decide(): BehaviorDecision {
309
+ return {
310
+ status: { summary: 'short finished' },
311
+ finish: { outcome: 'completed', reason: 'done' },
312
+ };
313
+ }
314
+ }
315
+
316
+ class ReportBehavior extends ClawclawBehavior {
317
+ static override readonly manifest = manifest('report', {
318
+ runtime: { defaultMs: 10_000, deadlineOutcome: 'failed' },
319
+ });
320
+ private submitted = false;
321
+
322
+ override decide(input: Readonly<BehaviorInput>): BehaviorDecision {
323
+ if (this.submitted && input.gameState.phase === 'meeting') {
324
+ return { finish: { outcome: 'completed', reason: 'corpse_reported' } };
325
+ }
326
+ this.submitted = true;
327
+ return { actions: [{ action: 'report' }], status: { summary: 'reporting' } };
328
+ }
329
+ }
330
+
331
+ class CadenceBehavior extends ClawclawBehavior {
332
+ static override readonly manifest = manifest('cadence', { everyTicks: 3 });
333
+ static frames: BehaviorInput[] = [];
334
+ override decide(input: Readonly<BehaviorInput>): BehaviorDecision {
335
+ CadenceBehavior.frames.push(input as BehaviorInput);
336
+ return { status: { summary: `cadence tick ${input.gameState.tick}` } };
337
+ }
338
+ }
339
+
340
+ class GraceBehavior extends ClawclawBehavior {
341
+ static override readonly manifest = manifest('grace', {
342
+ runtime: { defaultMs: 5_000, deadlineOutcome: 'failed', controlGraceMs: 11_000 },
343
+ });
344
+ override decide(): void {}
345
+ }
346
+
347
+ class NormalizeFallbackBehavior extends ClawclawBehavior<Readonly<{ internal: string }>> {
348
+ static override readonly manifest = manifest('normalized-fallback', {
349
+ inputs: [{ id: 'public_value', type: 'string', required: true, description: 'value' }],
350
+ });
351
+ static normalizeCalls = 0;
352
+ override normalize(input: Readonly<Record<string, unknown>>) {
353
+ NormalizeFallbackBehavior.normalizeCalls += 1;
354
+ return { internal: `normalized:${String(input.public_value)}` } as const;
355
+ }
356
+ override decide(input: Readonly<BehaviorInput<Readonly<{ internal: string }>>>): BehaviorDecision {
357
+ return { status: { summary: input.input.internal } };
358
+ }
359
+ }
360
+
361
+ class EventFinishBehavior extends ClawclawBehavior {
362
+ static override readonly manifest = manifest('event-finish', {
363
+ runtime: { defaultMs: 10_000, deadlineOutcome: 'failed' },
364
+ produces: ['fixture.finished'],
365
+ });
366
+ override decide(): BehaviorDecision {
367
+ return {
368
+ events: [{ type: 'fixture.finished', payload: { ok: true } }],
369
+ finish: { outcome: 'completed', reason: 'done' },
370
+ };
371
+ }
372
+ }
373
+
374
+ class ActionFinishBehavior extends ClawclawBehavior {
375
+ static override readonly manifest = manifest('action-finish', {
376
+ runtime: { defaultMs: 10_000, deadlineOutcome: 'failed' },
377
+ });
378
+ override decide(): BehaviorDecision {
379
+ return {
380
+ actions: [{ action: 'move', target_x: 1, target_y: 2 }],
381
+ finish: { outcome: 'completed', reason: 'unsafe_same_decision' },
382
+ };
383
+ }
384
+ }
385
+
386
+ class SlowBehavior extends ClawclawBehavior {
387
+ static override readonly manifest = manifest('slow');
388
+ static onDecide: (() => void) | undefined;
389
+ override decide(): Promise<BehaviorDecision> {
390
+ SlowBehavior.onDecide?.();
391
+ return new Promise(() => {});
392
+ }
393
+ }
394
+
395
+ describe('Clawclaw unified Behavior plugin', () => {
396
+ it('runs a long Behavior and submits generic Behavior action preconditions', async () => {
397
+ const actions: Array<Record<string, any>> = [];
398
+ const plugin = new ClawclawBehaviorPlugin({
399
+ catalog: catalog([LongBehavior]),
400
+ driver: driver(),
401
+ createActivationId: () => 'long-1',
402
+ now: () => 0,
403
+ });
404
+ const ctx = context(actions);
405
+ plugin.start(ctx);
406
+ await plugin.startLong('long', {}, { source: 'agent' });
407
+
408
+ const result = await step(plugin, input(1), ctx);
409
+ expect(actions).toEqual([expect.objectContaining({
410
+ behaviorOriginEpochSeq: 1,
411
+ behaviorActionSafetyGeneration: 7,
412
+ behaviorActivationGeneration: 1,
413
+ action: { action: 'move', target_x: 1, target_y: 1 },
414
+ })]);
415
+ expect(result).toMatchObject({
416
+ outcome: 'processed',
417
+ states: [{
418
+ topic: CLAWCLAW_BEHAVIOR_STATE_TOPIC,
419
+ value: {
420
+ running: true,
421
+ activation_id: 'long-1',
422
+ behavior: 'long',
423
+ layer: 'long',
424
+ status: { summary: 'long instance 1' },
425
+ },
426
+ }],
427
+ events: [expect.objectContaining({ type: 'behavior.started' })],
428
+ });
429
+ });
430
+
431
+ it('reports the persistent long Behavior asynchronously and ignores a short overlay', async () => {
432
+ vi.useFakeTimers();
433
+ try {
434
+ let resolveReport!: (value: ReturnType<typeof successfulStrategyReportResult>) => void;
435
+ const pendingReport = new Promise<ReturnType<typeof successfulStrategyReportResult>>((resolve) => {
436
+ resolveReport = resolve;
437
+ });
438
+ const performAction = vi.fn(() => pendingReport);
439
+ const ctx = contextWithPerformAction(
440
+ performAction as RuntimeEpochPluginContext<Record<string, any>>['capabilities']['performAction'],
441
+ );
442
+ let id = 0;
443
+ const plugin = new ClawclawBehaviorPlugin({
444
+ catalog: catalog([ReportingLongBehavior, ReportingOverlayBehavior]),
445
+ driver: driver(),
446
+ createActivationId: () => `reporting-${++id}`,
447
+ now: () => 0,
448
+ });
449
+ await plugin.start(ctx);
450
+ await plugin.startLong('reporting-long', {}, { source: 'agent' });
451
+
452
+ await step(plugin, input(1), ctx);
453
+ expect(performAction).not.toHaveBeenCalled();
454
+ await vi.advanceTimersByTimeAsync(0);
455
+ expect(performAction).toHaveBeenCalledTimes(1);
456
+ expect(performAction).toHaveBeenCalledWith('clawclaw.action', {
457
+ route: 'game',
458
+ action: {
459
+ action: 'strategy',
460
+ name: '纯任务',
461
+ description: '专心完成分配的任务。',
462
+ },
463
+ });
464
+
465
+ resolveReport(successfulStrategyReportResult());
466
+ await Promise.resolve();
467
+ await Promise.resolve();
468
+ await plugin.startShort('reporting-overlay', {}, { source: 'agent' });
469
+ await step(plugin, input(2), ctx);
470
+ await vi.advanceTimersByTimeAsync(5_000);
471
+ expect(performAction).toHaveBeenCalledTimes(1);
472
+ await plugin.stop('shutdown');
473
+ } finally {
474
+ vi.useRealTimers();
475
+ }
476
+ });
477
+
478
+ it('retries an invalid backend Strategy report once per second until acknowledged', async () => {
479
+ vi.useFakeTimers();
480
+ try {
481
+ const performAction = vi.fn()
482
+ .mockResolvedValueOnce({
483
+ ...successfulStrategyReportResult(),
484
+ value: { success: true, data: { ok: false } },
485
+ })
486
+ .mockResolvedValue(successfulStrategyReportResult());
487
+ const ctx = contextWithPerformAction(
488
+ performAction as RuntimeEpochPluginContext<Record<string, any>>['capabilities']['performAction'],
489
+ );
490
+ const plugin = new ClawclawBehaviorPlugin({
491
+ catalog: catalog([ReportingLongBehavior]),
492
+ driver: driver(),
493
+ createActivationId: () => 'report-retry',
494
+ now: () => 0,
495
+ });
496
+ await plugin.start(ctx);
497
+ await plugin.startLong('reporting-long', {}, { source: 'agent' });
498
+
499
+ await step(plugin, input(1), ctx);
500
+ await vi.advanceTimersByTimeAsync(0);
501
+ expect(performAction).toHaveBeenCalledTimes(1);
502
+ await vi.advanceTimersByTimeAsync(999);
503
+ expect(performAction).toHaveBeenCalledTimes(1);
504
+ await vi.advanceTimersByTimeAsync(1);
505
+ expect(performAction).toHaveBeenCalledTimes(2);
506
+ await vi.advanceTimersByTimeAsync(5_000);
507
+ expect(performAction).toHaveBeenCalledTimes(2);
508
+ await plugin.stop('shutdown');
509
+ } finally {
510
+ vi.useRealTimers();
511
+ }
512
+ });
513
+
514
+ it('does not let an old in-flight acknowledgement confirm a replacement long Behavior', async () => {
515
+ vi.useFakeTimers();
516
+ try {
517
+ let resolveFirst!: (value: ReturnType<typeof successfulStrategyReportResult>) => void;
518
+ const first = new Promise<ReturnType<typeof successfulStrategyReportResult>>((resolve) => {
519
+ resolveFirst = resolve;
520
+ });
521
+ const performAction = vi.fn()
522
+ .mockImplementationOnce(() => first)
523
+ .mockResolvedValue(successfulStrategyReportResult());
524
+ const ctx = contextWithPerformAction(
525
+ performAction as RuntimeEpochPluginContext<Record<string, any>>['capabilities']['performAction'],
526
+ );
527
+ let id = 0;
528
+ const plugin = new ClawclawBehaviorPlugin({
529
+ catalog: catalog([ReportingLongBehavior, ReplacementLongBehavior]),
530
+ driver: driver(),
531
+ createActivationId: () => `replacement-${++id}`,
532
+ now: () => 0,
533
+ });
534
+ await plugin.start(ctx);
535
+ await plugin.startLong('reporting-long', {}, { source: 'agent' });
536
+ await step(plugin, input(1), ctx);
537
+ await vi.advanceTimersByTimeAsync(0);
538
+ expect(performAction).toHaveBeenCalledTimes(1);
539
+
540
+ await plugin.startLong('replacement-long', {}, { source: 'agent' });
541
+ await step(plugin, input(2), ctx);
542
+ await vi.advanceTimersByTimeAsync(0);
543
+ expect(performAction).toHaveBeenCalledTimes(1);
544
+
545
+ resolveFirst(successfulStrategyReportResult());
546
+ await Promise.resolve();
547
+ await Promise.resolve();
548
+ await vi.advanceTimersByTimeAsync(0);
549
+ expect(performAction).toHaveBeenCalledTimes(2);
550
+ expect(performAction.mock.calls[1]?.[1]).toMatchObject({
551
+ action: {
552
+ action: 'strategy',
553
+ name: '替代策略',
554
+ description: '替代策略描述。',
555
+ },
556
+ });
557
+ await plugin.stop('shutdown');
558
+ } finally {
559
+ vi.useRealTimers();
560
+ }
561
+ });
562
+
563
+ it('fresh-restarts the suspended long only after the shared 500ms delay', async () => {
564
+ LongBehavior.instances = 0;
565
+ const manager = new BehaviorActivationManager();
566
+ let id = 0;
567
+ const plugin = new ClawclawBehaviorPlugin({
568
+ catalog: catalog([LongBehavior, FinishingShortBehavior]),
569
+ manager,
570
+ driver: driver(),
571
+ createActivationId: () => `activation-${++id}`,
572
+ now: () => 0,
573
+ });
574
+ const ctx = context();
575
+ plugin.start(ctx);
576
+ await plugin.startLong('long', {}, { source: 'agent' });
577
+ await step(plugin, input(1, { nowMs: 100 }), ctx);
578
+ await plugin.startShort('short', {}, { source: 'agent' });
579
+ const shortResult = await step(plugin, input(2, { nowMs: 200 }), ctx);
580
+ expect(shortResult.events).toEqual(expect.arrayContaining([
581
+ expect.objectContaining({ type: 'behavior.suspended' }),
582
+ expect.objectContaining({ type: 'behavior.started' }),
583
+ expect.objectContaining({ type: 'behavior.completed' }),
584
+ ]));
585
+ expect(manager.current()).toBeUndefined();
586
+
587
+ await step(plugin, input(3, { nowMs: 699 }), ctx);
588
+ expect(manager.current()).toBeUndefined();
589
+ await step(plugin, input(4, { nowMs: 700 }), ctx);
590
+ expect(manager.current()).toMatchObject({
591
+ activationId: 'activation-1', instanceGeneration: 2,
592
+ });
593
+ const resumed = await step(plugin, input(5, { nowMs: 701 }), ctx);
594
+ expect(resumed.states).toEqual([
595
+ expect.objectContaining({
596
+ value: expect.objectContaining({ status: { summary: 'long instance 2' } }),
597
+ }),
598
+ ]);
599
+ });
600
+
601
+ it('lets a report short observe meeting authority before cancelling the wandering boundary', async () => {
602
+ const actions: Array<Record<string, any>> = [];
603
+ const plugin = new ClawclawBehaviorPlugin({
604
+ catalog: catalog([ReportBehavior]),
605
+ driver: driver(),
606
+ createActivationId: () => 'report-1',
607
+ now: () => 0,
608
+ });
609
+ const ctx = context(actions);
610
+ plugin.start(ctx);
611
+ await plugin.startShort('report', {}, { source: 'agent' });
612
+ await step(plugin, input(1, { nowMs: 100 }), ctx);
613
+ expect(actions).toHaveLength(1);
614
+
615
+ const result = await step(plugin, input(2, { phase: 'meeting', nowMs: 200 }), ctx);
616
+ expect(result.events).toEqual(expect.arrayContaining([
617
+ expect.objectContaining({
618
+ type: 'behavior.completed',
619
+ payload: expect.objectContaining({ reason: 'corpse_reported' }),
620
+ }),
621
+ ]));
622
+ expect(result.events).not.toEqual(expect.arrayContaining([
623
+ expect.objectContaining({ type: 'behavior.cancelled' }),
624
+ ]));
625
+ expect(plugin.status().running).toBe(false);
626
+ });
627
+
628
+ it('retains pending Events across cadence skips', async () => {
629
+ CadenceBehavior.frames = [];
630
+ const plugin = new ClawclawBehaviorPlugin({
631
+ catalog: catalog([CadenceBehavior]),
632
+ driver: driver(),
633
+ createActivationId: () => 'cadence-1',
634
+ now: () => 0,
635
+ });
636
+ const ctx = context();
637
+ plugin.start(ctx);
638
+ await plugin.startLong('cadence', {}, { source: 'agent' });
639
+ const first = await step(plugin, input(1, {
640
+ tick: 10, nowMs: 100, pendingEvents: [event(1)],
641
+ }), ctx);
642
+ expect(first.consumeEventsThroughCommitSeq).toBe(1);
643
+
644
+ const skipped = await step(plugin, input(2, {
645
+ tick: 12, nowMs: 200, pendingEvents: [event(2)],
646
+ }), ctx);
647
+ expect(skipped.consumeEventsThroughCommitSeq).toBeUndefined();
648
+ expect(skipped.states).toEqual([
649
+ expect.objectContaining({
650
+ value: expect.objectContaining({ status: { summary: 'cadence tick 10' } }),
651
+ }),
652
+ ]);
653
+ await step(plugin, input(3, {
654
+ tick: 13, nowMs: 300, pendingEvents: [event(2)],
655
+ }), ctx);
656
+ expect(CadenceBehavior.frames.map(frame => frame.gameState.tick)).toEqual([10, 13]);
657
+ expect(CadenceBehavior.frames[1]!.events.map(candidate => candidate.eventId)).toEqual(['event-2']);
658
+ });
659
+
660
+ it('extends a finite activation deadline by manifest controlGraceMs', async () => {
661
+ const plugin = new ClawclawBehaviorPlugin({
662
+ catalog: catalog([GraceBehavior]),
663
+ driver: driver(),
664
+ createActivationId: () => 'grace-1',
665
+ now: () => 0,
666
+ });
667
+ await plugin.start(context());
668
+ const activation = await plugin.startShort('grace', {}, { source: 'agent' });
669
+ expect(activation).toMatchObject({
670
+ maxRuntimeMs: 16_000,
671
+ deadlineAt: 16_000,
672
+ });
673
+ });
674
+
675
+ it('rearms a persisted fallback after a segment stop and normalizes its binding once', async () => {
676
+ NormalizeFallbackBehavior.normalizeCalls = 0;
677
+ let now = 0;
678
+ const plugin = new ClawclawBehaviorPlugin({
679
+ catalog: catalog([NormalizeFallbackBehavior]),
680
+ driver: driver(),
681
+ createActivationId: () => 'fallback-1',
682
+ now: () => now,
683
+ });
684
+ const ctx = context();
685
+ await plugin.start(ctx);
686
+ await plugin.bindFallback('normalized-fallback', { public_value: 'one' });
687
+ expect(NormalizeFallbackBehavior.normalizeCalls).toBe(1);
688
+ await step(plugin, input(1, { nowMs: 500 }), ctx);
689
+ expect(plugin.status().current).toMatchObject({ behaviorId: 'normalized-fallback' });
690
+ expect(NormalizeFallbackBehavior.normalizeCalls).toBe(1);
691
+
692
+ now = 600;
693
+ await plugin.stop('segment_ending');
694
+ now = 1_000;
695
+ await plugin.start(ctx);
696
+ await step(plugin, input(2, { nowMs: 1_499 }), ctx);
697
+ expect(plugin.status().current).toBeUndefined();
698
+ await step(plugin, input(3, { nowMs: 1_500 }), ctx);
699
+ expect(plugin.status().current).toMatchObject({ behaviorId: 'normalized-fallback' });
700
+ const restarted = await step(plugin, input(4, { nowMs: 1_501 }), ctx);
701
+ expect(restarted.states).toEqual([
702
+ expect.objectContaining({
703
+ value: expect.objectContaining({ status: { summary: 'normalized:one' } }),
704
+ }),
705
+ ]);
706
+ expect(NormalizeFallbackBehavior.normalizeCalls).toBe(1);
707
+ });
708
+
709
+ it('lazily binds the configured fallback after the authoritative role is known', async () => {
710
+ NormalizeFallbackBehavior.normalizeCalls = 0;
711
+ const plugin = new ClawclawBehaviorPlugin({
712
+ catalog: catalog([NormalizeFallbackBehavior]),
713
+ driver: driver(),
714
+ fallbackBehaviors: {
715
+ shrimp_generic: {
716
+ behaviorId: 'normalized-fallback',
717
+ input: { public_value: 'role-default' },
718
+ },
719
+ },
720
+ createActivationId: () => 'role-fallback-1',
721
+ now: () => 0,
722
+ });
723
+ const ctx = context();
724
+ await plugin.start(ctx);
725
+
726
+ await step(plugin, input(1, { nowMs: 0 }), ctx);
727
+ expect(NormalizeFallbackBehavior.normalizeCalls).toBe(1);
728
+ expect(plugin.status().current).toBeUndefined();
729
+ await step(plugin, input(2, { nowMs: 499 }), ctx);
730
+ expect(plugin.status().current).toBeUndefined();
731
+ await step(plugin, input(3, { nowMs: 500 }), ctx);
732
+ expect(plugin.status().current).toMatchObject({
733
+ behaviorId: 'normalized-fallback',
734
+ source: 'idle',
735
+ });
736
+ const running = await step(plugin, input(4, { nowMs: 501 }), ctx);
737
+ expect(running.states).toEqual([
738
+ expect.objectContaining({
739
+ value: expect.objectContaining({ status: { summary: 'normalized:role-default' } }),
740
+ }),
741
+ ]);
742
+ expect(NormalizeFallbackBehavior.normalizeCalls).toBe(1);
743
+ });
744
+
745
+ it('publishes decision Events before the completion lifecycle Event', async () => {
746
+ const plugin = new ClawclawBehaviorPlugin({
747
+ catalog: catalog([EventFinishBehavior]),
748
+ driver: driver(),
749
+ createActivationId: () => 'event-finish-1',
750
+ now: () => 0,
751
+ });
752
+ const ctx = context();
753
+ await plugin.start(ctx);
754
+ await plugin.startShort('event-finish', {}, { source: 'agent' });
755
+ const result = await step(plugin, input(1), ctx);
756
+ expect(result.events?.map(candidate => candidate.type)).toEqual([
757
+ 'behavior.started',
758
+ 'fixture.finished',
759
+ 'behavior.completed',
760
+ ]);
761
+ });
762
+
763
+ it('rejects actions and finish in the same Decision before submitting an Action', async () => {
764
+ const actions: Array<Record<string, any>> = [];
765
+ const plugin = new ClawclawBehaviorPlugin({
766
+ catalog: catalog([ActionFinishBehavior]),
767
+ driver: driver(),
768
+ createActivationId: () => 'action-finish-1',
769
+ now: () => 0,
770
+ });
771
+ const ctx = context(actions);
772
+ await plugin.start(ctx);
773
+ await plugin.startShort('action-finish', {}, { source: 'agent' });
774
+ const result = await step(plugin, input(1), ctx);
775
+ expect(actions).toEqual([]);
776
+ expect(result.events).toEqual(expect.arrayContaining([
777
+ expect.objectContaining({
778
+ type: 'behavior.failed',
779
+ payload: expect.objectContaining({ reason: 'behavior_finish_with_actions_invalid' }),
780
+ }),
781
+ ]));
782
+ });
783
+
784
+ it('interrupts a slow serial Decision before admitting a higher reflex', async () => {
785
+ let entered!: () => void;
786
+ const deciding = new Promise<void>((resolve) => { entered = resolve; });
787
+ SlowBehavior.onDecide = entered;
788
+ let id = 0;
789
+ const plugin = new ClawclawBehaviorPlugin({
790
+ catalog: catalog([SlowBehavior, GraceBehavior]),
791
+ driver: driver(),
792
+ createActivationId: () => `preempt-${++id}`,
793
+ decisionTimeoutMs: 10_000,
794
+ now: () => 0,
795
+ });
796
+ const ctx = context();
797
+ await plugin.start(ctx);
798
+ await plugin.startLong('slow', {}, { source: 'agent' });
799
+ const slowStep = step(plugin, input(1), ctx);
800
+ await deciding;
801
+
802
+ const reflex = await plugin.requestReflex({
803
+ source: 'trigger',
804
+ triggerId: 'danger',
805
+ scope: { sessionId: scope.sessionId, segmentId: scope.segmentId },
806
+ epochId: 2,
807
+ configGeneration: 1,
808
+ behavior: 'grace',
809
+ behaviorInput: {},
810
+ reflexPriority: 10,
811
+ maxRuntimeMs: 5_000,
812
+ reason: 'danger_detected',
813
+ }, { isCurrent: () => true });
814
+
815
+ expect(reflex).toMatchObject({ accepted: true });
816
+ await slowStep;
817
+ expect(plugin.status().current).toMatchObject({
818
+ behaviorId: 'grace',
819
+ layer: 'reflex',
820
+ });
821
+ });
822
+
823
+ it('rejects a Trigger request whose configuration changes during prepare', async () => {
824
+ let current = true;
825
+ const plugin = new ClawclawBehaviorPlugin({
826
+ catalog: catalog([GraceBehavior]),
827
+ driver: driver(),
828
+ createActivationId: () => 'stale-reflex',
829
+ now: () => 0,
830
+ });
831
+ await plugin.start(context());
832
+ const request = plugin.requestReflex({
833
+ source: 'trigger',
834
+ triggerId: 'changed-rule',
835
+ scope: { sessionId: scope.sessionId, segmentId: scope.segmentId },
836
+ epochId: 1,
837
+ configGeneration: 1,
838
+ behavior: 'grace',
839
+ behaviorInput: {},
840
+ reflexPriority: 1,
841
+ maxRuntimeMs: 5_000,
842
+ reason: 'old_configuration',
843
+ }, { isCurrent: () => current });
844
+ current = false;
845
+ await expect(request).resolves.toEqual({ accepted: false, reason: 'stale_request' });
846
+ expect(plugin.status().current).toBeUndefined();
847
+ });
848
+ });