@myclaw163/clawclaw-cli 0.6.111 → 0.7.4

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 (418) hide show
  1. package/QUICKSTART.md +46 -0
  2. package/QUICKSTART_HERMES.md +134 -0
  3. package/QUICKSTART_OPENCLAW.md +134 -0
  4. package/QUICKSTART_OTHER.md +134 -0
  5. package/README.md +23 -398
  6. package/bin/clawclaw-cli.mjs +9 -1
  7. package/docs/configuration.md +197 -0
  8. package/docs/runtime/README.md +52 -0
  9. package/docs/runtime/agent-notifications.md +55 -0
  10. package/docs/runtime/components-and-boundaries.md +213 -0
  11. package/docs/runtime/events-and-state.md +105 -0
  12. package/docs/runtime/owner-lifecycle-and-observability.md +69 -0
  13. package/docs/runtime/perception-replay.md +51 -0
  14. package/docs/runtime/short-commands-and-capabilities.md +55 -0
  15. package/docs/runtime/strategy-runtime.md +111 -0
  16. package/docs//350/207/252/345/256/232/344/271/211/346/204/237/347/237/245.md +488 -0
  17. package/docs//350/207/252/345/256/232/344/271/211/347/255/226/347/225/245.md +395 -0
  18. package/package.json +24 -7
  19. package/scripts/check-skill-command-surface.mjs +16 -7
  20. package/scripts/compare-perception-replays.test.ts +188 -0
  21. package/scripts/compare-perception-replays.ts +589 -0
  22. package/scripts/generate-spatial-facts.py +246 -0
  23. package/scripts/package-readme.mjs +48 -0
  24. package/scripts/replay-perception.ts +347 -0
  25. package/scripts/sync-frontend-map.mjs +195 -0
  26. package/scripts/watch-perception-events.test.ts +43 -0
  27. package/scripts/watch-perception-events.ts +162 -0
  28. package/skills/clawclaw/SKILL.md +120 -64
  29. package/skills/clawclaw/references/CHATTERBOX.md +2 -4
  30. package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +1 -1
  31. package/skills/clawclaw/references/COMMANDS.md +95 -61
  32. package/skills/clawclaw/references/GAME-MECHANICS.md +18 -8
  33. package/skills/clawclaw/references/HUB.md +5 -5
  34. package/skills/clawclaw/references/STRATEGIES.md +34 -17
  35. package/skills/clawclaw/references/STREAM.md +82 -46
  36. package/src/assets/clawclaw-map.json +1692 -0
  37. package/src/assets/clawclaw-spatial-facts.json +1291 -0
  38. package/src/cli.ts +21 -47
  39. package/src/commands/account.test.ts +229 -50
  40. package/src/commands/account.ts +456 -223
  41. package/src/commands/communication.test.ts +259 -0
  42. package/src/commands/communication.ts +391 -0
  43. package/src/commands/competition.test.ts +116 -0
  44. package/src/commands/competition.ts +50 -28
  45. package/src/commands/data.test.ts +57 -1
  46. package/src/commands/data.ts +79 -4
  47. package/src/commands/events-canonical-state.test.ts +187 -0
  48. package/src/commands/events.test.ts +50 -136
  49. package/src/commands/events.ts +175 -241
  50. package/src/commands/game/index.test.ts +510 -0
  51. package/src/commands/game/index.ts +556 -0
  52. package/src/commands/game-map.test.ts +40 -3
  53. package/src/commands/hub.ts +2 -9
  54. package/src/commands/load.test.ts +12 -2
  55. package/src/commands/load.ts +15 -2
  56. package/src/commands/peek.ts +2 -3
  57. package/src/commands/perception.test.ts +46 -0
  58. package/src/commands/perception.ts +92 -0
  59. package/src/commands/setup/codex.ts +0 -1
  60. package/src/commands/strategy.test.ts +139 -83
  61. package/src/commands/strategy.ts +175 -125
  62. package/src/commands/upgrade.ts +0 -21
  63. package/src/lib/auth.test.ts +35 -0
  64. package/src/lib/auth.ts +45 -6
  65. package/src/lib/diagnostics-config.test.ts +59 -0
  66. package/src/lib/diagnostics-config.ts +76 -0
  67. package/src/lib/game-client.test.ts +166 -0
  68. package/src/lib/game-client.ts +316 -87
  69. package/src/lib/game-context.ts +29 -0
  70. package/src/lib/gameplay-config.test.ts +66 -0
  71. package/src/lib/gameplay-config.ts +151 -0
  72. package/src/lib/http-transport.test.ts +63 -0
  73. package/src/lib/http-transport.ts +76 -10
  74. package/src/lib/init-command.test.ts +25 -1
  75. package/src/lib/init-command.ts +66 -1
  76. package/src/lib/participation-leave.ts +78 -0
  77. package/src/lib/perception-config.test.ts +138 -0
  78. package/src/lib/perception-config.ts +101 -0
  79. package/src/lib/room.test.ts +14 -0
  80. package/src/lib/room.ts +28 -2
  81. package/src/lib/server-registry.test.ts +15 -5
  82. package/src/lib/server-registry.ts +9 -10
  83. package/src/lib/strategy-export.test.ts +123 -44
  84. package/src/lib/strategy-export.ts +111 -101
  85. package/src/lib/user-data.test.ts +2 -0
  86. package/src/lib/user-data.ts +17 -16
  87. package/src/pipeline/canonical-event-presentation.test.ts +195 -0
  88. package/src/pipeline/canonical-event-presentation.ts +71 -0
  89. package/src/pipeline/event-format.test.ts +357 -59
  90. package/src/pipeline/event-format.ts +365 -80
  91. package/src/pipeline/event-hints.test.ts +241 -0
  92. package/src/pipeline/event-hints.ts +202 -51
  93. package/src/pipeline/game-sync-event-normalization.test.ts +239 -0
  94. package/src/pipeline/game-sync-event-normalization.ts +215 -0
  95. package/src/pipeline/player-projection.test.ts +164 -102
  96. package/src/pipeline/player-projection.ts +194 -235
  97. package/src/runtime/canonical-event-emitter.test.ts +70 -0
  98. package/src/runtime/canonical-event-emitter.ts +78 -0
  99. package/src/runtime/canonical-monitor.test.ts +575 -0
  100. package/src/runtime/canonical-monitor.ts +388 -0
  101. package/src/runtime/clawclaw/agent-event-policy.test.ts +27 -0
  102. package/src/runtime/clawclaw/agent-event-policy.ts +35 -0
  103. package/src/runtime/clawclaw/index.ts +4 -0
  104. package/src/runtime/clawclaw/notifications.test.ts +47 -0
  105. package/src/runtime/clawclaw/notifications.ts +65 -0
  106. package/src/runtime/clawclaw/owner-lock.test.ts +221 -0
  107. package/src/runtime/clawclaw/owner.ts +945 -0
  108. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +299 -0
  109. package/src/runtime/clawclaw/plugins/action/index.ts +1 -0
  110. package/src/runtime/clawclaw/plugins/assembly.test.ts +81 -0
  111. package/src/runtime/clawclaw/plugins/assembly.ts +116 -0
  112. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.test.ts +150 -0
  113. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +100 -0
  114. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +162 -0
  115. package/src/runtime/clawclaw/plugins/derived-event/index.ts +2 -0
  116. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.test.ts +223 -0
  117. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +236 -0
  118. package/src/runtime/clawclaw/plugins/game-query/index.ts +1 -0
  119. package/src/runtime/clawclaw/plugins/index.ts +7 -0
  120. package/src/runtime/clawclaw/plugins/mailbox/index.ts +3 -0
  121. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +77 -0
  122. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +91 -0
  123. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.test.ts +1008 -0
  124. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +475 -0
  125. package/src/runtime/clawclaw/plugins/perception/contracts.ts +32 -0
  126. package/src/runtime/clawclaw/plugins/perception/index.ts +8 -0
  127. package/src/runtime/clawclaw/plugins/perception/module-runner.test.ts +204 -0
  128. package/src/runtime/clawclaw/plugins/perception/module-runner.ts +290 -0
  129. package/src/runtime/clawclaw/plugins/perception/modules/co-movement-module.ts +324 -0
  130. package/src/runtime/clawclaw/plugins/perception/modules/follow-module.ts +365 -0
  131. package/src/runtime/clawclaw/plugins/perception/modules/index.ts +7 -0
  132. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.test.ts +341 -0
  133. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.ts +447 -0
  134. package/src/runtime/clawclaw/plugins/perception/modules/parallel-module-test-helpers.ts +30 -0
  135. package/src/runtime/clawclaw/plugins/perception/modules/relation-stability.test.ts +289 -0
  136. package/src/runtime/clawclaw/plugins/perception/modules/route-module.test.ts +180 -0
  137. package/src/runtime/clawclaw/plugins/perception/modules/route-module.ts +329 -0
  138. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.test.ts +82 -0
  139. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.ts +172 -0
  140. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.test.ts +212 -0
  141. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.ts +256 -0
  142. package/src/runtime/clawclaw/plugins/perception/modules/temporal-evidence.test.ts +121 -0
  143. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.test.ts +106 -0
  144. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.ts +225 -0
  145. package/src/runtime/clawclaw/plugins/perception/official-module-ids.ts +11 -0
  146. package/src/runtime/clawclaw/plugins/perception/official-modules.ts +31 -0
  147. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.test.ts +759 -0
  148. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +707 -0
  149. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +215 -0
  150. package/src/runtime/clawclaw/plugins/perception/perception-module-loader.ts +61 -0
  151. package/src/runtime/clawclaw/plugins/perception/perception-plugin.test.ts +1516 -0
  152. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1529 -0
  153. package/src/runtime/clawclaw/plugins/perception/perception-source.test.ts +119 -0
  154. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +244 -0
  155. package/src/runtime/clawclaw/plugins/perception/replay.test.ts +65 -0
  156. package/src/runtime/clawclaw/plugins/perception/replay.ts +86 -0
  157. package/src/runtime/clawclaw/plugins/perception/shared/math.ts +107 -0
  158. package/src/runtime/clawclaw/plugins/perception/spatial-facts.ts +114 -0
  159. package/src/runtime/clawclaw/plugins/perception/visual-state-projector.ts +98 -0
  160. package/src/runtime/clawclaw/plugins/runtime-plugins.test.ts +1019 -0
  161. package/src/runtime/clawclaw/plugins/source/game-transport.test.ts +287 -0
  162. package/src/runtime/clawclaw/plugins/source/game-transport.ts +281 -0
  163. package/src/runtime/clawclaw/plugins/source/index.ts +5 -0
  164. package/src/runtime/clawclaw/plugins/source/player-change-tracker.test.ts +270 -0
  165. package/src/runtime/clawclaw/plugins/source/player-change-tracker.ts +151 -0
  166. package/src/runtime/clawclaw/plugins/source/room-transport.test.ts +307 -0
  167. package/src/runtime/clawclaw/plugins/source/room-transport.ts +480 -0
  168. package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +1909 -0
  169. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +2055 -0
  170. package/src/runtime/clawclaw/plugins/source/source-transports.ts +30 -0
  171. package/src/runtime/clawclaw/plugins/source/types.ts +79 -0
  172. package/src/runtime/clawclaw/plugins/strategy/context-capabilities.ts +5 -0
  173. package/src/runtime/clawclaw/plugins/strategy/examples/task-only-strategy.test.ts +177 -0
  174. package/src/runtime/clawclaw/plugins/strategy/examples/task-only-strategy.ts +185 -0
  175. package/src/runtime/clawclaw/plugins/strategy/index.ts +8 -0
  176. package/src/runtime/clawclaw/plugins/strategy/local-strategy-executor.ts +412 -0
  177. package/src/runtime/clawclaw/plugins/strategy/strategy-action.ts +73 -0
  178. package/src/runtime/clawclaw/plugins/strategy/strategy-analysis-thread-host.ts +183 -0
  179. package/src/runtime/clawclaw/plugins/strategy/strategy-executor-types.ts +25 -0
  180. package/src/runtime/clawclaw/plugins/strategy/strategy-executor.test.ts +693 -0
  181. package/src/runtime/clawclaw/plugins/strategy/strategy-game-api.ts +57 -0
  182. package/src/runtime/clawclaw/plugins/strategy/strategy-module-loader.ts +164 -0
  183. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.test.ts +1936 -0
  184. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.ts +1557 -0
  185. package/src/runtime/clawclaw/plugins/strategy/strategy-source.test.ts +131 -0
  186. package/src/runtime/clawclaw/plugins/strategy/strategy-source.ts +413 -0
  187. package/src/runtime/clawclaw/plugins/strategy/thread-strategy-executor.ts +792 -0
  188. package/src/runtime/clawclaw/runtime-data-export.test.ts +249 -0
  189. package/src/runtime/clawclaw/runtime-data-export.ts +402 -0
  190. package/src/runtime/clawclaw/runtime-state.ts +98 -0
  191. package/src/runtime/clawclaw/runtime.ts +133 -0
  192. package/src/runtime/clawclaw-event-catalog.test.ts +74 -0
  193. package/src/runtime/clawclaw-event-catalog.ts +266 -0
  194. package/src/runtime/clawclaw-position.ts +4 -0
  195. package/src/runtime/clawclaw-room-state.ts +51 -0
  196. package/src/runtime/framework/action-diagnostics.test.ts +81 -0
  197. package/src/runtime/framework/action-diagnostics.ts +146 -0
  198. package/src/runtime/framework/capability-registry.test.ts +282 -0
  199. package/src/runtime/framework/capability-registry.ts +283 -0
  200. package/src/runtime/framework/contracts.ts +118 -0
  201. package/src/runtime/framework/control/control-scheduler.ts +1260 -0
  202. package/src/runtime/framework/control/domain-set.ts +81 -0
  203. package/src/runtime/framework/control/index.ts +3 -0
  204. package/src/runtime/framework/control/types.ts +184 -0
  205. package/src/runtime/framework/control-coordinator.test.ts +660 -0
  206. package/src/runtime/framework/control-coordinator.ts +11 -0
  207. package/src/runtime/framework/events/event-catalog.ts +74 -0
  208. package/src/runtime/framework/events/event-delivery-service.test.ts +84 -0
  209. package/src/runtime/framework/events/event-delivery-service.ts +198 -0
  210. package/src/runtime/framework/events/event-ingress.test.ts +178 -0
  211. package/src/runtime/framework/events/event-ingress.ts +97 -0
  212. package/src/runtime/framework/events/event-repository.ts +59 -0
  213. package/src/runtime/framework/events/index.ts +7 -0
  214. package/src/runtime/framework/events/mailbox-event-repositories.test.ts +594 -0
  215. package/src/runtime/framework/events/memory-event-repository.ts +928 -0
  216. package/src/runtime/framework/events/sqlite-event-repository.test.ts +200 -0
  217. package/src/runtime/framework/events/sqlite-event-repository.ts +1681 -0
  218. package/src/runtime/framework/events/test-helpers.ts +78 -0
  219. package/src/runtime/framework/events/types.ts +286 -0
  220. package/src/runtime/framework/index.ts +7 -0
  221. package/src/runtime/framework/load-node-sqlite.ts +17 -0
  222. package/src/runtime/framework/mailbox/coalescer.test.ts +55 -0
  223. package/src/runtime/framework/mailbox/coalescer.ts +83 -0
  224. package/src/runtime/framework/mailbox/host-notification-sink.ts +44 -0
  225. package/src/runtime/framework/mailbox/identity.test.ts +38 -0
  226. package/src/runtime/framework/mailbox/identity.ts +38 -0
  227. package/src/runtime/framework/mailbox/index.ts +7 -0
  228. package/src/runtime/framework/mailbox/mailbox-dispatcher.test.ts +513 -0
  229. package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +282 -0
  230. package/src/runtime/framework/mailbox/mailbox-repository.ts +44 -0
  231. package/src/runtime/framework/mailbox/notification-projector.test.ts +77 -0
  232. package/src/runtime/framework/mailbox/notification-projector.ts +65 -0
  233. package/src/runtime/framework/mailbox/types.ts +139 -0
  234. package/src/runtime/framework/modules/runtime-module-loader-hooks.d.mts +19 -0
  235. package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +117 -0
  236. package/src/runtime/framework/modules/runtime-module-loader.test.ts +209 -0
  237. package/src/runtime/framework/modules/runtime-module-loader.ts +71 -0
  238. package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +23 -0
  239. package/src/runtime/framework/participation-manager.test.ts +108 -0
  240. package/src/runtime/framework/participation-manager.ts +244 -0
  241. package/src/runtime/framework/plugins/contracts.ts +382 -0
  242. package/src/runtime/framework/plugins/index.ts +4 -0
  243. package/src/runtime/framework/plugins/runtime-event-identity.ts +17 -0
  244. package/src/runtime/framework/plugins/runtime-input-journal.test.ts +179 -0
  245. package/src/runtime/framework/plugins/runtime-input-journal.ts +693 -0
  246. package/src/runtime/framework/plugins/runtime-plugin-scheduler.test.ts +1994 -0
  247. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +1860 -0
  248. package/src/runtime/framework/runtime.ts +1756 -0
  249. package/src/runtime/framework/serial-task-queue.ts +14 -0
  250. package/src/runtime/framework/state/contracts.ts +49 -0
  251. package/src/runtime/framework/state/current-state-store.ts +184 -0
  252. package/src/runtime/framework/state/durable-agent-state-snapshot.test.ts +144 -0
  253. package/src/runtime/framework/state/durable-agent-state-snapshot.ts +209 -0
  254. package/src/runtime/framework/state/freshness.ts +72 -0
  255. package/src/runtime/framework/state/history/contracts.ts +150 -0
  256. package/src/runtime/framework/state/history/history-writer.ts +194 -0
  257. package/src/runtime/framework/state/history/memory-state-history-repository.ts +178 -0
  258. package/src/runtime/framework/state/history/sqlite-state-history-repository.test.ts +157 -0
  259. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +629 -0
  260. package/src/runtime/framework/state/history/state-history.test.ts +251 -0
  261. package/src/runtime/framework/state/history/trajectory-projector.ts +209 -0
  262. package/src/runtime/framework/state/index.ts +13 -0
  263. package/src/runtime/framework/state/state-core.test.ts +197 -0
  264. package/src/runtime/framework/state/state-ingress.ts +95 -0
  265. package/src/runtime/framework/state/state-provider.ts +62 -0
  266. package/src/runtime/framework/state/types.ts +155 -0
  267. package/src/runtime/game-sync-protocol.test.ts +123 -0
  268. package/src/runtime/game-sync-protocol.ts +261 -0
  269. package/src/runtime/mailbox-host-relay.test.ts +248 -0
  270. package/src/runtime/mailbox-host-relay.ts +300 -0
  271. package/src/runtime/observability/factory.ts +188 -0
  272. package/src/runtime/observability/index.ts +6 -0
  273. package/src/runtime/observability/observability.test.ts +561 -0
  274. package/src/runtime/observability/recorder.ts +209 -0
  275. package/src/runtime/observability/redaction.ts +154 -0
  276. package/src/runtime/observability/reporter.ts +154 -0
  277. package/src/runtime/observability/sinks.ts +135 -0
  278. package/src/runtime/observability/types.ts +92 -0
  279. package/src/runtime/owner-control.test.ts +153 -0
  280. package/src/runtime/owner-control.ts +206 -42
  281. package/src/runtime/parent-process-watch.test.ts +27 -0
  282. package/src/runtime/parent-process-watch.ts +51 -0
  283. package/src/runtime/pending-event-handoff.test.ts +29 -0
  284. package/src/runtime/pending-event-handoff.ts +61 -0
  285. package/src/runtime/raw-ws-log.test.ts +86 -17
  286. package/src/runtime/raw-ws-log.ts +230 -21
  287. package/src/runtime/runtime-logger.test.ts +58 -0
  288. package/src/runtime/runtime-logger.ts +10 -13
  289. package/src/runtime/runtime-persistence.test.ts +26 -0
  290. package/src/runtime/runtime.test.ts +1704 -0
  291. package/src/runtime/ws-client.test.ts +496 -103
  292. package/src/runtime/ws-client.ts +546 -166
  293. package/src/sdk/action.ts +3 -1
  294. package/src/sdk/index.ts +4 -19
  295. package/src/sdk/perception-plugin/index.test.ts +22 -0
  296. package/src/sdk/perception-plugin/index.ts +285 -0
  297. package/src/sdk/strategy-plugin/index.test.ts +952 -0
  298. package/src/sdk/strategy-plugin/index.ts +1324 -0
  299. package/src/sdk/types.ts +3 -1
  300. package/src/short-command/classifier.test.ts +107 -0
  301. package/src/short-command/classifier.ts +169 -0
  302. package/src/short-command/index.ts +7 -0
  303. package/src/short-command/presenter.test.ts +119 -0
  304. package/src/short-command/presenter.ts +308 -0
  305. package/src/short-command/process-io.ts +13 -0
  306. package/src/short-command/response-contract.ts +58 -0
  307. package/src/short-command/runner.test.ts +78 -0
  308. package/src/short-command/runner.ts +164 -0
  309. package/src/short-command/sensitive-data-filter.test.ts +56 -0
  310. package/src/short-command/sensitive-data-filter.ts +123 -0
  311. package/src/short-command/transport-response.test.ts +39 -0
  312. package/src/short-command/transport-response.ts +89 -0
  313. package/src/short-command/types.ts +92 -0
  314. package/src/strategies/avoid-lone.ts +18 -11
  315. package/src/strategies/avoid-players.ts +29 -13
  316. package/src/strategies/corpse-patrol.ts +29 -11
  317. package/src/strategies/crab-sabotage.ts +31 -18
  318. package/src/strategies/custom-module.test.ts +3 -5
  319. package/src/strategies/find-player.ts +34 -15
  320. package/src/strategies/game-utils.test.ts +42 -0
  321. package/src/strategies/game-utils.ts +143 -53
  322. package/src/strategies/goals/avoid-lone-top.ts +22 -1
  323. package/src/strategies/goals/avoid-players-top.test.ts +13 -0
  324. package/src/strategies/goals/avoid-players-top.ts +6 -5
  325. package/src/strategies/goals/corpse-patrol-top.ts +9 -2
  326. package/src/strategies/goals/crab-octopus-reflexes.ts +6 -2
  327. package/src/strategies/goals/crab-sabotage-top.ts +7 -1
  328. package/src/strategies/goals/emergency-hunt-goal.ts +15 -3
  329. package/src/strategies/goals/find-player-top.ts +47 -3
  330. package/src/strategies/goals/flee-players-goal.ts +2 -0
  331. package/src/strategies/goals/follow-companion-goal.ts +27 -3
  332. package/src/strategies/goals/hide-top.ts +47 -5
  333. package/src/strategies/goals/keep-away-goal.ts +24 -2
  334. package/src/strategies/goals/kill-frenzy-top.ts +12 -2
  335. package/src/strategies/goals/kill-lone-top.test.ts +72 -0
  336. package/src/strategies/goals/kill-lone-top.ts +8 -6
  337. package/src/strategies/goals/kill-target-goal.ts +16 -7
  338. package/src/strategies/goals/kill-target-top.ts +16 -2
  339. package/src/strategies/goals/linger-corpse-goal.ts +11 -3
  340. package/src/strategies/goals/lone-kill-core.ts +4 -2
  341. package/src/strategies/goals/move-room-goal.ts +46 -4
  342. package/src/strategies/goals/normal-shrimp-top.test.ts +16 -0
  343. package/src/strategies/goals/normal-shrimp-top.ts +18 -18
  344. package/src/strategies/goals/paradise-fish-top.test.ts +78 -0
  345. package/src/strategies/goals/paradise-fish-top.ts +16 -6
  346. package/src/strategies/goals/patrol-top.ts +14 -3
  347. package/src/strategies/goals/report-patrol-top.ts +14 -3
  348. package/src/strategies/goals/safe-task-goal.ts +32 -4
  349. package/src/strategies/goals/social-task-top.ts +39 -8
  350. package/src/strategies/goals/task-kill-report-top.ts +33 -10
  351. package/src/strategies/goals/task-only-top.test.ts +89 -0
  352. package/src/strategies/goals/task-only-top.ts +9 -2
  353. package/src/strategies/goals/task-or-patrol-goal.ts +21 -3
  354. package/src/strategies/goals/warrior-shrimp-top.test.ts +75 -23
  355. package/src/strategies/goals/warrior-shrimp-top.ts +34 -13
  356. package/src/strategies/greeting.ts +10 -3
  357. package/src/strategies/hide-spots.ts +4 -0
  358. package/src/strategies/hide.ts +35 -20
  359. package/src/strategies/kill-frenzy.ts +18 -12
  360. package/src/strategies/kill-lone.ts +43 -12
  361. package/src/strategies/kill-target.ts +34 -17
  362. package/src/strategies/lone-kill-task.ts +31 -18
  363. package/src/strategies/move-room.ts +32 -15
  364. package/src/strategies/off-route-points.ts +12 -4
  365. package/src/strategies/paradise-fish.ts +49 -14
  366. package/src/strategies/pathfind/astar-path.test.ts +73 -0
  367. package/src/strategies/pathfind/astar-path.ts +196 -0
  368. package/src/strategies/pathfind/escape-planner.test.ts +27 -1
  369. package/src/strategies/pathfind/escape-planner.ts +108 -0
  370. package/src/strategies/patrol.ts +18 -11
  371. package/src/strategies/report-patrol.ts +18 -11
  372. package/src/strategies/shrimp-memory.ts +66 -14
  373. package/src/strategies/social-task.ts +49 -45
  374. package/src/strategies/task-kill-report.ts +34 -16
  375. package/src/strategies/task-only.test.ts +124 -0
  376. package/src/strategies/task-only.ts +20 -11
  377. package/src/strategies/task-report.ts +29 -11
  378. package/src/strategies/types.ts +29 -62
  379. package/src/strategies/warrior-memory.ts +44 -14
  380. package/scripts/check_monitor.test.mjs +0 -212
  381. package/skills/clawclaw/references/KNOWLEDGE.md +0 -42
  382. package/src/commands/do.test.ts +0 -117
  383. package/src/commands/do.ts +0 -195
  384. package/src/commands/game-monitor-status.test.ts +0 -58
  385. package/src/commands/game-start-plan.test.ts +0 -356
  386. package/src/commands/game.ts +0 -2046
  387. package/src/commands/history-player.test.ts +0 -105
  388. package/src/commands/history.ts +0 -573
  389. package/src/commands/knowledge.test.ts +0 -13
  390. package/src/commands/knowledge.ts +0 -176
  391. package/src/commands/meeting-history.test.ts +0 -106
  392. package/src/commands/state.ts +0 -46
  393. package/src/commands/watch.test.ts +0 -1313
  394. package/src/commands/watch.ts +0 -824
  395. package/src/lib/knowledge-store.test.ts +0 -170
  396. package/src/lib/knowledge-store.ts +0 -369
  397. package/src/perception/player-history-store.test.ts +0 -177
  398. package/src/perception/player-history-store.ts +0 -262
  399. package/src/pipeline/event-store.test.ts +0 -28
  400. package/src/pipeline/event-store.ts +0 -193
  401. package/src/pipeline/pipeline.ts +0 -35
  402. package/src/runtime/event-daemon.test.ts +0 -268
  403. package/src/runtime/event-daemon.ts +0 -531
  404. package/src/runtime/room-lobby-runtime.test.ts +0 -95
  405. package/src/runtime/room-lobby-runtime.ts +0 -367
  406. package/src/strategies/avoid-players.knowledge.md +0 -19
  407. package/src/strategies/kill-lone.knowledge.md +0 -17
  408. package/src/strategies/knowledge-contract.ts +0 -85
  409. package/src/strategies/loader.test.ts +0 -678
  410. package/src/strategies/loader.ts +0 -212
  411. package/src/strategies/new-events-backfill.ts +0 -98
  412. package/src/strategies/paradise-fish.knowledge.md +0 -19
  413. package/src/strategies/shrimp-memory.knowledge.md +0 -19
  414. package/src/strategies/social-task.test.ts +0 -28
  415. package/src/strategies/spawn.ts +0 -82
  416. package/src/strategies/strategy-loop.test.ts +0 -15
  417. package/src/strategies/strategy-loop.ts +0 -748
  418. package/src/strategies/warrior-memory.knowledge.md +0 -21
