@myclaw163/clawclaw-cli 0.7.16 → 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 +1 -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 +285 -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 +388 -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 -2175
  331. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.ts +0 -1774
  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,655 @@
1
+ import type {
2
+ ClawclawTrigger,
3
+ TriggerInput,
4
+ TriggerMatch,
5
+ TriggerRearm,
6
+ TriggerResetReason,
7
+ } from '../../../../sdk/trigger-plugin/index.js';
8
+ import {
9
+ MAX_TRIGGER_RUNTIME_MS,
10
+ TRIGGER_PLUGIN_API_VERSION,
11
+ } from '../../../../sdk/trigger-plugin/index.js';
12
+ import type {
13
+ BehaviorInput,
14
+ ObservationFrame,
15
+ } from '../../../../sdk/module-input/index.js';
16
+ import type {
17
+ RuntimeEpochPlugin,
18
+ RuntimeEpochPluginContext,
19
+ RuntimeEpochPluginInput,
20
+ RuntimeEpochPluginResult,
21
+ } from '../../../framework/plugins/contracts.js';
22
+ import { createBehaviorInput } from '../../behavior-input.js';
23
+ import { normalizeBehaviorInput } from '../../behavior-input-fields.js';
24
+ import { ClawclawBehaviorObservationMemory } from '../../behavior-observation-memory.js';
25
+ import { createBehaviorReadApi } from '../../behavior-read-api.js';
26
+ import { ObservationFrameProjector } from '../../observation-frame-projector.js';
27
+ import {
28
+ CLAWCLAW_TRIGGER_PLUGIN_ID,
29
+ type BehaviorReflexActivationDriver,
30
+ type BehaviorReflexActivationRequest,
31
+ type BehaviorReflexActivationResult,
32
+ type ClawclawTriggerEvaluation,
33
+ type ClawclawTriggerRegistration,
34
+ } from './contracts.js';
35
+ import { TriggerModuleLoader } from './trigger-module-loader.js';
36
+ import type { ResolvedClawclawTriggerSource } from './trigger-source.js';
37
+
38
+ const TRIGGER_COMPUTATION_SCHEMA = 1;
39
+ const TRIGGER_CHECKPOINT_SCHEMA = 1;
40
+ export const DEFAULT_TRIGGER_PLUGIN_TIMEOUT_MS = 2_000;
41
+
42
+ interface EffectiveTriggerConfig {
43
+ readonly source: ResolvedClawclawTriggerSource;
44
+ readonly enabled: boolean;
45
+ readonly input: Readonly<Record<string, unknown>>;
46
+ readonly behavior: string;
47
+ readonly behaviorInput: Readonly<Record<string, unknown>>;
48
+ readonly reflexPriority: number;
49
+ readonly cooldownMs: number;
50
+ readonly rearm: TriggerRearm;
51
+ readonly maxRuntimeMs: number;
52
+ }
53
+
54
+ interface TriggerSlot {
55
+ readonly config: EffectiveTriggerConfig;
56
+ readonly module: ClawclawTrigger;
57
+ }
58
+
59
+ interface TriggerRuntimeState {
60
+ armed: boolean;
61
+ lastAcceptedAtMs?: number;
62
+ }
63
+
64
+ interface TriggerComputationProposal {
65
+ readonly schema: typeof TRIGGER_COMPUTATION_SCHEMA;
66
+ readonly configGeneration: number;
67
+ readonly epochId: number;
68
+ readonly nowMs: number;
69
+ readonly eventCursor?: number;
70
+ readonly evaluations: readonly ClawclawTriggerEvaluation[];
71
+ }
72
+
73
+ interface TriggerCheckpoint {
74
+ readonly schema: typeof TRIGGER_CHECKPOINT_SCHEMA;
75
+ readonly states: Readonly<Record<string, Readonly<TriggerRuntimeState>>>;
76
+ }
77
+
78
+ export interface ClawclawTriggerPluginOptions {
79
+ readonly after?: readonly string[];
80
+ readonly triggers?: readonly ClawclawTriggerRegistration[];
81
+ readonly loader?: TriggerModuleLoader;
82
+ readonly driver?: BehaviorReflexActivationDriver;
83
+ }
84
+
85
+ function record(value: unknown): Record<string, unknown> | undefined {
86
+ return value && typeof value === 'object' && !Array.isArray(value)
87
+ ? value as Record<string, unknown>
88
+ : undefined;
89
+ }
90
+
91
+ function normalizeMatch(value: unknown): TriggerMatch | undefined {
92
+ if (value === undefined) return undefined;
93
+ const source = record(value);
94
+ if (!source) throw new Error('trigger_match_invalid');
95
+ const allowed = new Set(['reason', 'evidence', 'behaviorInput']);
96
+ for (const key of Object.keys(source)) {
97
+ if (!allowed.has(key)) throw new Error(`trigger_match_field_unknown:${key}`);
98
+ }
99
+ if (typeof source.reason !== 'string' || !source.reason.trim()) {
100
+ throw new Error('trigger_match_reason_invalid');
101
+ }
102
+ if (source.evidence !== undefined && !record(source.evidence)) {
103
+ throw new Error('trigger_match_evidence_invalid');
104
+ }
105
+ if (source.behaviorInput !== undefined && !record(source.behaviorInput)) {
106
+ throw new Error('trigger_match_behavior_input_invalid');
107
+ }
108
+ return Object.freeze(structuredClone({
109
+ reason: source.reason.trim(),
110
+ ...(source.evidence === undefined ? {} : { evidence: source.evidence }),
111
+ ...(source.behaviorInput === undefined ? {} : { behaviorInput: source.behaviorInput }),
112
+ })) as TriggerMatch;
113
+ }
114
+
115
+ function normalizeRegistration(value: ClawclawTriggerRegistration): EffectiveTriggerConfig {
116
+ const { source } = value;
117
+ const manifest = source.manifest;
118
+ if (!source || source.id !== manifest.id) throw new Error('trigger_source_identity_invalid');
119
+ const input = normalizeBehaviorInput(value.input ?? {}, manifest.inputs);
120
+ const behavior = value.behavior ?? manifest.defaultBehavior;
121
+ const behaviorInput = {
122
+ ...structuredClone(manifest.defaultBehaviorInput),
123
+ ...structuredClone(value.behaviorInput ?? {}),
124
+ };
125
+ const reflexPriority = value.reflexPriority ?? manifest.defaultReflexPriority;
126
+ const cooldownMs = value.cooldownMs ?? manifest.defaultCooldownMs;
127
+ const rearm = value.rearm ?? manifest.defaultRearm;
128
+ const maxRuntimeMs = value.maxRuntimeMs ?? manifest.defaultMaxRuntimeMs;
129
+ if (typeof behavior !== 'string' || !/^[a-z0-9][a-z0-9._-]*$/.test(behavior)) {
130
+ throw new Error('trigger_behavior_invalid');
131
+ }
132
+ if (!Number.isSafeInteger(reflexPriority)) throw new Error('trigger_reflex_priority_invalid');
133
+ if (!Number.isSafeInteger(cooldownMs) || cooldownMs < 0) throw new Error('trigger_cooldown_ms_invalid');
134
+ if (rearm !== 'after_clear' && rearm !== 'after_cooldown') throw new Error('trigger_rearm_invalid');
135
+ if (
136
+ !Number.isSafeInteger(maxRuntimeMs)
137
+ || maxRuntimeMs <= 0
138
+ || maxRuntimeMs > MAX_TRIGGER_RUNTIME_MS
139
+ ) {
140
+ throw new Error('trigger_max_runtime_ms_invalid');
141
+ }
142
+ return Object.freeze({
143
+ source,
144
+ enabled: value.enabled,
145
+ input,
146
+ behavior,
147
+ behaviorInput: Object.freeze(behaviorInput),
148
+ reflexPriority,
149
+ cooldownMs,
150
+ rearm,
151
+ maxRuntimeMs,
152
+ });
153
+ }
154
+
155
+ function normalizeRegistrations(
156
+ values: readonly ClawclawTriggerRegistration[],
157
+ ): Map<string, EffectiveTriggerConfig> {
158
+ const result = new Map<string, EffectiveTriggerConfig>();
159
+ for (const value of values) {
160
+ const normalized = normalizeRegistration(value);
161
+ if (result.has(normalized.source.id)) {
162
+ throw new Error(`trigger_registration_duplicate:${normalized.source.id}`);
163
+ }
164
+ result.set(normalized.source.id, normalized);
165
+ }
166
+ return result;
167
+ }
168
+
169
+ function proposal(value: unknown): TriggerComputationProposal {
170
+ const parsed = record(value);
171
+ if (
172
+ parsed?.schema !== TRIGGER_COMPUTATION_SCHEMA
173
+ || !Number.isSafeInteger(parsed.configGeneration)
174
+ || !Number.isSafeInteger(parsed.epochId)
175
+ || typeof parsed.nowMs !== 'number'
176
+ || !Array.isArray(parsed.evaluations)
177
+ ) throw new Error('trigger_computation_invalid');
178
+ return parsed as unknown as TriggerComputationProposal;
179
+ }
180
+
181
+ function diagnosticErrorCode(error: unknown): string {
182
+ const message = error instanceof Error ? error.message : String(error);
183
+ return /^[a-z0-9_.:-]+$/i.test(message) ? message.slice(0, 160) : 'TRIGGER_MODULE_FAILED';
184
+ }
185
+
186
+ function triggerInputFor(
187
+ frame: Readonly<ObservationFrame>,
188
+ semanticInput: Readonly<BehaviorInput>,
189
+ config: EffectiveTriggerConfig,
190
+ ): Readonly<TriggerInput> {
191
+ const consumes = new Set(config.source.manifest.consumes);
192
+ const events = consumes.has('*')
193
+ ? semanticInput.events
194
+ : semanticInput.events.filter((event) => consumes.has(event.type));
195
+ return Object.freeze({
196
+ frame,
197
+ events: Object.freeze(events),
198
+ input: config.input,
199
+ });
200
+ }
201
+
202
+ function behaviorInputForTrigger(
203
+ frame: Readonly<ObservationFrame>,
204
+ semanticInput: Readonly<BehaviorInput>,
205
+ triggerInput: Readonly<TriggerInput>,
206
+ ): Readonly<BehaviorInput> {
207
+ return Object.freeze({
208
+ epochId: semanticInput.epochId,
209
+ scope: semanticInput.scope,
210
+ nowMs: frame.timeMs,
211
+ gameState: frame.gameState,
212
+ events: triggerInput.events,
213
+ input: triggerInput.input,
214
+ });
215
+ }
216
+
217
+ function triggerLifecycle(frame: Readonly<ObservationFrame>): string {
218
+ const phase = frame.gameState.phase ?? 'unknown';
219
+ return phase === 'wandering' && frame.gameState.you?.is_alive === false
220
+ ? 'dead'
221
+ : phase;
222
+ }
223
+
224
+ /**
225
+ * Ordered Trigger host. Trigger and Perception project the same Source frame
226
+ * independently and have no scheduler dependency on each other. Trigger
227
+ * delegates at most one same-epoch Reflex request to the narrow Behavior
228
+ * activation boundary.
229
+ */
230
+ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string, any>> {
231
+ readonly kind = 'epoch' as const;
232
+ readonly id = CLAWCLAW_TRIGGER_PLUGIN_ID;
233
+ readonly version = String(TRIGGER_PLUGIN_API_VERSION);
234
+ readonly after: readonly string[];
235
+ readonly consumes = { events: ['*'] } as const;
236
+ readonly catchUp = 'strict_ordered' as const;
237
+ readonly maxInFlight = 1;
238
+ readonly timeoutMs = DEFAULT_TRIGGER_PLUGIN_TIMEOUT_MS;
239
+ readonly failurePolicy = 'failed_completion' as const;
240
+
241
+ private registrations: Map<string, EffectiveTriggerConfig>;
242
+ private readonly loader: TriggerModuleLoader;
243
+ private readonly slots = new Map<string, TriggerSlot>();
244
+ private readonly loadFailures = new Set<string>();
245
+ private readonly states = new Map<string, TriggerRuntimeState>();
246
+ private readonly observationMemory = new ClawclawBehaviorObservationMemory();
247
+ private readonly projector = new ObservationFrameProjector();
248
+ private driver?: BehaviorReflexActivationDriver;
249
+ private configGeneration = 1;
250
+ private started = false;
251
+ private lastFrameSeq = 0;
252
+ private lastVisualTick: number | null = null;
253
+ private lastConnectionId: string | null = null;
254
+ private lifecyclePhase: string | null = null;
255
+
256
+ constructor(options: ClawclawTriggerPluginOptions = {}) {
257
+ this.after = [...(options.after ?? [])];
258
+ this.registrations = normalizeRegistrations(options.triggers ?? []);
259
+ this.loader = options.loader ?? new TriggerModuleLoader();
260
+ this.driver = options.driver;
261
+ }
262
+
263
+ attachDriver(driver: BehaviorReflexActivationDriver): void {
264
+ if (this.driver && this.driver !== driver) throw new Error('trigger_activation_driver_already_attached');
265
+ this.driver = driver;
266
+ }
267
+
268
+ /** Atomically replace effective config; newly enabled modules import on the next ordered boundary. */
269
+ configure(triggers: readonly ClawclawTriggerRegistration[]): void {
270
+ const next = normalizeRegistrations(triggers);
271
+ this.configGeneration += 1;
272
+ this.registrations = next;
273
+ this.slots.clear();
274
+ this.loadFailures.clear();
275
+ this.states.clear();
276
+ this.observationMemory.clear();
277
+ this.clearFrameBoundary();
278
+ this.loader.stop();
279
+ }
280
+
281
+ descriptors(): readonly Readonly<{
282
+ id: string;
283
+ enabled: boolean;
284
+ behavior: string;
285
+ reflexPriority: number;
286
+ cooldownMs: number;
287
+ rearm: TriggerRearm;
288
+ maxRuntimeMs: number;
289
+ }>[] {
290
+ return [...this.registrations.values()].map((entry) => Object.freeze({
291
+ id: entry.source.id,
292
+ enabled: entry.enabled,
293
+ behavior: entry.behavior,
294
+ reflexPriority: entry.reflexPriority,
295
+ cooldownMs: entry.cooldownMs,
296
+ rearm: entry.rearm,
297
+ maxRuntimeMs: entry.maxRuntimeMs,
298
+ }));
299
+ }
300
+
301
+ async start(context: RuntimeEpochPluginContext<Record<string, any>>): Promise<void> {
302
+ this.started = true;
303
+ await this.ensureModules(context);
304
+ }
305
+
306
+ recover(context: RuntimeEpochPluginContext<Record<string, any>>): void {
307
+ const checkpoint = record(context.checkpoint());
308
+ if (checkpoint?.schema !== TRIGGER_CHECKPOINT_SCHEMA) return;
309
+ const states = record(checkpoint.states);
310
+ if (!states) return;
311
+ for (const [triggerId, value] of Object.entries(states)) {
312
+ if (!this.registrations.has(triggerId)) continue;
313
+ const state = record(value);
314
+ if (!state || typeof state.armed !== 'boolean') continue;
315
+ if (state.lastAcceptedAtMs !== undefined && typeof state.lastAcceptedAtMs !== 'number') continue;
316
+ this.states.set(triggerId, {
317
+ armed: state.armed,
318
+ ...(state.lastAcceptedAtMs === undefined ? {} : {
319
+ lastAcceptedAtMs: state.lastAcceptedAtMs,
320
+ }),
321
+ });
322
+ }
323
+ }
324
+
325
+ async update(
326
+ input: RuntimeEpochPluginInput<Record<string, any>>,
327
+ context: RuntimeEpochPluginContext<Record<string, any>>,
328
+ ): Promise<RuntimeEpochPluginResult> {
329
+ await this.ensureModules(context);
330
+ const generation = this.configGeneration;
331
+ const eventCursor = input.pendingEvents.at(-1)?.commitSeq;
332
+ // Trigger observes only backend-pushed Events. Every Epoch Plugin output,
333
+ // including DerivedEvent, Perception, and Behavior, is local_synth and is
334
+ // excluded so rule evaluation has no hidden computation-plugin dependency.
335
+ const triggerVisibleInput = {
336
+ ...input,
337
+ pendingEvents: input.pendingEvents.filter((event) => event.producer === 'backend_push'),
338
+ } satisfies RuntimeEpochPluginInput<Record<string, any>>;
339
+ const emptyInput = createBehaviorInput(triggerVisibleInput, Object.freeze({}));
340
+ if (
341
+ !emptyInput
342
+ || emptyInput.gameState.phase !== 'wandering'
343
+ || emptyInput.gameState.you?.is_alive === false
344
+ ) {
345
+ if (this.lastVisualTick !== null) {
346
+ await this.resetModules('phase_changed', context);
347
+ this.clearFrameBoundary();
348
+ }
349
+ return {
350
+ outcome: 'processed',
351
+ reason: 'trigger_ineligible_state',
352
+ proposal: {
353
+ schema: TRIGGER_COMPUTATION_SCHEMA,
354
+ configGeneration: generation,
355
+ epochId: input.epoch.epochSeq,
356
+ nowMs: input.frame.observedAtMs ?? input.frame.receivedAtMs,
357
+ ...(eventCursor === undefined ? {} : { eventCursor }),
358
+ evaluations: [],
359
+ } satisfies TriggerComputationProposal,
360
+ };
361
+ }
362
+ const projected = this.projector.project(input.frame);
363
+ if (!projected) {
364
+ if (this.lastVisualTick !== null) {
365
+ await this.resetModules('trajectory_gap', context);
366
+ this.clearFrameBoundary();
367
+ }
368
+ return {
369
+ outcome: 'processed',
370
+ reason: 'trigger_observation_unavailable',
371
+ proposal: {
372
+ schema: TRIGGER_COMPUTATION_SCHEMA,
373
+ configGeneration: generation,
374
+ epochId: input.epoch.epochSeq,
375
+ nowMs: emptyInput.nowMs,
376
+ ...(eventCursor === undefined ? {} : { eventCursor }),
377
+ evaluations: [],
378
+ } satisfies TriggerComputationProposal,
379
+ };
380
+ }
381
+ const stateFrameGap = this.lastFrameSeq > 0 && input.frame.frameSeq > this.lastFrameSeq + 1;
382
+ const tickDelta = this.lastVisualTick === null ? null : projected.tick - this.lastVisualTick;
383
+ const lifecycle = triggerLifecycle(projected);
384
+ const phaseChanged = this.lifecyclePhase !== null && this.lifecyclePhase !== lifecycle;
385
+ const continuousFromPrevious = !stateFrameGap
386
+ && !phaseChanged
387
+ && tickDelta !== null
388
+ && tickDelta >= 0
389
+ && tickDelta <= 3
390
+ && this.lastConnectionId === input.frame.connectionId;
391
+ const frame: Readonly<ObservationFrame> = Object.freeze({
392
+ ...projected,
393
+ tickDelta,
394
+ continuousFromPrevious,
395
+ });
396
+ const gap = this.lastVisualTick !== null && !phaseChanged && !continuousFromPrevious;
397
+ if (gap || phaseChanged) {
398
+ await this.resetModules(gap ? 'trajectory_gap' : 'phase_changed', context);
399
+ }
400
+ this.lastFrameSeq = input.frame.frameSeq;
401
+ this.lastVisualTick = frame.tick;
402
+ this.lastConnectionId = input.frame.connectionId;
403
+ this.lifecyclePhase = lifecycle;
404
+
405
+ const observationSnapshot = this.observationMemory.capture(emptyInput);
406
+ const slots = [...this.slots.values()].sort((left, right) => (
407
+ left.config.source.id.localeCompare(right.config.source.id)
408
+ ));
409
+ const settled = await Promise.allSettled(slots.map(async (slot): Promise<ClawclawTriggerEvaluation> => {
410
+ const triggerInput = triggerInputFor(frame, emptyInput, slot.config);
411
+ const readInput = behaviorInputForTrigger(frame, emptyInput, triggerInput);
412
+ const isActive = (): boolean => (
413
+ generation === this.configGeneration
414
+ && this.slots.get(slot.config.source.id) === slot
415
+ );
416
+ try {
417
+ const value = await slot.module.evaluate(
418
+ triggerInput,
419
+ createBehaviorReadApi(readInput, { isActive, observationSnapshot }),
420
+ );
421
+ if (!isActive()) return { triggerId: slot.config.source.id, outcome: 'error' };
422
+ const match = normalizeMatch(value);
423
+ return match
424
+ ? { triggerId: slot.config.source.id, outcome: 'match', match }
425
+ : { triggerId: slot.config.source.id, outcome: 'clear' };
426
+ } catch (error) {
427
+ context.diagnostic('trigger.module.failed', {
428
+ trigger_id: slot.config.source.id,
429
+ operation: 'evaluate',
430
+ error_code: diagnosticErrorCode(error),
431
+ }, 'error');
432
+ return { triggerId: slot.config.source.id, outcome: 'error' };
433
+ }
434
+ }));
435
+ const evaluations = settled.map((result, index): ClawclawTriggerEvaluation => {
436
+ if (result.status === 'fulfilled') return result.value;
437
+ const triggerId = slots[index]!.config.source.id;
438
+ context.diagnostic('trigger.module.failed', {
439
+ trigger_id: triggerId,
440
+ operation: 'evaluate',
441
+ error_code: diagnosticErrorCode(result.reason),
442
+ }, 'error');
443
+ return { triggerId, outcome: 'error' };
444
+ });
445
+ return {
446
+ outcome: 'processed',
447
+ reason: evaluations.some((entry) => entry.outcome === 'match')
448
+ ? 'trigger_match_computed'
449
+ : 'trigger_no_match',
450
+ proposal: {
451
+ schema: TRIGGER_COMPUTATION_SCHEMA,
452
+ configGeneration: generation,
453
+ epochId: input.epoch.epochSeq,
454
+ nowMs: frame.timeMs,
455
+ ...(eventCursor === undefined ? {} : { eventCursor }),
456
+ evaluations,
457
+ } satisfies TriggerComputationProposal,
458
+ };
459
+ }
460
+
461
+ async commit(
462
+ input: RuntimeEpochPluginInput<Record<string, any>>,
463
+ computation: Readonly<RuntimeEpochPluginResult>,
464
+ context: RuntimeEpochPluginContext<Record<string, any>>,
465
+ ): Promise<RuntimeEpochPluginResult> {
466
+ const computed = proposal(computation.proposal);
467
+ if (computed.configGeneration !== this.configGeneration) {
468
+ return {
469
+ outcome: 'noop',
470
+ reason: 'trigger_config_superseded',
471
+ checkpoint: this.checkpoint(),
472
+ };
473
+ }
474
+
475
+ for (const evaluation of computed.evaluations) {
476
+ if (evaluation.outcome !== 'clear') continue;
477
+ const config = this.registrations.get(evaluation.triggerId);
478
+ if (config?.rearm !== 'after_clear') continue;
479
+ const state = this.stateFor(evaluation.triggerId);
480
+ state.armed = true;
481
+ }
482
+
483
+ const candidates = computed.evaluations.flatMap((evaluation) => {
484
+ if (evaluation.outcome !== 'match' || !evaluation.match) return [];
485
+ const config = this.registrations.get(evaluation.triggerId);
486
+ if (!config?.enabled) return [];
487
+ const state = this.stateFor(evaluation.triggerId);
488
+ if (config.rearm === 'after_clear' && !state.armed) return [];
489
+ if (
490
+ state.lastAcceptedAtMs !== undefined
491
+ && computed.nowMs - state.lastAcceptedAtMs < config.cooldownMs
492
+ ) return [];
493
+ return [{ config, match: evaluation.match }];
494
+ }).sort((left, right) => {
495
+ if (left.config.reflexPriority !== right.config.reflexPriority) {
496
+ return left.config.reflexPriority > right.config.reflexPriority ? -1 : 1;
497
+ }
498
+ return left.config.source.id.localeCompare(right.config.source.id);
499
+ });
500
+
501
+ let activationResult: BehaviorReflexActivationResult | undefined;
502
+ const selected = candidates[0];
503
+ if (selected) {
504
+ const request: BehaviorReflexActivationRequest = Object.freeze({
505
+ source: 'trigger',
506
+ triggerId: selected.config.source.id,
507
+ scope: Object.freeze({
508
+ sessionId: input.epoch.scope.sessionId,
509
+ segmentId: input.epoch.scope.segmentId,
510
+ }),
511
+ epochId: computed.epochId,
512
+ configGeneration: computed.configGeneration,
513
+ behavior: selected.config.behavior,
514
+ behaviorInput: Object.freeze({
515
+ ...structuredClone(selected.config.behaviorInput),
516
+ ...structuredClone(selected.match.behaviorInput ?? {}),
517
+ }),
518
+ reflexPriority: selected.config.reflexPriority,
519
+ maxRuntimeMs: selected.config.maxRuntimeMs,
520
+ reason: selected.match.reason,
521
+ ...(selected.match.evidence === undefined ? {} : {
522
+ evidence: structuredClone(selected.match.evidence),
523
+ }),
524
+ });
525
+ if (!this.driver) {
526
+ activationResult = { accepted: false, reason: 'activation_driver_unavailable' };
527
+ context.diagnostic('trigger.activation.rejected', {
528
+ trigger_id: request.triggerId,
529
+ reason: activationResult.reason,
530
+ }, 'error');
531
+ } else {
532
+ try {
533
+ activationResult = await this.driver.requestReflex(request, {
534
+ isCurrent: () => computed.configGeneration === this.configGeneration,
535
+ });
536
+ } catch (error) {
537
+ activationResult = { accepted: false, reason: 'activation_driver_failed' };
538
+ context.diagnostic('trigger.activation.rejected', {
539
+ trigger_id: request.triggerId,
540
+ reason: activationResult.reason,
541
+ error_code: diagnosticErrorCode(error),
542
+ }, 'error');
543
+ }
544
+ }
545
+ if (activationResult.accepted) {
546
+ const state = this.stateFor(request.triggerId);
547
+ state.lastAcceptedAtMs = computed.nowMs;
548
+ if (selected.config.rearm === 'after_clear') state.armed = false;
549
+ context.diagnostic('trigger.activation.accepted', {
550
+ trigger_id: request.triggerId,
551
+ behavior_id: request.behavior,
552
+ activation_id: activationResult.activationId,
553
+ reflex_priority: request.reflexPriority,
554
+ ...(activationResult.replacedActivationId === undefined ? {} : {
555
+ replaced_activation_id: activationResult.replacedActivationId,
556
+ }),
557
+ });
558
+ } else {
559
+ context.diagnostic('trigger.activation.rejected', {
560
+ trigger_id: request.triggerId,
561
+ behavior_id: request.behavior,
562
+ reason: activationResult.reason,
563
+ reflex_priority: request.reflexPriority,
564
+ });
565
+ }
566
+ }
567
+
568
+ return {
569
+ outcome: activationResult?.accepted ? 'processed' : 'noop',
570
+ reason: activationResult?.accepted
571
+ ? 'trigger_activation_accepted'
572
+ : selected ? `trigger_activation_rejected:${activationResult?.reason ?? 'unknown'}` : 'trigger_no_eligible_match',
573
+ checkpoint: this.checkpoint(),
574
+ ...(computed.eventCursor === undefined ? {} : {
575
+ consumeEventsThroughCommitSeq: computed.eventCursor,
576
+ }),
577
+ };
578
+ }
579
+
580
+ async stop(reason: 'segment_ending' | 'shutdown'): Promise<void> {
581
+ await this.resetModules(reason, undefined);
582
+ this.started = false;
583
+ this.configGeneration += 1;
584
+ this.slots.clear();
585
+ this.loadFailures.clear();
586
+ this.states.clear();
587
+ this.observationMemory.clear();
588
+ this.clearFrameBoundary();
589
+ this.loader.stop();
590
+ }
591
+
592
+ private async ensureModules(context: RuntimeEpochPluginContext<Record<string, any>>): Promise<void> {
593
+ if (!this.started) return;
594
+ const enabled = [...this.registrations.values()].filter((entry) => entry.enabled);
595
+ await Promise.all(enabled.map(async (config) => {
596
+ const id = config.source.id;
597
+ if (this.slots.has(id) || this.loadFailures.has(id)) return;
598
+ try {
599
+ const ModuleClass = await this.loader.load(config.source);
600
+ if (!this.started || this.registrations.get(id) !== config) return;
601
+ this.slots.set(id, { config, module: new ModuleClass() });
602
+ } catch (error) {
603
+ if (!this.started || this.registrations.get(id) !== config) return;
604
+ this.loadFailures.add(id);
605
+ context.diagnostic('trigger.module.failed', {
606
+ trigger_id: id,
607
+ operation: 'load',
608
+ error_code: diagnosticErrorCode(error),
609
+ }, 'error');
610
+ }
611
+ }));
612
+ }
613
+
614
+ private stateFor(triggerId: string): TriggerRuntimeState {
615
+ let state = this.states.get(triggerId);
616
+ if (!state) {
617
+ state = { armed: true };
618
+ this.states.set(triggerId, state);
619
+ }
620
+ return state;
621
+ }
622
+
623
+ private async resetModules(
624
+ reason: TriggerResetReason,
625
+ context: RuntimeEpochPluginContext<Record<string, any>> | undefined,
626
+ ): Promise<void> {
627
+ await Promise.all([...this.slots.values()].map(async (slot) => {
628
+ if (!slot.module.reset) return;
629
+ try {
630
+ await slot.module.reset(reason);
631
+ } catch (error) {
632
+ context?.diagnostic('trigger.module.failed', {
633
+ trigger_id: slot.config.source.id,
634
+ operation: 'reset',
635
+ error_code: diagnosticErrorCode(error),
636
+ }, 'error');
637
+ }
638
+ }));
639
+ }
640
+
641
+ private clearFrameBoundary(): void {
642
+ this.projector.reset();
643
+ this.lastFrameSeq = 0;
644
+ this.lastVisualTick = null;
645
+ this.lastConnectionId = null;
646
+ this.lifecyclePhase = null;
647
+ }
648
+
649
+ private checkpoint(): TriggerCheckpoint {
650
+ return {
651
+ schema: TRIGGER_CHECKPOINT_SCHEMA,
652
+ states: Object.fromEntries([...this.states].map(([id, state]) => [id, { ...state }])),
653
+ };
654
+ }
655
+ }