@@ -0,0 +1,693 @@
1
+ import { createHash } from 'crypto';
2
+ import { createRequire } from 'module';
3
+ import { mkdirSync } from 'fs';
4
+ import { dirname } from 'path';
5
+ import { loadNodeSqliteModule } from '../load-node-sqlite.js';
6
+ import { cloneCanonical, runtimeScopeKey, sameRuntimeScope, type RuntimeScope } from '../state/types.js';
7
+ import type {
8
+ RuntimeEpoch,
9
+ RuntimePersistenceStore,
10
+ RuntimeEpochPluginProgress,
11
+ RuntimeEpochPluginRecord,
12
+ RuntimeEpochStateRecord,
13
+ RuntimeInputAcceptance,
14
+ RuntimeInputBatch,
15
+ } from './contracts.js';
16
+
17
+ interface StatementLike {
18
+ run(...params: unknown[]): { changes: number | bigint; lastInsertRowid?: number | bigint };
19
+ get(...params: unknown[]): Record<string, unknown> | undefined;
20
+ all(...params: unknown[]): Array<Record<string, unknown>>;
21
+ }
22
+
23
+ interface DatabaseLike {
24
+ exec(sql: string): void;
25
+ prepare(sql: string): StatementLike;
26
+ close(): void;
27
+ }
28
+
29
+ interface SqliteModuleLike {
30
+ DatabaseSync: new (path: string) => DatabaseLike;
31
+ }
32
+
33
+ const localRequire = createRequire(import.meta.url);
34
+
35
+ function canonicalPayload(batch: RuntimeInputBatch<any, any>): Record<string, unknown> {
36
+ return {
37
+ scope: batch.scope,
38
+ sourceId: batch.sourceId,
39
+ connectionId: batch.connectionId,
40
+ sourceKey: batch.sourceKey,
41
+ sourceSeq: batch.sourceSeq,
42
+ domainTick: batch.domainTick,
43
+ state: batch.state,
44
+ events: batch.events,
45
+ eventWatermark: batch.eventWatermark,
46
+ completeness: batch.completeness,
47
+ coalescing: batch.coalescing,
48
+ observedAt: batch.observedAt,
49
+ };
50
+ }
51
+
52
+ function payloadHash(batch: RuntimeInputBatch<any, any>): string {
53
+ return createHash('sha256').update(JSON.stringify(canonicalPayload(batch))).digest('hex');
54
+ }
55
+
56
+ function assertOptionalSequence(value: unknown, field: string): void {
57
+ if (value === undefined) return;
58
+ if (typeof value === 'number' && Number.isFinite(value)) return;
59
+ if (typeof value === 'string' && value.length > 0) return;
60
+ throw new TypeError(`Runtime InputBatch ${field} must be a finite number or non-empty string.`);
61
+ }
62
+
63
+ function assertOptionalTimestamp(value: unknown, field: string): void {
64
+ if (value === undefined) return;
65
+ if (typeof value !== 'string' || !Number.isFinite(Date.parse(value))) {
66
+ throw new TypeError(`Runtime InputBatch ${field} must be an ISO timestamp.`);
67
+ }
68
+ }
69
+
70
+ export function assertRuntimeInputBatch(batch: RuntimeInputBatch<any, any>): void {
71
+ if (!batch || typeof batch !== 'object') throw new TypeError('Runtime InputBatch is required.');
72
+ if (!batch.scope || typeof batch.scope !== 'object') {
73
+ throw new TypeError('Runtime InputBatch scope is required.');
74
+ }
75
+ for (const key of ['adapterId', 'accountId', 'sessionId', 'segmentId'] as const) {
76
+ if (typeof batch.scope[key] !== 'string' || !batch.scope[key].trim()) {
77
+ throw new TypeError(`Runtime InputBatch scope.${key} is required.`);
78
+ }
79
+ }
80
+ if (
81
+ batch.scope.segmentSeq !== undefined
82
+ && (!Number.isInteger(batch.scope.segmentSeq) || batch.scope.segmentSeq <= 0)
83
+ ) {
84
+ throw new TypeError('Runtime InputBatch scope.segmentSeq must be a positive integer.');
85
+ }
86
+ if (typeof batch.sourceId !== 'string' || !batch.sourceId.trim()) {
87
+ throw new TypeError('Runtime InputBatch sourceId is required.');
88
+ }
89
+ if (typeof batch.connectionId !== 'string' || !batch.connectionId.trim()) {
90
+ throw new TypeError('Runtime InputBatch connectionId is required.');
91
+ }
92
+ if (typeof batch.sourceKey !== 'string' || !batch.sourceKey.trim()) {
93
+ throw new TypeError('Runtime InputBatch sourceKey is required.');
94
+ }
95
+ assertOptionalSequence(batch.sourceSeq, 'sourceSeq');
96
+ assertOptionalSequence(batch.domainTick, 'domainTick');
97
+ assertOptionalSequence(batch.eventWatermark, 'eventWatermark');
98
+ if (!batch.state || typeof batch.state !== 'object' || Array.isArray(batch.state)) {
99
+ throw new TypeError('Runtime InputBatch requires one complete State object.');
100
+ }
101
+ if (!Array.isArray(batch.events)) throw new TypeError('Runtime InputBatch events must be an explicit array.');
102
+ for (const [index, event] of batch.events.entries()) {
103
+ if (!event || typeof event !== 'object' || Array.isArray(event)) {
104
+ throw new TypeError(`Runtime InputBatch Event ${index} must be an object.`);
105
+ }
106
+ if (typeof event.type !== 'string' || !event.type.trim()) {
107
+ throw new TypeError(`Runtime InputBatch Event ${index} requires type.`);
108
+ }
109
+ if (!event.payload || typeof event.payload !== 'object' || Array.isArray(event.payload)) {
110
+ throw new TypeError(`Runtime InputBatch Event ${index} requires an object payload.`);
111
+ }
112
+ if (
113
+ event.producer !== undefined
114
+ && event.producer !== 'backend_push'
115
+ && event.producer !== 'local_synth'
116
+ ) {
117
+ throw new TypeError(`Runtime InputBatch Event ${index} producer is invalid.`);
118
+ }
119
+ if (
120
+ event.sourceEventId !== undefined
121
+ && (typeof event.sourceEventId !== 'string' || !event.sourceEventId.trim())
122
+ ) {
123
+ throw new TypeError(`Runtime InputBatch Event ${index} sourceEventId must be a non-empty string.`);
124
+ }
125
+ assertOptionalSequence(event.sourceSeq, `Event ${index} sourceSeq`);
126
+ assertOptionalTimestamp(event.observedAt, `Event ${index} observedAt`);
127
+ assertOptionalTimestamp(event.receivedAt, `Event ${index} receivedAt`);
128
+ if (event.replayed !== undefined && typeof event.replayed !== 'boolean') {
129
+ throw new TypeError(`Runtime InputBatch Event ${index} replayed must be a boolean.`);
130
+ }
131
+ if (event.checkpoint !== undefined && typeof event.checkpoint !== 'string') {
132
+ throw new TypeError(`Runtime InputBatch Event ${index} checkpoint must be a string.`);
133
+ }
134
+ }
135
+ if (batch.completeness !== 'complete' && batch.completeness !== 'best_effort') {
136
+ throw new TypeError('Runtime InputBatch completeness is invalid.');
137
+ }
138
+ if (
139
+ batch.coalescing !== undefined
140
+ && batch.coalescing !== 'allowed'
141
+ && batch.coalescing !== 'forbidden'
142
+ ) {
143
+ throw new TypeError('Runtime InputBatch coalescing is invalid.');
144
+ }
145
+ assertOptionalTimestamp(batch.observedAt, 'observedAt');
146
+ if (typeof batch.receivedAt !== 'string' || !Number.isFinite(Date.parse(batch.receivedAt))) {
147
+ throw new TypeError('Runtime InputBatch receivedAt must be an ISO timestamp.');
148
+ }
149
+ }
150
+
151
+ function sourceIdentity(batch: RuntimeInputBatch<any, any>): string {
152
+ return [runtimeScopeKey(batch.scope), batch.sourceId, batch.sourceKey].join('\u001f');
153
+ }
154
+
155
+ export class RuntimeInputConflictError extends Error {
156
+ constructor(readonly sourceId: string, readonly sourceKey: string) {
157
+ super(`Runtime input ${sourceId}/${sourceKey} was retried with different content.`);
158
+ this.name = 'RuntimeInputConflictError';
159
+ }
160
+ }
161
+
162
+ export class MemoryRuntimeInputJournal<TState = Record<string, unknown>, TEvent = Record<string, unknown>>
163
+ implements RuntimePersistenceStore<TState, TEvent> {
164
+ private readonly epochs: RuntimeEpoch<TState, TEvent>[] = [];
165
+ private readonly hashes = new Map<string, string>();
166
+ private readonly byIdentity = new Map<string, RuntimeEpoch<TState, TEvent>>();
167
+ private readonly closed = new Set<number>();
168
+ private readonly inputEventCommits = new Set<number>();
169
+ private readonly eventWatermarks = new Map<number, number>();
170
+ private readonly progress = new Map<string, RuntimeEpochPluginProgress>();
171
+ private readonly pluginOutcomeRecords: RuntimeEpochPluginRecord[] = [];
172
+ private readonly stateRecords: RuntimeEpochStateRecord[] = [];
173
+ private nextEpochSeq = 1;
174
+
175
+ accept(batch: RuntimeInputBatch<TState, TEvent>): RuntimeInputAcceptance<TState, TEvent> {
176
+ assertRuntimeInputBatch(batch);
177
+ const identity = sourceIdentity(batch);
178
+ const hash = payloadHash(batch as RuntimeInputBatch);
179
+ const existing = this.byIdentity.get(identity);
180
+ if (existing) {
181
+ if (this.hashes.get(identity) !== hash) throw new RuntimeInputConflictError(batch.sourceId, batch.sourceKey);
182
+ return { inserted: false, epoch: cloneCanonical(existing) };
183
+ }
184
+ const epoch: RuntimeEpoch<TState, TEvent> = {
185
+ ...cloneCanonical(batch),
186
+ epochSeq: this.nextEpochSeq++,
187
+ };
188
+ this.epochs.push(epoch);
189
+ this.byIdentity.set(identity, epoch);
190
+ this.hashes.set(identity, hash);
191
+ return { inserted: true, epoch: cloneCanonical(epoch) };
192
+ }
193
+
194
+ epoch(epochSeq: number): RuntimeEpoch<TState, TEvent> | null {
195
+ const value = this.epochs.find((item) => item.epochSeq === epochSeq);
196
+ return value ? cloneCanonical(value) : null;
197
+ }
198
+
199
+ list(scope: RuntimeScope, afterEpochSeq = 0, limit = 100): RuntimeEpoch<TState, TEvent>[] {
200
+ return this.epochs
201
+ .filter((item) => item.epochSeq > afterEpochSeq && sameRuntimeScope(item.scope, scope))
202
+ .slice(0, Math.max(1, Math.min(limit, 10_000)))
203
+ .map(cloneCanonical);
204
+ }
205
+
206
+ listOpen(scope: RuntimeScope, afterEpochSeq = 0, limit = 100): RuntimeEpoch<TState, TEvent>[] {
207
+ return this.epochs
208
+ .filter((item) => (
209
+ item.epochSeq > afterEpochSeq
210
+ && sameRuntimeScope(item.scope, scope)
211
+ && !this.closed.has(item.epochSeq)
212
+ ))
213
+ .slice(0, Math.max(1, Math.min(limit, 10_000)))
214
+ .map(cloneCanonical);
215
+ }
216
+
217
+ markClosed(epochSeq: number, _closedAt?: string, _durationMs?: number): void {
218
+ this.closed.add(epochSeq);
219
+ }
220
+
221
+ eventWatermarkThrough(scope: RuntimeScope, epochSeq: number): number {
222
+ return this.epochs.reduce((watermark, epoch) => (
223
+ epoch.epochSeq <= epochSeq && sameRuntimeScope(epoch.scope, scope)
224
+ ? Math.max(watermark, this.eventWatermarks.get(epoch.epochSeq) ?? 0)
225
+ : watermark
226
+ ), 0);
227
+ }
228
+
229
+ inputEventsCommitted(epochSeq: number): boolean {
230
+ return this.inputEventCommits.has(epochSeq);
231
+ }
232
+
233
+ markInputEventsCommitted(epochSeq: number, eventWatermark: number): void {
234
+ this.inputEventCommits.add(epochSeq);
235
+ this.eventWatermarks.set(epochSeq, Math.max(this.eventWatermarks.get(epochSeq) ?? 0, eventWatermark));
236
+ }
237
+
238
+ markEventWatermark(epochSeq: number, eventWatermark: number): void {
239
+ this.eventWatermarks.set(epochSeq, Math.max(this.eventWatermarks.get(epochSeq) ?? 0, eventWatermark));
240
+ }
241
+
242
+ recordPlugin(record: RuntimeEpochPluginRecord): void {
243
+ const index = this.pluginOutcomeRecords.findIndex((candidate) => (
244
+ candidate.epochSeq === record.epochSeq && candidate.pluginId === record.pluginId
245
+ ));
246
+ if (index >= 0) this.pluginOutcomeRecords[index] = cloneCanonical(record);
247
+ else this.pluginOutcomeRecords.push(cloneCanonical(record));
248
+ }
249
+
250
+ pluginRecords(epochSeq: number): RuntimeEpochPluginRecord[] {
251
+ return this.pluginOutcomeRecords
252
+ .filter((record) => record.epochSeq === epochSeq)
253
+ .sort((a, b) => a.pluginId.localeCompare(b.pluginId))
254
+ .map(cloneCanonical);
255
+ }
256
+
257
+ pluginProgress(pluginId: string, scope: RuntimeScope): RuntimeEpochPluginProgress {
258
+ return cloneCanonical(this.progress.get(`${runtimeScopeKey(scope)}\u001f${pluginId}`) ?? {
259
+ pluginId,
260
+ completedThroughEpochSeq: 0,
261
+ eventCursor: 0,
262
+ updatedAt: new Date(0).toISOString(),
263
+ });
264
+ }
265
+
266
+ savePluginProgress(progress: RuntimeEpochPluginProgress, scope: RuntimeScope): void {
267
+ this.progress.set(`${runtimeScopeKey(scope)}\u001f${progress.pluginId}`, cloneCanonical(progress));
268
+ }
269
+
270
+ saveStates(records: readonly RuntimeEpochStateRecord[]): void {
271
+ this.stateRecords.push(...records.map(cloneCanonical));
272
+ }
273
+
274
+ states(epochSeq: number): RuntimeEpochStateRecord[] {
275
+ return this.stateRecords.filter((row) => row.epochSeq === epochSeq).map(cloneCanonical);
276
+ }
277
+
278
+ }
279
+
280
+ function parseJson<T>(value: unknown): T {
281
+ if (typeof value !== 'string') throw new Error('Runtime Input Journal contains invalid JSON.');
282
+ return JSON.parse(value) as T;
283
+ }
284
+
285
+ function numberValue(value: unknown): number {
286
+ return typeof value === 'bigint' ? Number(value) : Number(value ?? 0);
287
+ }
288
+
289
+ export class SqliteRuntimeInputJournal<TState = Record<string, unknown>, TEvent = Record<string, unknown>>
290
+ implements RuntimePersistenceStore<TState, TEvent> {
291
+ private readonly db: DatabaseLike;
292
+
293
+ constructor(path: string) {
294
+ const sqlite = loadNodeSqliteModule<Partial<SqliteModuleLike>>(localRequire);
295
+ if (typeof sqlite.DatabaseSync !== 'function') throw new Error('node:sqlite is unavailable in this Node.js runtime');
296
+ if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true });
297
+ this.db = new sqlite.DatabaseSync(path);
298
+ this.initialize();
299
+ }
300
+
301
+ accept(batch: RuntimeInputBatch<TState, TEvent>): RuntimeInputAcceptance<TState, TEvent> {
302
+ assertRuntimeInputBatch(batch);
303
+ const hash = payloadHash(batch as RuntimeInputBatch);
304
+ const existing = this.findByIdentity(batch.scope, batch.sourceId, batch.sourceKey);
305
+ if (existing) {
306
+ if (String(existing.payload_hash) !== hash) throw new RuntimeInputConflictError(batch.sourceId, batch.sourceKey);
307
+ return { inserted: false, epoch: this.fromRow(existing) };
308
+ }
309
+ const result = this.db.prepare(`
310
+ INSERT INTO runtime_epochs(
311
+ adapter_id, account_id, session_id, segment_id, segment_seq,
312
+ source_id, connection_id, source_key, source_seq_json, domain_tick_json,
313
+ state_json, events_json, event_watermark_json, completeness, coalescing,
314
+ observed_at, received_at, payload_hash, status
315
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'accepted')
316
+ `).run(
317
+ batch.scope.adapterId,
318
+ batch.scope.accountId,
319
+ batch.scope.sessionId,
320
+ batch.scope.segmentId,
321
+ batch.scope.segmentSeq ?? null,
322
+ batch.sourceId,
323
+ batch.connectionId,
324
+ batch.sourceKey,
325
+ batch.sourceSeq === undefined ? null : JSON.stringify(batch.sourceSeq),
326
+ batch.domainTick === undefined ? null : JSON.stringify(batch.domainTick),
327
+ JSON.stringify(batch.state),
328
+ JSON.stringify(batch.events),
329
+ batch.eventWatermark === undefined ? null : JSON.stringify(batch.eventWatermark),
330
+ batch.completeness,
331
+ batch.coalescing ?? 'allowed',
332
+ batch.observedAt ?? null,
333
+ batch.receivedAt,
334
+ hash,
335
+ );
336
+ const row = this.db.prepare('SELECT * FROM runtime_epochs WHERE epoch_seq = ?')
337
+ .get(numberValue(result.lastInsertRowid));
338
+ if (!row) throw new Error('Runtime epoch was inserted but could not be read.');
339
+ return { inserted: true, epoch: this.fromRow(row) };
340
+ }
341
+
342
+ epoch(epochSeq: number): RuntimeEpoch<TState, TEvent> | null {
343
+ const row = this.db.prepare('SELECT * FROM runtime_epochs WHERE epoch_seq = ?').get(epochSeq);
344
+ return row ? this.fromRow(row) : null;
345
+ }
346
+
347
+ list(scope: RuntimeScope, afterEpochSeq = 0, limit = 100): RuntimeEpoch<TState, TEvent>[] {
348
+ return this.db.prepare(`
349
+ SELECT * FROM runtime_epochs
350
+ WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?
351
+ AND epoch_seq > ?
352
+ ORDER BY epoch_seq ASC LIMIT ?
353
+ `).all(
354
+ scope.adapterId,
355
+ scope.accountId,
356
+ scope.sessionId,
357
+ scope.segmentId,
358
+ afterEpochSeq,
359
+ Math.max(1, Math.min(limit, 10_000)),
360
+ ).map((row) => this.fromRow(row));
361
+ }
362
+
363
+ listOpen(scope: RuntimeScope, afterEpochSeq = 0, limit = 100): RuntimeEpoch<TState, TEvent>[] {
364
+ return this.db.prepare(`
365
+ SELECT * FROM runtime_epochs
366
+ WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?
367
+ AND epoch_seq > ? AND status = 'accepted'
368
+ ORDER BY epoch_seq ASC LIMIT ?
369
+ `).all(
370
+ scope.adapterId,
371
+ scope.accountId,
372
+ scope.sessionId,
373
+ scope.segmentId,
374
+ afterEpochSeq,
375
+ Math.max(1, Math.min(limit, 10_000)),
376
+ ).map((row) => this.fromRow(row));
377
+ }
378
+
379
+ markClosed(
380
+ epochSeq: number,
381
+ closedAt = new Date().toISOString(),
382
+ durationMs?: number,
383
+ ): void {
384
+ this.db.prepare(`
385
+ UPDATE runtime_epochs
386
+ SET status = 'closed', closed_at = ?, processing_duration_ms = ?
387
+ WHERE epoch_seq = ?
388
+ `).run(closedAt, durationMs ?? null, epochSeq);
389
+ }
390
+
391
+ inputEventsCommitted(epochSeq: number): boolean {
392
+ const row = this.db.prepare('SELECT input_events_committed_at FROM runtime_epochs WHERE epoch_seq = ?')
393
+ .get(epochSeq);
394
+ return typeof row?.input_events_committed_at === 'string';
395
+ }
396
+
397
+ markInputEventsCommitted(
398
+ epochSeq: number,
399
+ eventWatermark: number,
400
+ committedAt = new Date().toISOString(),
401
+ ): void {
402
+ this.db.prepare(`
403
+ UPDATE runtime_epochs
404
+ SET input_events_committed_at = ?,
405
+ event_commit_watermark = MAX(COALESCE(event_commit_watermark, 0), ?)
406
+ WHERE epoch_seq = ?
407
+ `).run(committedAt, eventWatermark, epochSeq);
408
+ }
409
+
410
+ eventWatermarkThrough(scope: RuntimeScope, epochSeq: number): number {
411
+ const row = this.db.prepare(`
412
+ SELECT event_commit_watermark AS watermark
413
+ FROM runtime_epochs
414
+ WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?
415
+ AND epoch_seq <= ? AND event_commit_watermark IS NOT NULL
416
+ ORDER BY event_commit_watermark DESC
417
+ LIMIT 1
418
+ `).get(
419
+ scope.adapterId,
420
+ scope.accountId,
421
+ scope.sessionId,
422
+ scope.segmentId,
423
+ epochSeq,
424
+ );
425
+ return numberValue(row?.watermark);
426
+ }
427
+
428
+ markEventWatermark(epochSeq: number, eventWatermark: number): void {
429
+ this.db.prepare(`
430
+ UPDATE runtime_epochs
431
+ SET event_commit_watermark = MAX(COALESCE(event_commit_watermark, 0), ?)
432
+ WHERE epoch_seq = ?
433
+ `).run(eventWatermark, epochSeq);
434
+ }
435
+
436
+ recordPlugin(record: RuntimeEpochPluginRecord): void {
437
+ this.db.prepare(`
438
+ INSERT OR REPLACE INTO runtime_plugin_outcomes(
439
+ epoch_seq, plugin_id, invocation_id, outcome, reason, duration_ms,
440
+ state_count, event_count, event_cursor_before, event_cursor_after, recorded_at
441
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
442
+ `).run(
443
+ record.epochSeq,
444
+ record.pluginId,
445
+ record.invocationId,
446
+ record.outcome,
447
+ record.reason ?? null,
448
+ record.durationMs,
449
+ record.stateCount,
450
+ record.eventCount,
451
+ record.eventCursorBefore,
452
+ record.eventCursorAfter,
453
+ record.recordedAt,
454
+ );
455
+ }
456
+
457
+ pluginRecords(epochSeq: number): RuntimeEpochPluginRecord[] {
458
+ return this.db.prepare(`
459
+ SELECT * FROM runtime_plugin_outcomes
460
+ WHERE epoch_seq = ?
461
+ ORDER BY plugin_id
462
+ `).all(epochSeq).map((row) => ({
463
+ epochSeq: numberValue(row.epoch_seq),
464
+ pluginId: String(row.plugin_id),
465
+ invocationId: String(row.invocation_id),
466
+ outcome: row.outcome as RuntimeEpochPluginRecord['outcome'],
467
+ ...(typeof row.reason === 'string' ? { reason: row.reason } : {}),
468
+ durationMs: numberValue(row.duration_ms),
469
+ stateCount: numberValue(row.state_count),
470
+ eventCount: numberValue(row.event_count),
471
+ eventCursorBefore: numberValue(row.event_cursor_before),
472
+ eventCursorAfter: numberValue(row.event_cursor_after),
473
+ recordedAt: String(row.recorded_at),
474
+ }));
475
+ }
476
+
477
+ pluginProgress(pluginId: string, scope: RuntimeScope): RuntimeEpochPluginProgress {
478
+ const row = this.db.prepare(`
479
+ SELECT * FROM runtime_plugin_progress
480
+ WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ? AND plugin_id = ?
481
+ `).get(scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId, pluginId);
482
+ return row ? {
483
+ pluginId,
484
+ completedThroughEpochSeq: numberValue(row.completed_through_epoch_seq),
485
+ eventCursor: numberValue(row.event_cursor),
486
+ ...(typeof row.checkpoint_json === 'string'
487
+ ? { checkpoint: parseJson(row.checkpoint_json) }
488
+ : {}),
489
+ updatedAt: String(row.updated_at),
490
+ } : {
491
+ pluginId,
492
+ completedThroughEpochSeq: 0,
493
+ eventCursor: 0,
494
+ updatedAt: new Date(0).toISOString(),
495
+ };
496
+ }
497
+
498
+ savePluginProgress(progress: RuntimeEpochPluginProgress, scope: RuntimeScope): void {
499
+ this.db.prepare(`
500
+ INSERT INTO runtime_plugin_progress(
501
+ adapter_id, account_id, session_id, segment_id, plugin_id,
502
+ completed_through_epoch_seq, event_cursor, checkpoint_json, updated_at
503
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
504
+ ON CONFLICT(adapter_id, account_id, session_id, segment_id, plugin_id)
505
+ DO UPDATE SET
506
+ completed_through_epoch_seq = excluded.completed_through_epoch_seq,
507
+ event_cursor = excluded.event_cursor,
508
+ checkpoint_json = excluded.checkpoint_json,
509
+ updated_at = excluded.updated_at
510
+ `).run(
511
+ scope.adapterId,
512
+ scope.accountId,
513
+ scope.sessionId,
514
+ scope.segmentId,
515
+ progress.pluginId,
516
+ progress.completedThroughEpochSeq,
517
+ progress.eventCursor,
518
+ progress.checkpoint === undefined ? null : JSON.stringify(progress.checkpoint),
519
+ progress.updatedAt,
520
+ );
521
+ }
522
+
523
+ saveStates(records: readonly RuntimeEpochStateRecord[]): void {
524
+ const statement = this.db.prepare(`
525
+ INSERT OR REPLACE INTO runtime_plugin_states(epoch_seq, plugin_id, topic, value_json)
526
+ VALUES (?, ?, ?, ?)
527
+ `);
528
+ this.db.exec('BEGIN IMMEDIATE');
529
+ try {
530
+ for (const record of records) {
531
+ statement.run(record.epochSeq, record.pluginId, record.topic, JSON.stringify(record.value));
532
+ }
533
+ this.db.exec('COMMIT');
534
+ } catch (error) {
535
+ this.db.exec('ROLLBACK');
536
+ throw error;
537
+ }
538
+ }
539
+
540
+ states(epochSeq: number): RuntimeEpochStateRecord[] {
541
+ return this.db.prepare(`
542
+ SELECT epoch_seq, plugin_id, topic, value_json
543
+ FROM runtime_plugin_states WHERE epoch_seq = ? ORDER BY plugin_id, topic
544
+ `).all(epochSeq).map((row) => ({
545
+ epochSeq: numberValue(row.epoch_seq),
546
+ pluginId: String(row.plugin_id),
547
+ topic: String(row.topic),
548
+ value: parseJson(row.value_json),
549
+ }));
550
+ }
551
+
552
+ close(): void {
553
+ this.db.close();
554
+ }
555
+
556
+ private findByIdentity(scope: RuntimeScope, sourceId: string, sourceKey: string) {
557
+ return this.db.prepare(`
558
+ SELECT * FROM runtime_epochs
559
+ WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?
560
+ AND source_id = ? AND source_key = ?
561
+ `).get(scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId, sourceId, sourceKey);
562
+ }
563
+
564
+ private fromRow(row: Record<string, unknown>): RuntimeEpoch<TState, TEvent> {
565
+ return cloneCanonical({
566
+ epochSeq: numberValue(row.epoch_seq),
567
+ scope: {
568
+ adapterId: String(row.adapter_id),
569
+ accountId: String(row.account_id),
570
+ sessionId: String(row.session_id),
571
+ segmentId: String(row.segment_id),
572
+ ...(row.segment_seq === null || row.segment_seq === undefined
573
+ ? {}
574
+ : { segmentSeq: numberValue(row.segment_seq) }),
575
+ },
576
+ sourceId: String(row.source_id),
577
+ connectionId: String(row.connection_id),
578
+ sourceKey: String(row.source_key),
579
+ ...(row.source_seq_json === null ? {} : { sourceSeq: parseJson<number | string>(row.source_seq_json) }),
580
+ ...(row.domain_tick_json === null ? {} : { domainTick: parseJson<number | string>(row.domain_tick_json) }),
581
+ state: parseJson<TState>(row.state_json),
582
+ events: parseJson<RuntimeInputBatch<TState, TEvent>['events']>(row.events_json),
583
+ ...(row.event_watermark_json === null
584
+ ? {}
585
+ : { eventWatermark: parseJson<number | string>(row.event_watermark_json) }),
586
+ completeness: row.completeness as RuntimeInputBatch['completeness'],
587
+ ...(row.coalescing === 'forbidden' ? { coalescing: 'forbidden' as const } : {}),
588
+ ...(typeof row.observed_at === 'string' ? { observedAt: row.observed_at } : {}),
589
+ receivedAt: String(row.received_at),
590
+ });
591
+ }
592
+
593
+ private initialize(): void {
594
+ this.db.exec(`
595
+ PRAGMA journal_mode = WAL;
596
+ CREATE TABLE IF NOT EXISTS runtime_epochs(
597
+ epoch_seq INTEGER PRIMARY KEY AUTOINCREMENT,
598
+ adapter_id TEXT NOT NULL,
599
+ account_id TEXT NOT NULL,
600
+ session_id TEXT NOT NULL,
601
+ segment_id TEXT NOT NULL,
602
+ segment_seq INTEGER,
603
+ source_id TEXT NOT NULL,
604
+ connection_id TEXT NOT NULL,
605
+ source_key TEXT NOT NULL,
606
+ source_seq_json TEXT,
607
+ domain_tick_json TEXT,
608
+ state_json TEXT NOT NULL,
609
+ events_json TEXT NOT NULL,
610
+ event_watermark_json TEXT,
611
+ completeness TEXT NOT NULL CHECK(completeness IN ('complete', 'best_effort')),
612
+ coalescing TEXT NOT NULL DEFAULT 'allowed' CHECK(coalescing IN ('allowed', 'forbidden')),
613
+ observed_at TEXT,
614
+ received_at TEXT NOT NULL,
615
+ payload_hash TEXT NOT NULL,
616
+ status TEXT NOT NULL CHECK(status IN ('accepted', 'closed')),
617
+ input_events_committed_at TEXT,
618
+ event_commit_watermark INTEGER,
619
+ closed_at TEXT,
620
+ processing_duration_ms INTEGER,
621
+ UNIQUE(adapter_id, account_id, session_id, segment_id, source_id, source_key)
622
+ );
623
+ CREATE INDEX IF NOT EXISTS runtime_epochs_scope_seq
624
+ ON runtime_epochs(adapter_id, account_id, session_id, segment_id, epoch_seq);
625
+ CREATE INDEX IF NOT EXISTS runtime_epochs_scope_event_watermark
626
+ ON runtime_epochs(
627
+ adapter_id, account_id, session_id, segment_id,
628
+ event_commit_watermark DESC, epoch_seq
629
+ );
630
+
631
+ CREATE TABLE IF NOT EXISTS runtime_plugin_outcomes(
632
+ epoch_seq INTEGER NOT NULL,
633
+ plugin_id TEXT NOT NULL,
634
+ invocation_id TEXT NOT NULL,
635
+ outcome TEXT NOT NULL CHECK(outcome IN ('processed', 'noop', 'failed', 'coalesced')),
636
+ reason TEXT,
637
+ duration_ms INTEGER NOT NULL,
638
+ state_count INTEGER NOT NULL,
639
+ event_count INTEGER NOT NULL,
640
+ event_cursor_before INTEGER NOT NULL,
641
+ event_cursor_after INTEGER NOT NULL,
642
+ recorded_at TEXT NOT NULL,
643
+ PRIMARY KEY(epoch_seq, plugin_id)
644
+ );
645
+
646
+ CREATE TABLE IF NOT EXISTS runtime_plugin_progress(
647
+ adapter_id TEXT NOT NULL,
648
+ account_id TEXT NOT NULL,
649
+ session_id TEXT NOT NULL,
650
+ segment_id TEXT NOT NULL,
651
+ plugin_id TEXT NOT NULL,
652
+ completed_through_epoch_seq INTEGER NOT NULL,
653
+ event_cursor INTEGER NOT NULL,
654
+ checkpoint_json TEXT,
655
+ updated_at TEXT NOT NULL,
656
+ PRIMARY KEY(adapter_id, account_id, session_id, segment_id, plugin_id)
657
+ );
658
+
659
+ CREATE TABLE IF NOT EXISTS runtime_plugin_states(
660
+ epoch_seq INTEGER NOT NULL,
661
+ plugin_id TEXT NOT NULL,
662
+ topic TEXT NOT NULL,
663
+ value_json TEXT NOT NULL,
664
+ PRIMARY KEY(epoch_seq, plugin_id, topic)
665
+ );
666
+
667
+ `);
668
+ const epochColumns = new Set(
669
+ this.db.prepare('PRAGMA table_info(runtime_epochs)').all().map((row) => String(row.name)),
670
+ );
671
+ if (!epochColumns.has('segment_seq')) {
672
+ this.db.exec('ALTER TABLE runtime_epochs ADD COLUMN segment_seq INTEGER;');
673
+ }
674
+ if (!epochColumns.has('input_events_committed_at')) {
675
+ this.db.exec('ALTER TABLE runtime_epochs ADD COLUMN input_events_committed_at TEXT;');
676
+ }
677
+ if (!epochColumns.has('event_commit_watermark')) {
678
+ this.db.exec('ALTER TABLE runtime_epochs ADD COLUMN event_commit_watermark INTEGER;');
679
+ }
680
+ if (!epochColumns.has('coalescing')) {
681
+ this.db.exec("ALTER TABLE runtime_epochs ADD COLUMN coalescing TEXT NOT NULL DEFAULT 'allowed';");
682
+ }
683
+ if (!epochColumns.has('processing_duration_ms')) {
684
+ this.db.exec('ALTER TABLE runtime_epochs ADD COLUMN processing_duration_ms INTEGER;');
685
+ }
686
+ const progressColumns = new Set(
687
+ this.db.prepare('PRAGMA table_info(runtime_plugin_progress)').all().map((row) => String(row.name)),
688
+ );
689
+ if (!progressColumns.has('checkpoint_json')) {
690
+ this.db.exec('ALTER TABLE runtime_plugin_progress ADD COLUMN checkpoint_json TEXT;');
691
+ }
692
+ }
693
+ }